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 |
|---|---|---|---|---|---|---|
#!/usr/bin/env python
"""Launch the browser preview app and tie it to the preview parent on Linux."""
from __future__ import annotations
import ctypes
import os
import signal
import sys
_PR_SET_PDEATHSIG = 1
def _arm_parent_death_signal() -> None:
"""Best-effort Linux guard so orphaned preview sessions termina... | agent0ai/a0-connector | devtools/preview_launcher.py | .py | d38502fad843ac8f | 7.5 | 9 |
#!/usr/bin/env python
"""Launch the Agent Zero CLI TUI in a browser via textual-serve.
Usage:
python devtools/serve.py [--port PORT] [--host HOST]
Opens http://localhost:PORT in a browser where you can interact with the
full TUI exactly as you would in a terminal.
"""
from __future__ import annotations
import a... | agent0ai/a0-connector | devtools/serve.py | .py | 164e248e9e985e8e | 7.5 | 9 |
#!/usr/bin/env python
"""Capture an SVG snapshot of the TUI without a live Agent Zero instance.
Usage:
python devtools/snapshot.py [--output PATH] [--width COLS] [--height ROWS] [--wait SECONDS]
Produces a pixel-perfect SVG of the initial screen (connection-pending state).
Useful for verifying layout, footer labe... | agent0ai/a0-connector | devtools/snapshot.py | .py | d2b94cedb3fca3de | 7.5 | 9 |
#!/usr/bin/env python3
"""Consolidate scraped TSTC data into a transaction catalog.
This script reads all SE16 query result files and creates the
transactions.json catalog file.
"""
import json
import sys
from datetime import UTC, datetime
from pathlib import Path
# Add project root to path
project_root = Path(__fil... | Hochfrequenz/sapgui.mcp | scripts/consolidate_catalog.py | .py | b7a426e457a67e07 | 7.45 | 7 |
"""Exploratory live probe for issue #717.
Phase 1: Navigate ``/n/NA2/DCS`` on HF R/3, dump the tree, probe every
``id=`` the updated snapshot emits. Captures the snapshot under
``unittests/desktop/testdata/issue_717/`` for the fixture-based
regression test.
Phase 2: Drive the reporter's end-to-end workflow: expand th... | Hochfrequenz/sapgui.mcp | scripts/explore_issue_717.py | .py | 9b56a4e0b21c5e92 | 7.45 | 7 |
"""Dedicated background thread for SAP GUI COM calls.
All COM calls must happen on the same apartment-threaded context.
This thread runs CoInitialize() once at startup and processes work
items from a queue. Async callers submit callables and await the
result via concurrent.futures.Future + asyncio.wrap_future.
Adapti... | Hochfrequenz/sapgui.mcp | src/sapguimcp/backend/desktop/_com_thread.py | .py | 386337d022adc029 | 7.45 | 7 |
"""Landscape XML parsing — find and parse SAPUILandscape.xml."""
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any
__all__ = ["_find_landscape_path", "_parse_landscape_xml"]
def _find_landscape_path() -> Path | None:
"""Find SAPUILandscape.xml via registry or default ... | Hochfrequenz/sapgui.mcp | src/sapguimcp/backend/desktop/_landscape.py | .py | 65827c8fa99d0875 | 7.45 | 7 |
"""Session registry for desktop (COM) backend.
Mirrors WebGUI's SessionRegistry but stores sapsucker GuiSession objects
instead of Playwright Pages. Stale sessions are detected on access via
a COM probe (no close-event mechanism exists for SAP GUI COM).
"""
from __future__ import annotations
import logging
from typi... | Hochfrequenz/sapgui.mcp | src/sapguimcp/backend/desktop/_session_registry.py | .py | 67156eae591b676f | 7.45 | 7 |
"""Render the SAP GUI element tree as text for ``sap_com_snapshot``.
Extracted from ``DesktopBackend.get_snapshot_with_depth`` so it can be
unit-tested without a live SAP connection.
Output format (per line):
<indent><type>[<name>]: <text-repr> [id=<relative-id>]
The ``id=<relative-id>`` suffix is only added fo... | Hochfrequenz/sapgui.mcp | src/sapguimcp/backend/desktop/_snapshot_render.py | .py | bdb2d8d45441463e | 7.45 | 7 |
"""Tree truncation for LLM-facing tool responses.
Internal backend code always operates on the full tree. This module
provides helpers to truncate the tree to a given depth for tool results,
while reporting how much was hidden.
"""
from __future__ import annotations
from sapsucker.models import ElementInfo
def com... | Hochfrequenz/sapgui.mcp | src/sapguimcp/backend/desktop/_truncation.py | .py | 9a1aa67fe3060402 | 7.45 | 7 |
"""Pydantic models for COM evaluate tool results."""
from pydantic import BaseModel, Field
from sapguimcp.models.base import ToolResult
class ComOperation(ToolResult):
"""Result of a single COM operation."""
element_id: str = Field(default="", description="SAP GUI element path")
action: str = Field(def... | Hochfrequenz/sapgui.mcp | src/sapguimcp/backend/desktop/models/com_results.py | .py | c7482d6c8eef60a5 | 7.45 | 7 |
"""Backend manager — singleton entry point for tools."""
from __future__ import annotations
import asyncio
import logging
import sys
from typing import TYPE_CHECKING, Any, get_args
from sapguimcp.backend.webgui.backend import WebGuiBackend
from sapguimcp.backend.webgui.browser import close_browser_manager, get_brows... | Hochfrequenz/sapgui.mcp | src/sapguimcp/backend/manager.py | .py | 655b95f3e3e4d009 | 7.45 | 7 |
"""
Auto-detect and launch Chrome with CDP debugging flags on Windows.
Used by BrowserManager in connect mode: when no Chrome instance is reachable
on the CDP port, this module finds chrome.exe, launches it with the required
flags, and waits until the CDP endpoint is ready.
"""
from __future__ import annotations
imp... | Hochfrequenz/sapgui.mcp | src/sapguimcp/backend/webgui/chrome_finder.py | .py | c0ccf468823896cc | 7.45 | 7 |
"""JavaScript file loading helpers for the WebGUI backend."""
from functools import lru_cache
from importlib import resources
@lru_cache(maxsize=16)
def load_js(filename: str) -> str:
"""Load a JavaScript file from the sapguimcp.backend.webgui.js package."""
return resources.files("sapguimcp.backend.webgui.j... | Hochfrequenz/sapgui.mcp | src/sapguimcp/backend/webgui/js_helpers.py | .py | 2fd587be36fe087e | 7.45 | 7 |
#!/usr/bin/env python3
"""
Green Invoice API Client
A helper script for common Green Invoice (Morning) API operations:
- Authenticate and get JWT token
- Create documents (invoices, receipts, credit notes)
- Search and list documents
- Manage clients (create, search, list)
Usage:
python3 green-invoice-client.py a... | skills-il/accounting | green-invoice/scripts/green-invoice-client.py | .py | 327599558b42e9ca | 7.52 | 10 |
#!/usr/bin/env python3
"""Backup Google Sheets tabs as local CSV files using the gws CLI.
Exports each tab from a Google Spreadsheet to a separate CSV file in the
specified output directory. Useful for creating accountant-ready backups.
Usage:
python3 scripts/backup-sheets.py --spreadsheet-id SHEET_ID --output-dir ... | skills-il/accounting | gws-israeli-business-sheets/scripts/backup-sheets.py | .py | e126d86fc53a5824 | 7.52 | 10 |
#!/usr/bin/env python3
"""Validate Israeli e-invoice structure and fields.
Checks invoice JSON against SHAAM (Israeli Tax Authority) requirements:
- Required fields presence
- TIN (mispar osek) format and check digit
- Invoice type validity
- VAT calculation accuracy
- Allocation number requirement based on amount thr... | skills-il/accounting | israeli-e-invoice/scripts/validate_invoice.py | .py | bc1973e9208d9be5 | 7.52 | 10 |
from __future__ import annotations
import os
from collections.abc import Awaitable, Callable, Iterable
from typing import Any
from ..ats import detect_provider
from ..state import canonical_url
from .contracts import QueueRowReceiptV1
RowProcessor = Callable[[dict[str, Any]], Awaitable[str]]
_STATUSES = frozenset(
... | Daisuke134/life-manager | apps/job-search-loop/job_search_loop/browser_agent/queue.py | .py | 2ae5cc933f0b9288 | 7.48 | 8 |
"""头像本地缓存:把远端头像下载到数据目录并返回本地 URL。
解决第三方图床(sinaimg / pbs.twimg 等)签名链接过期、外链被拦截导致的头像显示失败。
"""
from __future__ import annotations
from pathlib import Path
import httpx
from .url_safety import safe_get
ALLOWED_TYPES = {
"image/jpeg": "jpg",
"image/png": "png",
"image/webp": "webp",
"image/gif": "gif",
}
... | icekale/vpush | app/avatar_cache.py | .py | 46d138074e7e717d | 7.42 | 6 |
"""推送渠道注册表与统一分发骨架。
新增推送渠道只需四步:
1. 在 app/notifiers/ 下实现 notifier 类(继承 Notifier,channel 属性);
2. 在 CHANNELS 元组里加渠道名;
3. channel_bound / build_channel_notifier 各加一个分支;
4. 前端(Web 推送设置页 + 小程序设置页)的通道选择/状态卡片同步。
分发骨架(成功日志 / 失败日志+重试+告警)由 deliver_post 统一提供,
各调用点(实时推送 / 免打扰汇总 / 管理员通知 / 测试推送 / 失败重试)不再各自复制。
"""
from __future__ imp... | icekale/vpush | app/channels.py | .py | 4a81bb533f1bd257 | 7.42 | 6 |
"""配置加载:YAML 文件 + 环境变量覆盖。"""
from __future__ import annotations
import os
from dataclasses import dataclass, field, fields, is_dataclass
from pathlib import Path
import yaml
@dataclass
class FeishuConfig:
webhook_url: str = ""
app_id: str = ""
app_secret: str = ""
bot_name: str = ""
# 凭据加密密钥(Fer... | icekale/vpush | app/config.py | .py | 3031980f765b3fe3 | 7.42 | 6 |
"""抓取器基础:Post 数据类与公共文本清理。"""
from __future__ import annotations
import email.utils
import html
import logging
import re
import threading
import time
from dataclasses import dataclass, field, replace
from datetime import datetime, timedelta, timezone
logger = logging.getLogger(__name__)
# 项目面向中文社交平台,发布时间统一按北京时间展示,避免依... | icekale/vpush | app/fetchers/base.py | .py | 7e281feedb738489 | 7.42 | 6 |
"""腾讯 ima 只读探针:解析官方 OpenAPI 响应,不负责发请求。"""
from __future__ import annotations
from collections import Counter
from typing import Any
from urllib.parse import urlparse
def _as_dict(value: Any) -> dict[str, Any]:
return value if isinstance(value, dict) else {}
def _as_list(value: Any) -> list[Any]:
return val... | icekale/vpush | app/fetchers/ima_inspect.py | .py | 05b73151bb5328d5 | 7.92 | 6 |
"""雪球用户原创动态抓取。"""
from __future__ import annotations
import hashlib
import json
import logging
import os
import re
import tempfile
from pathlib import Path
import httpx
from ..avatar_cache import cache_avatar
from .base import (
Fetcher,
Post,
ThreadLocalClient,
catchup_pages,
format_published_at... | icekale/vpush | app/fetchers/xueqiu.py | .py | c4198bd1f1981434 | 7.42 | 6 |
"""知识星球 App 混合加密(对应逆向 `tc/a.java`,G3)。
App 用「随机 AES 密钥包裹 + RSA(服务公钥) 再包裹」对 POST/登录体加密:
1. 生成 16 字节随机 AES 密钥 + 16 字节随机 IV(AES-128-CBC/PKCS7)
2. 用该密钥 AES/CBC/PKCS7 加密 JSON 明文,得到 Base64 密文
3. 用内置 RSA 公钥 RSA/ECB/PKCS1Padding 加密 AES 密钥
纯读 GET 不需要加密(探针已验证),此模块给未来含体/登录 POST 用。
实现对齐 tc/a.java:Base64 用 NO_WRAP(Java flag... | icekale/vpush | app/fetchers/zsxq_crypto.py | .py | b412b9d129b9b0f0 | 7.42 | 6 |
"""知识星球只读探针:解析网页版 API 响应,不负责发请求。"""
from __future__ import annotations
from collections import Counter
from typing import Any
def access_token_from_cookie(raw: str) -> str:
"""接受裸 token 或完整 Cookie 头,只取出 zsxq_access_token。"""
text = (raw or "").strip()
if not text:
raise ValueError("缺少知识星球登录态")
... | icekale/vpush | app/fetchers/zsxq_inspect.py | .py | 50035fe23e9e4826 | 7.92 | 6 |
"""可选 LLM:站点默认 Grok(管理员推送设置),用户可自配覆盖。
设计要点:
- 失败静默降级:任何异常只记日志并返回 None,调用方回退原逻辑;
- 只传帖文标题/大V/平台/摘要,不传用户隐私字段。
"""
from __future__ import annotations
import json
import logging
import re
import time
logger = logging.getLogger(__name__)
# 摘要通常几秒到十几秒;标记解析走 thinking + JSON,16 条实测约 150s。
DEFAULT_CHAT_TIMEOUT = 60
MARK_RES... | icekale/vpush | app/llm.py | .py | d0be2630bd23c473 | 7.42 | 6 |
"""统一日志配置:级别可控、内存环形缓冲(网页查看)、可选文件轮转。"""
from __future__ import annotations
import copy
import logging
import logging.handlers
import os
import re
import threading
from collections import deque
from pathlib import Path
LOG_FORMAT = "%(asctime)s.%(msecs)03d %(levelname)s %(name)s [%(threadName)s] %(message)s"
DATE_FORMA... | icekale/vpush | app/logging_setup.py | .py | ebb5d991126d693a | 7.42 | 6 |
"""通知器基类。"""
from __future__ import annotations
from ..fetchers.base import Post
def why_badges(favorite: bool = False, keyword: bool = False) -> str:
"""新帖通知的「为什么推给你」徽标行:特别关注 / 命中关键词。"""
return " · ".join(
b
for b in (("🔔 特别关注" if favorite else ""), ("🔑 命中关键词" if keyword else ""))
... | icekale/vpush | app/notifiers/base.py | .py | 911abfbfa336fd0b | 7.42 | 6 |
"""动态广场数据源显隐:自动(启用大V 为 0 则藏)/ 显示 / 隐藏。"""
from __future__ import annotations
import json
from .db import DB
# 与前端 PLATFORM_TABS 对齐(不含 ima:广场没有 ima 角标)
PLAZA_PLATFORMS = ("xueqiu", "combination", "weibo", "twitter", "zsxq")
PLAZA_MODES = ("auto", "show", "hide")
PLAZA_VISIBILITY_KEY = "plaza_source_visibility"
def ... | icekale/vpush | app/plaza.py | .py | ad2ad2ca3970e864 | 7.42 | 6 |
"""Telegram Rich Message 运行时开关:后台设置优先,未保存过则跟 yaml/env。"""
from __future__ import annotations
SETTING_KEY = "config_telegram_rich_messages"
def parse_telegram_rich_setting(raw: str | None, default: bool) -> bool:
if raw is None or raw == "":
return bool(default)
return str(raw).strip().lower() not in ... | icekale/vpush | app/telegram_rich_flag.py | .py | 96a2579805de9e7e | 7.42 | 6 |
"""URL 下载安全校验:防止服务端抓取/下载时被引导访问内网地址(SSRF)。
头像缓存与飞书图片上传会下载抓取内容里携带的 URL(帖子图片、头像来自
第三方平台/RSSHub),这些地址不可信。统一经 is_safe_http_url / safe_get
校验:仅允许 http/https、拒绝环回/私网/链路本地/云元数据等保留网段,
跟随重定向时逐跳重新校验。
"""
from __future__ import annotations
import ipaddress
import socket
from urllib.parse import urljoin, urlparse, urlunparse
imp... | icekale/vpush | app/url_safety.py | .py | a42eceb3d061cf2d | 7.42 | 6 |
from enum import Enum
class Interval(str, Enum):
"""
标准 K 线周期。
"""
MINUTE_1 = "1m"
MINUTE_5 = "5m"
MINUTE_15 = "15m"
MINUTE_30 = "30m"
MINUTE_60 = "60m"
DAY_1 = "1d"
WEEK_1 = "1w"
MONTH_1 = "1M"
class PEType(str, Enum):
"""
市盈率类型。
"""
STATIC = "sta... | artinte/stock-analysis | common/constants.py | .py | 0c559efcf6b32a2a | 7.54 | 11 |
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
@dataclass(slots=True)
class IndicatorPoint:
"""
技术指标时间点数据基类。
所有技术指标都对应某一个证券、
某一个时间点,因此统一包含:
symbol
timestamp
具体指标由子类实现。
"""
symbol: str
timestamp: datetime
@sta... | artinte/stock-analysis | core/models/indicators/base.py | .py | 9d20844e39a64945 | 7.54 | 11 |
from __future__ import annotations
from dataclasses import dataclass
from core.models.indicators.base import IndicatorPoint
@dataclass(slots=True)
class BollingerPoint(IndicatorPoint):
"""
Bollinger Bands(布林带)在某个时间点的计算结果。
upper:
上轨
middle:
中轨
lower:
下轨
bandwidth:
... | artinte/stock-analysis | core/models/indicators/bollinger.py | .py | 24cfb192b32916c7 | 7.54 | 11 |
from __future__ import annotations
from dataclasses import dataclass
from core.models.indicators.base import IndicatorPoint
@dataclass(slots=True)
class MACDPoint(IndicatorPoint):
"""
MACD 指标在某个时间点的计算结果。
DIF:
快速 EMA - 慢速 EMA
DEA:
DIF 的 EMA
HIST:
DIF - DEA
"""
... | artinte/stock-analysis | core/models/indicators/macd.py | .py | 5041848e0ab2f196 | 7.54 | 11 |
from __future__ import annotations
from dataclasses import dataclass
from core.models.indicators.base import IndicatorPoint
@dataclass(slots=True)
class MovingAveragePoint(IndicatorPoint):
"""
移动平均线在某个时间点的计算结果。
period:
移动平均周期,例如:
MA5
MA10
MA20
MA... | artinte/stock-analysis | core/models/indicators/moving_average.py | .py | eb0d7cd8275eeb74 | 7.54 | 11 |
from __future__ import annotations
from dataclasses import dataclass
from core.models.indicators.base import IndicatorPoint
@dataclass(slots=True)
class RSIPoint(IndicatorPoint):
"""
RSI 指标在某个时间点的计算结果。
RSI:
Relative Strength Index
相对强弱指标
"""
rsi: float | None = None
def di... | artinte/stock-analysis | core/models/indicators/rsi.py | .py | c3cef6c4ba1d5797 | 7.54 | 11 |
from __future__ import annotations
from dataclasses import dataclass
from core.models.indicators.base import IndicatorPoint
@dataclass(slots=True)
class WilliamsRPoint(IndicatorPoint):
"""
Williams %R 指标在某个时间点的计算结果。
Williams %R 通常取值范围:
[-100, 0]
"""
value: float | None = None
def d... | artinte/stock-analysis | core/models/indicators/williams.py | .py | 1f5af1a2f7931909 | 7.54 | 11 |
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
from common.constants import IndustryStandard
@dataclass(slots=True)
class Industry:
"""股票所属行业。"""
code: Optional[str] = None
name: Optional[str] = None
level_1: Optional[str] = None
level_2: Optiona... | artinte/stock-analysis | core/models/industry.py | .py | 4460d0b28b7a1312 | 7.54 | 11 |
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from common.constants import Interval
@dataclass(slots=True)
class Kline:
"""
标准 K 线数据模型。
描述证券在一个指定时间周期内的 OHLCV 行情数据。
不同数据源由 Gateway 统一转换为该结构。
时间约定:
timestamp 表示该 K 线周期的时间。
例如:
... | artinte/stock-analysis | core/models/kline.py | .py | 09af23215365b440 | 7.54 | 11 |
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from common.enums.exchange import Exchange
from utils.stock_mapping import exchange_name
@dataclass(slots=True)
class Stock:
"""
股票基础信息,描述证券本身的静态属性。
不包含:行业、新闻、公告、财务、行情、估值
数据流:
DataSource -> StockG... | artinte/stock-analysis | core/models/stock.py | .py | 9f77250410036f42 | 7.54 | 11 |
import logging
from abc import ABC, abstractmethod
from typing import Any
# 统一日志格式
logging.basicConfig(level=logging.INFO, format='%(asctime)s - [%(levelname)s] - %(message)s')
logger = logging.getLogger("MonitorEngine")
class MonitorTask(ABC):
"""
监控任务抽象基类。
商业化设计:一个完整的监控生命周期 = 抓取数据 -> 检查条件 -> 执行动作。
"... | artinte/stock-analysis | core/monitor/base_monitor.py | .py | 4cb89c88f6217590 | 7.54 | 11 |
import asyncio
from typing import List
from core.monitor.base_monitor import MonitorTask, logger
class ConcurrentMonitorEngine:
def __init__(self):
self.tasks: List[MonitorTask] = []
self._running_tasks = []
self.is_running = False
def register_task(self, task: MonitorTask):
""... | artinte/stock-analysis | core/monitor/engine.py | .py | 384589420145d7c6 | 7.54 | 11 |
import asyncio
import random
from core.monitor.base_monitor import MonitorTask, logger
class XMonitorPlugin(MonitorTask):
"""插件 A:假装这是一个 X.com 监控器"""
async def fetch(self) -> str:
# 实际商业开发中,这里是 aiohttp.get("https://x.com...")
await asyncio.sleep(0.1) # 模拟网络请求耗时
mock_tweets = ["正常推文", "包... | artinte/stock-analysis | core/monitor/plugins.py | .py | de3c0c484a251286 | 7.54 | 11 |
from typing import Dict, Any, List
class PnlCalculator:
"""
商业化标准的持仓与盈亏计算器(采用移动平均成本法卷算)。
支持计算:当前持仓量、平均开仓成本、已实现盈亏、浮动盈亏。
"""
@staticmethod
def calculate_position_and_pnl(orders: List[Dict[str, Any]], current_market_price: float = None) -> Dict[str, Any]:
position = 0.0 # 当前持仓数量
... | artinte/stock-analysis | core/trading/pnl_calculator.py | .py | 8d48f5a8a9eb20bd | 7.54 | 11 |
import os
from typing import List, Any
def print_fetched_articles(
articles: List[Any], max_content_len: int = 500, include_content: bool = False
) -> None:
"""
格式化打印爬虫抓取到的原生数据(控制台预览)
:param articles: 抓取到的 ArticleItem 列表
:param max_content_len: 正文打印的最大字符数,默认 500 字
"""
total = len(articles... | artinte/stock-analysis | crawler/common/data_printer.py | .py | 2846d9da11a8d8aa | 7.54 | 11 |
from abc import ABC, abstractmethod
from typing import List
from urllib.parse import urljoin
from playwright.async_api import Page
from crawler.core.browser import browser_manager
from crawler.core.models import ArticleItem
class BaseSpider(ABC):
name: str = "base_spider"
start_url: str = ""
@abstractmet... | artinte/stock-analysis | crawler/core/base_spider.py | .py | 59d1a0f24e47a940 | 7.54 | 11 |
from typing import Optional
from playwright.async_api import Browser, Page, async_playwright
class BrowserManager:
"""全局单例浏览器管理器,避免反复启动 Browser 实例耗尽内存"""
def __init__(self):
self._playwright = None
self._browser: Optional[Browser] = None
async def start(self):
if not self._browse... | artinte/stock-analysis | crawler/core/browser.py | .py | 9b06e7598e553fed | 7.54 | 11 |
import easyocr
import pathlib
from PIL import Image, ImageEnhance
import numpy
import cv2
# 保持 reader 全局或在函数外初始化以避免重复加载模型
reader = easyocr.Reader(["ch_sim", "en"])
def _calculate_iou(box1, box2):
"""
计算两个边界框的 IoU (Intersection over Union)
边界框格式为:[[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
"""
x1_min... | artinte/stock-analysis | crawler/phone/ocr.py | .py | 57e2464fdc51aebb | 7.54 | 11 |
import os
import asyncio
from typing import List, Union
from playwright.async_api import async_playwright, Page, BrowserContext
class XiaohongshuArticlePublisher:
"""小红书专栏/文章(纯文本)全自动发布脚本"""
def __init__(self, user_data_dir: str = "./xhs_cookie_store"):
self.user_data_dir = os.path.abspath(user_data_d... | artinte/stock-analysis | crawler/pipelines/auto_post_xiaohongshu.py | .py | ddb83e1e3e5fbfb2 | 7.54 | 11 |
from typing import Any
class ContentPublisherPipeline:
"""
内容发布管道
负责将生成好的文章发布到目标平台
"""
def __init__(self):
pass
def publish(self, article: Any):
"""
发布文章
"""
title = getattr(article, "title", "")
content = getattr(article, "content", "")
... | artinte/stock-analysis | crawler/pipelines/content_publisher.py | .py | e07dd28dacec1f05 | 7.54 | 11 |
import asyncio
import re
from typing import Any, List
from openai import OpenAI
class ContentSummaryPipeline:
"""文章内容提炼/生成摘要 Pipeline
专门用于为单条新闻/文章的 content 字段生成精炼 summary 字段
"""
def __init__(self, model_name, concurrency_limit: int = 5):
"""初始化 Pipeline
:param concurrency_limit: AI AP... | artinte/stock-analysis | crawler/pipelines/content_summary.py | .py | 3ac00fb26d8c9100 | 7.54 | 11 |
#!/usr/bin/env python3
# coding: utf-8
"""Convert ASTRAL extended support annotations to a single selected label.
Example input annotation:
'[q1=0.5;q2=0.25;q3=0.25;f1=1.0;...;pp1=0.45;...;QC=2;EN=2.0]'
This script replaces each annotation with one selected key value (e.g., q1).
It is robust to field order changes... | kfuku52/genegalleon | workflow/support/extract_astral_support_label.py | .py | e220f407dfe2a539 | 7.42 | 6 |
"""Test fixtures for vivosun_thermo integration."""
import sys
import types
from pathlib import Path
from typing import Generic, TypeVar
from unittest.mock import AsyncMock, MagicMock, Mock, patch
import pytest
_DataT = TypeVar("_DataT")
# Mock pycares for python 3.13 (works fine as is on 3.14)
pycares = types.Modu... | sormy/vivosun-thermo-hass | tests/conftest.py | .py | 1f9937a4a86e8fa4 | 8.12 | 16 |
"""Tests for vivosun_thermo config flow."""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from homeassistant.components.bluetooth import BluetoothServiceInfoBleak
from homeassistant.const import ATTR_NAME
from custom_components.vivosun_thermo.config_flow import VivosunThermoConfigFlow
# pyrigh... | sormy/vivosun-thermo-hass | tests/test_config_flow.py | .py | 33e6b2b143880927 | 7.12 | 16 |
"""The lookup tables must agree with the shape the coordinator decodes."""
from custom_components.vivosun_thermo.const import PROBE_TYPES, SENSOR_TYPES
from custom_components.vivosun_thermo.coordinator import ProbeData, SensorData
class TestTablesMatchDecodedShape:
"""Entities are built from the tables but read ... | sormy/vivosun-thermo-hass | tests/test_const.py | .py | ae65092a0004909b | 8.12 | 16 |
"""Tests for vivosun_thermo coordinator."""
from asyncio import TimeoutError as AsyncTimeoutError
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from bleak.exc import BleakError
from homeassistant.helpers.update_coordinator import UpdateFailed
from custom_components.vivosun_thermo.coordinator im... | sormy/vivosun-thermo-hass | tests/test_coordinator.py | .py | dc56bfe22fcbb3fc | 7.12 | 16 |
"""Tests for vivosun_thermo setup and teardown."""
from unittest.mock import AsyncMock
import pytest
from homeassistant.const import Platform
from custom_components.vivosun_thermo import async_setup_entry, async_unload_entry
class TestVivosunThermoSetup:
"""Test the config entry lifecycle."""
async def te... | sormy/vivosun-thermo-hass | tests/test_init.py | .py | 75db4bfaa6f87d52 | 8.12 | 16 |
"""The integration manifest must agree with the packaging metadata beside it."""
import json
import tomllib
from pathlib import Path
import pytest
from custom_components.vivosun_thermo.const import DOMAIN
_ROOT = Path(__file__).parent.parent
_CUSTOM_COMPONENTS = _ROOT / "custom_components"
_MANIFEST = _CUSTOM_COMPO... | sormy/vivosun-thermo-hass | tests/test_manifest.py | .py | 1dda22a7b25f3361 | 8.12 | 16 |
"""Tests for vivosun_thermo sensor."""
from unittest.mock import MagicMock
import pytest
from homeassistant.components.sensor import SensorDeviceClass, SensorStateClass
from homeassistant.const import PERCENTAGE, UnitOfTemperature
from custom_components.vivosun_thermo.const import DOMAIN, SENSOR_TYPES
from custom_co... | sormy/vivosun-thermo-hass | tests/test_sensor.py | .py | be66c55fd613249b | 7.12 | 16 |
import asyncio
import os
from logging.config import fileConfig
from alembic import context
from dotenv import load_dotenv
from sqlalchemy.ext.asyncio import create_async_engine
import hiresense.shared.infrastructure.registry # noqa: F401 — registers all ORM models
from hiresense.shared.infrastructure.database import... | StevSant/HireSense | backend/alembic/env.py | .py | 28706820a0b4e7b2 | 7.57 | 13 |
"""add linkedin/github/portfolio URLs to profiles
Revision ID: 009
Revises: 008
Create Date: 2026-05-25
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "009"
down_revision: Union[str, None] = "008"
branch_labels: Union[str, Sequence[str], None] = None
depends_on... | StevSant/HireSense | backend/alembic/versions/009_add_profile_links.py | .py | 008f90385bb6ce75 | 7.57 | 13 |
"""add countries + remote_modality to ingested_jobs
Carries the source's hybrid/remote/on-site signal and country list through to
the API so the strict-location filter can reject hybrid/on-site postings in
mismatched countries instead of relying on naive substring matching.
Revision ID: 012
Revises: 011
Create Date: ... | StevSant/HireSense | backend/alembic/versions/012_add_ingested_jobs_remote_modality.py | .py | 03640ef62afda4d3 | 7.57 | 13 |
"""create vector_embeddings (pgvector)
Generic vector store for semantic search: (id, embedding, metadata). Backs the
VectorStorePort / PgVectorStore adapter and replaces the in-memory cosine cache
for job embeddings. Requires the Postgres `pgvector` extension.
Revision ID: 014
Revises: 013
Create Date: 2026-05-30
""... | StevSant/HireSense | backend/alembic/versions/014_create_vector_embeddings.py | .py | 02d0c24e36a4cc36 | 7.57 | 13 |
"""create preference tables (feedback_signals, preference_models)
Backs the preference learning loop. Embeddings are stored as JSON float arrays
(the ANN query targets the separate vector_embeddings table; taste math is in
Python), so no pgvector column type is used here.
Revision ID: 016
Revises: 015
Create Date: 20... | StevSant/HireSense | backend/alembic/versions/016_create_preference_tables.py | .py | 9cac414320fb61a8 | 7.57 | 13 |
"""create application_status_history (+ backfill one seed row per existing app)
Backs the funnel analytics. Each tracked-application status change appends a
row (written transactionally by the tracking repository). Existing applications
are seeded with a single NULL->current_status row timestamped at applied_at or
cre... | StevSant/HireSense | backend/alembic/versions/017_create_application_status_history.py | .py | e6ba02916698bfdf | 7.57 | 13 |
"""create digests (auto-hunt run log + top-N new-match snapshots)
Revision ID: 018
Revises: 017
Create Date: 2026-05-31
"""
from typing import Sequence, Union
from alembic import op
revision: str = "018"
down_revision: Union[str, None] = "017"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[... | StevSant/HireSense | backend/alembic/versions/018_create_digests.py | .py | 39fd6cf5463e7276 | 7.57 | 13 |
"""create outreach_events (append-only outreach log per application)
Revision ID: 019
Revises: 018
Create Date: 2026-05-31
"""
from typing import Sequence, Union
from alembic import op
revision: str = "019"
down_revision: Union[str, None] = "018"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Uni... | StevSant/HireSense | backend/alembic/versions/019_create_outreach_events.py | .py | 523a3bd76659e7da | 7.57 | 13 |
"""add weight_overrides to preference_models (Phase 2 dimension-weight nudging)
Adds a JSONB column holding ``{dimension_name: integer_delta}`` applied on top
of each scorer's base weight in the matching composite. Nullable with no
backfill: existing rows read back as NULL and the repository maps that to "no
overrides... | StevSant/HireSense | backend/alembic/versions/020_add_preference_weight_overrides.py | .py | b9a12751c5d38a94 | 7.57 | 13 |
"""add dimension_scores to feedback_signals (Phase 2 nudge activation)
Adds a JSONB column holding ``{dimension_name: score}`` snapshotted from the
matching dimension scorers at outcome time. Nullable with no backfill: existing
rows (and explicit signals) read back as NULL, which the repository maps to
domain ``None``... | StevSant/HireSense | backend/alembic/versions/021_add_feedback_signal_dimension_scores.py | .py | b619b679dcce121a | 7.57 | 13 |
"""ensure vector_embeddings exists (drift repair)
Reconciliation migration for environments whose `alembic_version` advanced past
revision 014 without its `vector_embeddings` table ever materializing on the
volume (observed on a long-lived dev DB stamped at a later revision; see the
2026-05/06 alembic-drift fixes). Mi... | StevSant/HireSense | backend/alembic/versions/023_ensure_vector_embeddings.py | .py | 848a051bea79fa7a | 7.57 | 13 |
"""add quality + quality_reason to ingested_jobs
Intrinsic, profile-independent job-quality classification (see JobQuality):
"ok" | "low_quality" | "spam". Defaults to "ok" with a server_default so every
existing row backfills to "ok" and nothing is hidden retroactively. The
ingestion orchestrator (re)classifies jobs ... | StevSant/HireSense | backend/alembic/versions/024_add_job_quality.py | .py | 620ee22886681fd8 | 7.57 | 13 |
"""index vector_embeddings metadata bucket
PgVectorStore.search() always filters by metadata->>'bucket' ("boards" /
"portals") before the HNSW ANN ordering. Without an index that filter is a
sequential scan over every vector row; an expression index keeps the filtered
ANN search cheap as the corpus grows.
Revision ID... | StevSant/HireSense | backend/alembic/versions/025_add_vector_embeddings_bucket_index.py | .py | 2bdeb2c47532d228 | 7.57 | 13 |
"""replace outreach_events application_id index with composite (application_id, created_at)
Revision ID: 028
Revises: 027
Create Date: 2026-06-10
"""
from typing import Sequence, Union
from alembic import op
revision: str = "028"
down_revision: Union[str, None] = "027"
branch_labels: Union[str, Sequence[str], None]... | StevSant/HireSense | backend/alembic/versions/028_outreach_events_application_created_index.py | .py | fafabfc6d0432127 | 7.57 | 13 |
"""add include_in_matching column to portfolio_projects
Revision ID: 029
Revises: 028
Create Date: 2026-06-13
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "029"
down_revision: Union[str, None] = "028"
branch_labels: Union[str, Sequence[str], None] = None
depe... | StevSant/HireSense | backend/alembic/versions/029_add_portfolio_projects_include_in_matching.py | .py | aa017ef9059afb06 | 7.57 | 13 |
"""add apply_profile JSON column to profiles
Revision ID: 031
Revises: 030
Create Date: 2026-06-14
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "031"
down_revision: Union[str, None] = "030"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Uni... | StevSant/HireSense | backend/alembic/versions/031_add_profiles_apply_profile.py | .py | b273d21e96c93dbb | 7.57 | 13 |
"""add machine_translated to profiles
Revision ID: 032
Revises: 031
Create Date: 2026-06-15
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "032"
down_revision: Union[str, None] = "031"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str,... | StevSant/HireSense | backend/alembic/versions/032_add_profile_machine_translated.py | .py | cdab1995d428238c | 7.57 | 13 |
"""add autopilot_drafts
Revision ID: 035
Revises: 034
Create Date: 2026-06-22
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "035"
down_revision: Union[str, None] = "034"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str]... | StevSant/HireSense | backend/alembic/versions/035_add_autopilot_drafts.py | .py | 333dee180be158b4 | 7.57 | 13 |
"""add expiry_date to ingested_jobs
Revision ID: 036
Revises: 035
Create Date: 2026-07-04
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "036"
down_revision: Union[str, None] = "035"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, S... | StevSant/HireSense | backend/alembic/versions/036_add_ingested_jobs_expiry_date.py | .py | 41f38c56ef5c467a | 7.57 | 13 |
"""unique constraint on autopilot_drafts.job_id
Makes a reserved draft the idempotency guard for the autopilot pipeline: two
concurrent runs racing on the same job can no longer both insert a draft row.
Pre-existing duplicate rows (from before this guard existed) are collapsed to a
single row per job_id — the earlies... | StevSant/HireSense | backend/alembic/versions/038_unique_autopilot_drafts_job_id.py | .py | ce6f6fc2f0dbb447 | 7.57 | 13 |
"""add manual application listing metadata
Revision ID: 039
Revises: 038
Create Date: 2026-07-21
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "039"
down_revision: Union[str, None] = "038"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union... | StevSant/HireSense | backend/alembic/versions/039_add_manual_application_metadata.py | .py | cc8fb79c182c455b | 7.57 | 13 |
"""add structured work-authorization facts to ingested jobs
Revision ID: 041
Revises: 040
Create Date: 2026-07-22
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "041"
down_revision: Union[str, None] = "040"
branch_labels: Union[str, Sequence[str], None] = None
... | StevSant/HireSense | backend/alembic/versions/041_add_ingested_job_work_authorization_facts.py | .py | 0d85658a8b2e68b2 | 7.57 | 13 |
"""create ingestion_runs table
Revision ID: 045
Revises: 044
Create Date: 2026-08-19
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "045"
down_revision: Union[str, None] = "044"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequen... | StevSant/HireSense | backend/alembic/versions/045_create_ingestion_runs.py | .py | 870289fe04367c02 | 7.57 | 13 |
"""purge RemoteOK residue after source retirement
Revision ID: 048
Revises: 047
Create Date: 2026-08-24
"""
from typing import Sequence, Union
from alembic import op
revision: str = "048"
down_revision: Union[str, None] = "047"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[st... | StevSant/HireSense | backend/alembic/versions/048_purge_remoteok_residue.py | .py | 5e19d9cb365f3a87 | 7.57 | 13 |
"""Offline-synthetic benchmark for AnchorKV-adapted anchor-residual compression.
AnchorKV (arXiv:2608.02901v1, no verified peer-reviewed venue as of
2026-08-20 — see paper/research/surveys/NEW_METHOD_SURVEY_V22.md for the
one-time venue-exception rationale) never drops a token: every position
stays in the softmax, rep... | rajveer43/VeloxQuant-MLX | benchmark_scripts/benchmark_anchorkv.py | .py | 0ee7bb344c2a516f | 7.59 | 14 |
"""Benchmark: KV-cache block pool allocator vs naive per-request allocation.
Issue #249 asks for a KV-cache-specific block pool allocator and a
comparison against the current (naive) implementation on:
- allocation latency
- peak memory usage
- fragmentation
- tokens/sec
- number of allocations per request
... | rajveer43/VeloxQuant-MLX | benchmark_scripts/benchmark_block_pool.py | .py | f8ebc5bc56063097 | 7.59 | 14 |
"""Real-model validation for KIVI Metal kernel warmup (issue #250, PR #268).
Runs mlx-community/Llama-3.2-1B-Instruct-4bit (already cached locally, small
enough to iterate on) through the real serving path --
``patch_model_kv_cache`` -> ``KVCacheBuilder.for_model`` -> ``mlx_lm.generate``
-- and measures, for fp16 base... | rajveer43/VeloxQuant-MLX | benchmark_scripts/benchmark_kivi_warmup.py | .py | 594d9a2b82dc749e | 7.59 | 14 |
"""CSV file data provider — load OHLCV from local files.
Usage:
from income_desk.adapters.csv_provider import CSVProvider
from income_desk import MarketAnalyzer, DataService
ds = DataService()
ds._registry.register_priority(CSVProvider("/path/to/data/"))
ma = MarketAnalyzer(data_service=ds)
#... | nitinblue/income-desk | income_desk/adapters/csv_provider.py | .py | a7dced98ab9c0e9f | 7.63 | 17 |
"""Calibration functions — pure computation for prediction accuracy tracking.
All functions are stateless. eTrading captures predictions and outcomes,
passes them in as lists, and receives calibration analysis back.
No I/O, no state, no side effects.
"""
from __future__ import annotations
import math
import statisti... | nitinblue/income-desk | income_desk/benchmarking/calibration.py | .py | 6954a906216f6b85 | 7.63 | 17 |
"""Benchmarking models — Pydantic schemas for prediction tracking and calibration."""
from __future__ import annotations
from pydantic import BaseModel
class PredictionRecord(BaseModel):
"""What income_desk predicted at trade entry. eTrading captures and stores this."""
trade_id: str
ticker: str
ti... | nitinblue/income-desk | income_desk/benchmarking/models.py | .py | 222a881449beecc6 | 7.63 | 17 |
"""Alpaca broker integration — optional sub-package.
Requires ``alpaca-py`` SDK: ``pip install 'market-analyzer[alpaca]'``
Works with free tier (no funding required).
Get free API keys at: https://app.alpaca.markets/signup
Usage::
from income_desk.broker.alpaca import connect_alpaca
market_data, metrics, a... | nitinblue/income-desk | income_desk/broker/alpaca/__init__.py | .py | 1cd57f0be1547f8d | 7.63 | 17 |
"""Alpaca account provider.
Reads account balance and buying power from Alpaca's trading API.
"""
from __future__ import annotations
import logging
from income_desk.broker.base import AccountProvider
from income_desk.models.quotes import AccountBalance
logger = logging.getLogger(__name__)
class AlpacaAccount(Acc... | nitinblue/income-desk | income_desk/broker/alpaca/account.py | .py | 2fee1c5eb50cb4a0 | 7.63 | 17 |
"""Alpaca market metrics provider.
Alpaca does not natively provide IV rank or IV percentile (those are
TastyTrade-specific metrics). This provider computes a simple IV rank
approximation from Alpaca's historical option data when available,
and returns None for unavailable fields.
"""
from __future__ import annotatio... | nitinblue/income-desk | income_desk/broker/alpaca/metrics.py | .py | eb08854097dc3616 | 7.63 | 17 |
"""Dhan broker integration for India NSE/NFO markets.
Provides live option quotes with Greeks, account balance, and metrics
for all NSE F&O instruments via DhanHQ REST API.
Credentials: client_id + access_token (from https://dhanhq.co/).
- Standalone: args, env vars (DHAN_CLIENT_ID / DHAN_ACCESS_TOKEN),
or ~/.incom... | nitinblue/income-desk | income_desk/broker/dhan/__init__.py | .py | bab6a28ab93d95c0 | 7.63 | 17 |
"""Dhan account provider — balance and buying power via DhanHQ fund limits API.
DhanHQ get_fund_limits() returns (via dhanhq SDK wrapper)::
{
"status": "success",
"data": {
"dhanClientId": "...",
"availabelBalance": 98440.0, # available cash (note Dhan typo)
"... | nitinblue/income-desk | income_desk/broker/dhan/account.py | .py | f77d898a7982d27d | 7.63 | 17 |
"""Dhan market metrics provider — IV and liquidity metrics for India instruments.
DhanHQ provides IV natively in the option chain (as percentage).
We extract ATM IV as iv_30_day proxy and compute a rough IV rank from the
chain's IV spread (same approximation as Zerodha, but with real IV data).
IV rank (true historica... | nitinblue/income-desk | income_desk/broker/dhan/metrics.py | .py | 59d2f16e36926644 | 7.63 | 17 |
"""Dhan watchlist provider — registry-based fallback.
Dhan does not expose a watchlist management API (as of SDK 2.1.0).
We implement the WatchlistProvider interface using the market registry
presets (india_fno, india_index, nifty50, etc.) as named watchlists.
If a requested name matches a registry preset, we return ... | nitinblue/income-desk | income_desk/broker/dhan/watchlist.py | .py | 64621c0873e9dd61 | 7.63 | 17 |
"""IBKR account provider via ib_insync."""
from __future__ import annotations
import logging
from income_desk.broker.base import AccountProvider
from income_desk.models.quotes import AccountBalance
logger = logging.getLogger(__name__)
class IBKRAccount(AccountProvider):
"""Account balance and buying power via... | nitinblue/income-desk | income_desk/broker/ibkr/account.py | .py | 6d0517b43b1bef33 | 7.63 | 17 |
"""Schwab account provider via schwab-py."""
from __future__ import annotations
import logging
from income_desk.broker.base import AccountProvider
from income_desk.models.quotes import AccountBalance
logger = logging.getLogger(__name__)
class SchwabAccount(AccountProvider):
"""Account balance and buying power... | nitinblue/income-desk | income_desk/broker/schwab/account.py | .py | 04b9f3dacbb8f7e8 | 7.63 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.