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
""" EventSource 基类 — 事件产生端 事件源负责产生事件并发射到 EventEngine。 用法: from evebus.sources import EventSource class MySource(EventSource): def __init__(self, name="my_source"): super().__init__(name) async def start(self): self._running = True while self._running: ...
openbot-coder/pyevebus
python/evebus/sources/base.py
.py
f66f2f3ef5e6136b
7
0
""" TimerSource — 定时事件源 定期发射事件,用于心跳、定时任务等。 用法: from evebus.sources import TimerSource timer = TimerSource( name="heartbeat", topic="system.heartbeat", interval_ms=5000, # 5秒 payload={"status": "ok"} ) engine.add_source(timer) """ import asyncio from .base import Eve...
openbot-coder/pyevebus
python/evebus/sources/timer.py
.py
0703a9afc4e453fe
7
0
""" WebhookSource — HTTP Webhook 事件源 监听 HTTP POST 请求,将请求体转换为事件。 用法: from evebus.sources import WebhookSource webhook = WebhookSource( name="webhook", path="/events/ingest", topic_prefix="webhook", ) engine.add_source(webhook) # 外部 POST /events/ingest → engine.emit("webhoo...
openbot-coder/pyevebus
python/evebus/sources/webhook.py
.py
ae6b9e2aceb3b7d1
7
0
""" WebSocketSource — WebSocket 事件源 连接 WebSocket 服务端,将消息转换为事件。 用法: from evebus.sources import WebSocketSource ws = WebSocketSource( name="binance_ws", url="wss://stream.binance.com:9943/ws/ethusdt@ticker", topic_prefix="data.ws.binance", parse_json=True, ) engine.add_...
openbot-coder/pyevebus
python/evebus/sources/websocket.py
.py
94c078d6c018d5ac
7
0
# signaldeck_sdk/context.py from __future__ import annotations from dataclasses import dataclass from typing import Protocol, Optional, Any, Mapping from .message import Message, MessageBus import datetime class FileService(Protocol): def save(self, file: Any, path: str) -> str: """Persist an uploaded fil...
signaldeck/signaldeck-sdk
signaldeck_sdk/context.py
.py
15f2a176268ae09f
7
0
from __future__ import annotations from dataclasses import dataclass, field from typing import Any, Callable, Mapping, Protocol @dataclass(frozen=True, slots=True) class Message: source: str content: Any channel: str | None = None metadata: Mapping[str, Any] = field(default_factory=dict) MessageLis...
signaldeck/signaldeck-sdk
signaldeck_sdk/message.py
.py
d64c7c5db67dca4d
7
0
import asyncio, json import pandas as pd import logging from dataclasses import dataclass from typing import List, Tuple, Any from pathlib import Path from ..cmd import Cmd from importlib import resources from ..value_provider import ValueProvider from ..context import ApplicationContext @dataclass(frozen=True) class...
signaldeck/signaldeck-sdk
signaldeck_sdk/processor/processor.py
.py
5ffff6fdc8d47c8b
7
0
"""Thread-safe state container for Powers Tool worker daemon.""" from __future__ import annotations import threading from typing import Any, TYPE_CHECKING import uuid if TYPE_CHECKING: from powers_tool_cli.worker_http import WorkerHTTPServer class WorkerState: """Thread-safe worker daemon state tracker."""...
tom758258/powers-tool
src/powers_tool_cli/worker_state.py
.py
7a6055ffce6e5113
7
0
"""Internal helpers for no-hardware SCPI previews.""" from __future__ import annotations from collections.abc import Callable from typing import Any from powers_tool_core.factory import create_power_supply class RecordingSession: """Session fake that records driver commands and returns numeric query data.""" ...
tom758258/powers-tool
src/powers_tool_core/_scpi_preview.py
.py
c06e36d359a00e72
7
0
"""Immutable Product build identity.""" from __future__ import annotations from dataclasses import dataclass from enum import Enum from importlib import metadata class BuildProfile(str, Enum): """Build profile embedded by the Product artifact.""" PRODUCT = "product" @dataclass(frozen=True) class ProductB...
tom758258/powers-tool
src/powers_tool_core/build_profile.py
.py
aa8d22569bc1c672
7
0
"""Cooperative cancellation helpers for long-running core commands.""" from __future__ import annotations from typing import Callable from powers_tool_core.core import CommandCancelled StopRequested = Callable[[], bool] | None def raise_if_cancelled(stop_requested: StopRequested) -> None: if stop_requested is...
tom758258/powers-tool
src/powers_tool_core/cancellation.py
.py
278d80b7726f9bd9
7
0
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.preprocessing import LabelEncoder from sklearn.metrics import accuracy_score, classification_report import joblib i...
givemehat/app-live
files-6/model.py
.py
dbec5b32d2dac59c
7.15
1
# Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
6TcbpVB4h7jSZWz2/huggingface__transformers
benchmark/benchmark.py
.py
246359c95a81e90a
7
0
# Copyright 2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
6TcbpVB4h7jSZWz2/huggingface__transformers
benchmark/benchmarks_entrypoint.py
.py
7c10692ca930ab8c
7
0
""" Continuous batching overall benchmark suite. Runs CB in-process across many configurations (GSM8K prompts and synthetic data) and can compare throughput against a previously-saved run. """ import argparse import gc import json import os import time import types from collections.abc import Callable from dataclasse...
6TcbpVB4h7jSZWz2/huggingface__transformers
benchmark_v2/benchmark_scripts/continuous_batching_overall.py
.py
abbd3a8da85df4a1
7
0
import logging import subprocess import sys import time from dataclasses import dataclass from enum import Enum from logging import Logger from multiprocessing import Pipe, Process from multiprocessing.connection import Connection from transformers.utils.import_utils import is_cuda_platform, is_rocm_platform if is_c...
6TcbpVB4h7jSZWz2/huggingface__transformers
benchmark_v2/framework/hardware_metrics.py
.py
bb704cd0acc38d54
7
0
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
6TcbpVB4h7jSZWz2/huggingface__transformers
conftest.py
.py
3e24407411f40c09
7.5
0
# Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
6TcbpVB4h7jSZWz2/huggingface__transformers
examples/3D_parallel.py
.py
291c740b9e518c91
7
0
# # build/build.py # Build both executables with PyInstaller. # """ Run from the repo root: python build/build.py Outputs land in dist/VaderMapper/ VaderService.exe – no console window, no UAC elevation, custom icon VaderConfig.exe – windowed GUI, custom icon config.json – default config copied ...
DrProton824/vader5pro-hid-tools
build/build.py
.py
8fc64d81910054f4
7.24
2
"""``CTkScript`` — base class for CTkMaker behavior scripts. The Unity ``MonoBehaviour`` model for CTkMaker. You subclass it in your own script (in the project's ``scripts/`` folder) and attach it to an object in the builder. CTkMaker injects the object you attached it to — and **only** that object: - atta...
DrProton824/vader5pro-hid-tools
gui/ctkmaker.py
.py
c38a9016f0d29248
7.24
2
# # gui/scripts/device.py # Controller detection, connection state, battery and status info. # """ STATUS SOURCE Reads service-written status.json (not config.json), keeping service → GUI status separate from GUI → service configuration. This script only reads, never writes. STATUS FILE STRUCTURE { ...
DrProton824/vader5pro-hid-tools
gui/scripts/device.py
.py
7083df68363cf152
7.24
2
# # gui/scripts/settings.py # Application settings, startup options, user preferences. # """ CONFIG SOURCE _read_config/_write_config prefer shared/config.py (present once merged into repo) and fall back to local config.json for standalone testing in CTkMaker. Either way reads/writes the same config.json that Va...
DrProton824/vader5pro-hid-tools
gui/scripts/settings.py
.py
1004ad0e843a0df2
7.24
2
# # gui/scripts/storage.py # CRUD helpers over config.json for profiles, macros and settings. # """CRUD helpers over config.json for profiles, macros and settings. Not a CTkScript — a plain module imported by macros.py, profiles.py and settings.py so those stay focused on widget/UI logic instead of JSON bookkeeping. ...
DrProton824/vader5pro-hid-tools
gui/scripts/storage.py
.py
a56a7781910138dd
7.24
2
"""Replacement dropdown popup for CTkComboBox and CTkOptionMenu. CTk's built-in dropdown grows the popup vertically with every added value (no scroll), and its width is fixed regardless of the parent widget's width. This class fixes both: - Scrollbar appears when value count exceeds ``max_visible`` - Popup wid...
DrProton824/vader5pro-hid-tools
gui/scrollable_dropdown.py
.py
5c053889f9d38c4d
7.24
2
# # service/automation/hotkey_watcher.py # Global hotkey listener for profile automation. # """ Uses the Win32 RegisterHotKey API instead of a low-level keyboard hook (the approach macros.py's `keyboard` module uses for GUI-side macro recording). RegisterHotKey only asks Windows to notify this thread when a specific m...
DrProton824/vader5pro-hid-tools
service/automation/hotkey_watcher.py
.py
aa7ae864050fc601
7.24
2
# # service/hid_interface/hid_protocol.py # Vader 5 Pro HID report decoding. # """ Purpose ─────── Pure decode logic shared by every reader implementation (current and legacy): turns a raw HID report into a set of currently-pressed button names, and defines the press/release event types passed to the mapper. No device...
DrProton824/vader5pro-hid-tools
service/hid_interface/hid_protocol.py
.py
2483fe3ac63be06b
7.24
2
# # service/hid_interface/vendor_init.py # Vendor HID initialization and stop commands. # """ Purpose ─────── Write-only helpers that open the Vader 5 Pro's vendor (0xFFA0) interface just long enough to send one command, then close it immediately. Used by rawinput_reader.py to send the recovered vendor initialization ...
DrProton824/vader5pro-hid-tools
service/hid_interface/vendor_init.py
.py
a784476c873df288
7.24
2
# service/mapping/macro_player.py # Macro playback via Win32 SendInput scancodes. # """ Recording and playback ────────────────────── Macro actions are recorded by the GUI's macros.py using the `keyboard` library, which reports hardware scan codes rather than virtual-key names. Replaying by scan code (KEYEVENTF_SCANCO...
DrProton824/vader5pro-hid-tools
service/mapping/macro_player.py
.py
bcdc11f9e3113c83
7.24
2
# # service/mapping/mapper.py # Mapping engine – the bridge between HID events and key injection. # """ Purpose ─────── This module knows nothing about HID reports. It knows nothing about Win32 SendInput. It only translates ButtonEvent objects into either press/release calls on an InputSender (keybind assignments) or ...
DrProton824/vader5pro-hid-tools
service/mapping/mapper.py
.py
fd03e928572684ad
7.24
2
# # service/status_writer.py # Write status.json for the GUI to read. # """ Purpose ─────── Writes status.json (read by gui/scripts/device.py) with the actively tracked controller's connection state and battery level. Kept as a small, focused writer rather than folded into main.py so the service's core startup flow st...
DrProton824/vader5pro-hid-tools
service/status_writer.py
.py
32c3dea48165a329
7.24
2
# Monitors Vader 5 Pro button input reports from the vendor HID channel # (VID 0x37D7 / PID 0x2401, Usage Page 0xFFA0) using hidapitester.exe. # Requires hidapitester.exe to be available in the script directory and decodes # discovered HID bit fields into button press/release events. import subprocess import re impor...
DrProton824/vader5pro-hid-tools
tools/hid_button_monitor.py
.py
938cddb3ccc6cf47
7.24
2
import requests import json import time # 官方文档地址 # https://doc2.bitbrowser.cn/jiekou/ben-di-fu-wu-zhi-nan.html # 此demo仅作为参考使用,以下使用的指纹参数仅是部分参数,完整参数请参考文档 url = "http://127.0.0.1:54345" headers = {"Content-Type": "application/json"} def createBrowser(): # 创建或者更新窗口,指纹参数 browserFingerPrint 如没有特定需求,只需要指定下内核即可,如果需要更详细的参...
MumuJun020/HKTicket
app/Auto/bit_api.py
.py
0c7d2b6dd8782e9e
7.24
2
""" 用**页面上的真实内容**核对接口解析结果。 为什么接口和页面都要有: 接口(ticket_parser) 不用登录、不用开窗口、开票前就能拿到, 所以配置方案只能靠它。 页面(这里) 是抢票时真正操作的对象,是地面真相, 但要登录、要开窗口、要点进购票流程。 两者的**接缝**是这个项目所有解析 bug 的发源地:配置用接口的文本, 抢票拿它去页面上找元素,两边对不上就"抢不到",而且看起来像"没票"。 这个模块把接缝显式化:开抢前跑一次,逐条比对,不一致就直接列出来。 这样...
MumuJun020/HKTicket
app/Auto/ticket_verify.py
.py
0592b6446c9bcae4
7.24
2
from flask import Flask, render_template import os import sys def _resource_dir() -> str: """ 静态资源(templates / static)所在目录。 普通运行时就是本文件所在的 app/ 目录;PyInstaller 打包后,资源被解压到 sys._MEIPASS 下的临时目录,要从那里取。 原来写的是 os.getcwd(),有两个问题:换个目录启动就找不到模板; 打包后压根没有 app/ 这个子目录。 """ base = getattr(sys, "_MEIP...
MumuJun020/HKTicket
app/app.py
.py
98e5fa1e3b815ded
7.24
2
""" 日志管理器:用于捕获和存储运行时的日志输出,供前端实时显示 """ import sys import threading from typing import Dict, List, Set from datetime import datetime from threading import Lock import uuid import queue import json class LogManager: """线程安全的日志管理器,支持SSE推送""" def __init__(self): self._logs: Dict[str, List[Dict[str, st...
MumuJun020/HKTicket
app/utils/logger.py
.py
bdec8b14bd9af597
7.24
2
""" 把项目打包成单文件可执行程序。 python build_exe.py **必须在目标系统上打包。** PyInstaller 不能交叉编译: 要 Windows 的 .exe 就得在 Windows 上跑这个脚本,在 macOS 上跑只会得到 macOS 可执行文件。 打包前先装: pip install -r requirements.txt pip install pyinstaller 产物在 dist/ 下。**data/ 目录会生成在可执行文件旁边**, 里面是账号密码等明文数据,分发时不要一起打包出去。 """ import os import shutil import sub...
MumuJun020/HKTicket
build_exe.py
.py
419f103bdec9aeae
7.24
2
r""" 入口:一条命令启动抢票控制台。 source venv/bin/activate # Windows: venv\Scripts\activate python run.py 会自己挑一个空闲端口、自己把浏览器打开,不用再手动设 PORT。 可选环境变量: PORT=5055 指定起始端口(被占用时会自动往后找) NO_BROWSER=1 不自动打开浏览器 KEEP_DATA=1 启动时不清空上一轮数据(调试用) KEEP_EVENT=1 只保留上次解析的活动,抢票人照常清空 """ import os import so...
MumuJun020/HKTicket
run.py
.py
df3b5818f1bad943
7.24
2
# fuserift.py """ Main module for FuseRift application. """ import argparse import logging import sys from typing import Optional class FuseRift: """Main class for FuseRift functionality.""" def __init__(self, verbose: bool = False): """Initialize with verbosity setting.""" self.verbose =...
mhassanqjlh/FuseRift
fuserift.py
.py
c2de73da50af0f69
7
0
# test_fuserift.py """ Tests for FuseRift module. """ import unittest from fuserift import FuseRift class TestFuseRift(unittest.TestCase): """Test cases for FuseRift class.""" def test_initialization(self): """Test class initialization.""" instance = FuseRift() self.assertIsInstan...
mhassanqjlh/FuseRift
test_fuserift.py
.py
9b54b3639821ddbd
7.5
0
"""Unpack/repack Lionheart's data.dat -- a standard ZIP archive with a renamed extension. Confirmed via Ghidra/ReVa analysis of Lionheart.exe: - It links zlib 1.1.3 for inflate/deflate (unmodified, well-known open-source code). - It checks for the standard ZIP end-of-central-directory signature (0x06054b50). - I...
EricHype/LionheartModTools
archive.py
.py
d12b50b4252bf3c4
7.15
1
"""Small Qt widgets shared by the editors. One entry so far, and it exists because of a real, silent data loss: a stray mouse wheel over a combo box in the dialogue editor's reply list retargeted a reply from `1 Conversation Start` to `10 Transformation` -- one notch down the list -- and saved it. Nothing on screen sa...
EricHype/LionheartModTools
qtwidgets.py
.py
959766404aba0c83
7.15
1
"""Parser/serializer for Lionheart's brace-delimited resource text format. Grammar (inferred from extracted .txt / .InventoryItem / .Quest.txt / .can files): file := TypeName NEWLINE "{" fields "}" fields := (field)* field := KEY "=" VALUE NEWLINE -- leaf field ...
EricHype/LionheartModTools
resource_format.py
.py
fb8527e7159e1f68
7.15
1
"""Byte-exact deltas between a vanilla game resource and a modded one. WHY --- A mod that changes a shipped file has to ship the whole file, because the engine reads no patch format -- so a 40-line edit to Crossroads.zax means redistributing 1.2 MB of the publisher's map. Shipping a delta instead means a release carri...
EricHype/LionheartModTools
resourcedelta.py
.py
13821146f4809ace
7.15
1
"""What the game's entity scripts are made of, and how to build new ones. Entities in a `.zax` carry scripts: trees of `C*Action` nodes hung off keys like `Action`, `After Action`, `Then`, `Next Action`. There are 125 distinct action classes across the shipped maps and about 44,600 nodes, with real control flow -- con...
EricHype/LionheartModTools
script_schema.py
.py
77e37ab9873fbe1a
7.15
1
import os import sys import time import logging import threading import traceback from abc import ABC, abstractmethod from typing import List, Dict, Any from nebula3.gclient.net import ConnectionPool from nebula3.Config import Config logger = logging.getLogger("GraphDBClient") def dump_all_thread_stacks(reason: str)...
apecloud/Aletheia
agents/graph_db_client.py
.py
f8a7029d40ce40a6
7
0
"""Entity deduplication for graph-native (Nebula) tenants, reusing the production identity-resolution building blocks already proven in ``agents/iterative_graph_enrichment_agent.py`` (``_node_identity_payload``, ``_identity_key``, ``SmallMultilingualEmbeddingAdapter``, ``_cosine_distance``, and the same distance thresh...
apecloud/Aletheia
agents/graph_entity_resolver.py
.py
c89bc4f602af91a2
7
0
import os import argparse import pandas as pd from sqlalchemy import create_engine from datasets import load_dataset from huggingface_hub import login try: from legacy_agent_common import configure_logging except ModuleNotFoundError: from agents.legacy_agent_common import configure_logging logger = configure_l...
apecloud/Aletheia
agents/hf_dataset_scraper.py
.py
8238c661db3e331e
7
0
"""Shared boilerplate for the legacy standalone metadata-pipeline agents (action_synthesizer_agent.py, business_context_agent.py, data_profiler_agent.py, data_scraper_agent.py, graph_ingestion_agent.py, hf_dataset_scraper.py, metadata_scraper_agent.py, semantic_consistency_agent.py). Each of these independently copy-pa...
apecloud/Aletheia
agents/legacy_agent_common.py
.py
36285cfc6d1b650c
7
0
"""Shared low-level utilities for the enrichment/graph-search/reasoning loop harnesses. These three harnesses are distinct orchestration layers (different domains, different DB tables, only enrichment mutates data) that happened to each define byte-identical or near-identical copies of these three helpers. Callers pass...
apecloud/Aletheia
agents/loop_harness_common.py
.py
fc8cede9d9411abb
7
0
import os import argparse from sqlalchemy import create_engine, inspect, text from sqlalchemy.orm import sessionmaker from ontology_artifacts import Base, ExtractedColumn, ExtractedTable try: from legacy_agent_common import configure_logging except ModuleNotFoundError: from agents.legacy_agent_common import con...
apecloud/Aletheia
agents/metadata_scraper_agent.py
.py
f2039037e655fac4
7
0
"""Governed node-TYPE catalog for graph extraction -- the "ontology mapping" stage between text-QA passage extraction and ontology-type registration. Mirrors ``scripts/relation_catalog.py``'s ``RelationCatalog`` exactly (same two-tier matching: cheap exact/alias match first, one LLM semantic-match call as fallback, vi...
apecloud/Aletheia
agents/node_type_catalog.py
.py
fb4f8457c6625eee
7
0
"""Embedding-based entity linking for a tenant's approved ontology nodes. Answers a different question than the identity-resolution pipeline this reuses (``SmallMultilingualEmbeddingAdapter``/``_cosine_distance`` from ``iterative_graph_enrichment_agent.py``, already proven for label-vs-label entity dedup in ``graph_en...
apecloud/Aletheia
agents/ontology_label_embeddings.py
.py
bd69c72e6a01c3b2
7
0
#!/usr/bin/env python3 """Convert WebQSP questions to Aletheia tenant format for benchmark evaluation. Extracts topic-entity neighborhoods from WebQSP Freebase subgraphs, derives entity_config and link_config (pruned to topic type's direct links), and produces benchmark questions with gold answer relation paths for pl...
apecloud/Aletheia
scripts/convert_webqsp_to_aletheia.py
.py
346899e41e3c3527
7
0
#!/usr/bin/env python3 """Generate natural language descriptions from Freebase relation names. Freebase relation names follow a dotted convention like ``people.person.nationality`` or ``film.film.starring``. This module converts them into readable descriptions (e.g. "the nationality of a person") so that the keyword-m...
apecloud/Aletheia
scripts/generate_relation_descriptions.py
.py
79f0d9c59bf9e204
7
0
"""Shared vertex-id scheme for HotpotQA/WebQSP graph-native tenants. Extracted from the retired ``import_hotpotqa_kg_tenant.py`` (the SQL-backed HotpotQA importer) -- ``entity_id()`` is backend-agnostic (just a qid-scoped slug) and is reused by every graph-native importer (``import_hotpotqa_nebula_tenant.py``, ``impor...
apecloud/Aletheia
scripts/hotpotqa_entity_ids.py
.py
5ec67ddf66f97b82
7
0
#!/usr/bin/env python3 """Download and freeze a deterministic HotpotQA dev-distractor sample. HotpotQA (Yang et al., 2018) pairs each question with ~10 candidate Wikipedia paragraphs (2 gold/supporting, 8 distractor) and a short span or yes/no answer. Unlike WebQSP/Mintaka this benchmark is passage-only: no knowledge-...
apecloud/Aletheia
scripts/hotpotqa_frozen_sample.py
.py
b06f783456e4dd3f
7
0
"""LLM judge for whether a graph traversal's retrieved facts support a gold answer. Plain substring matching (the original ``graph_hit``) produces false negatives on name variants that are the same entity but not a literal substring of each other -- e.g. label "Joseph Campbell" vs gold "Joseph John Campbell" (middle n...
apecloud/Aletheia
scripts/hotpotqa_graph_judge.py
.py
ccbfc6247809a633
7
0
#!/usr/bin/env python3 """Score HotpotQA predictions with the official EM / token-F1 metrics. Normalization and F1 follow the official HotpotQA/SQuAD evaluation script: lowercase, strip punctuation, drop English articles, collapse whitespace, then compare tokens for F1 and the normalized strings for EM. "yes"/"no" ans...
apecloud/Aletheia
scripts/hotpotqa_sample_eval.py
.py
fce320e8a14d36d9
7
0
""" Wave.exe 窗口结构分析工具 分析 Wave.exe 的窗口层次结构,找出所有子窗口 这可以帮助我们确定是否需要将焦点设置到特定的子窗口 """ import win32gui import win32api import win32con import win32process def find_wave_window(): """查找 Wave.exe 窗口""" wave_windows = [] def enum_callback(hwnd, _): if not win32gui.IsWindowVisible(hwnd): retur...
legendxcheng/ContextSwitcher
analyze_wave_window.py
.py
4eb190e4944b5d5b
7
0
""" 应用辅助类注册表 提供统一的接口来管理和访问各应用辅助类: - 自动注册所有辅助类 - 根据进程名或应用类型获取对应的辅助类 - 统一的上下文提取和窗口恢复接口 """ from typing import Optional, Dict, List, Any, Tuple from .base_app_helper import BaseAppHelper from .terminal_helper import TerminalHelper from .vscode_helper import VSCodeHelper class AppHelperRegistry: "...
legendxcheng/ContextSwitcher
core/app_helpers/app_helper_registry.py
.py
f9abfc3308705046
7
0
""" 应用窗口辅助抽象基类 定义所有应用辅助类的接口规范,包括: - 窗口识别 - 上下文提取 - 窗口恢复 - 窗口匹配 """ import time import win32gui import win32con from abc import ABC, abstractmethod from typing import Optional, Dict, List, Tuple, Any from utils.screen_helper import ScreenHelper class BaseAppHelper(ABC): """应用窗口辅助抽象基类 ...
legendxcheng/ContextSwitcher
core/app_helpers/base_app_helper.py
.py
6c122dfac762ce6a
7
0
""" Windows Terminal 窗口辅助模块 支持的应用: - Windows Terminal (WindowsTerminal.exe) - PowerShell (powershell.exe, pwsh.exe) - 命令提示符 (cmd.exe) 功能: - 从窗口标题解析工作目录和配置文件 - 恢复 Terminal 窗口到指定工作目录 """ import os import re import time import subprocess from typing import Optional, Dict, List, Tuple, Any from .base...
legendxcheng/ContextSwitcher
core/app_helpers/terminal_helper.py
.py
72c6d77de6c39ef7
7
0
""" 专注计时器模块 (番茄钟) 提供番茄钟工作法支持: - 可配置的专注时长 (默认25分钟) - 可配置的休息时长 (默认5分钟) - 自动计时和提醒 - 专注统计 """ import time import threading from datetime import datetime, timedelta from typing import Optional, Callable, Dict, Any from dataclasses import dataclass from enum import Enum class TimerState(Enum): """计...
legendxcheng/ContextSwitcher
core/focus_timer.py
.py
f4fb9dd0bbc5d163
7
0
"""Herdr workspace 命令行集成。""" import json import os import shutil import subprocess from pathlib import Path from typing import Any, Dict, List, Optional, Sequence from utils.localization import tr class HerdrWorkspaceError(RuntimeError): """Herdr workspace 操作失败。""" class HerdrWorkspaceClient: """通过 Herdr ...
legendxcheng/ContextSwitcher
core/herdr_workspace.py
.py
faf22b706ba44d31
7
0
""" 全局热键管理模块 负责注册和处理全局热键: - Ctrl+Alt+1-9 热键注册 - 热键事件处理 - 热键冲突检测 - 热键生命周期管理 """ import os import threading import time from typing import Any, Dict, List, Optional, Protocol try: from pynput import keyboard from pynput.keyboard import Key, KeyCode, Listener except ImportError: print("错误: 请先安装pynput库") ...
legendxcheng/ContextSwitcher
core/hotkey_manager.py
.py
2dfe2a1e6789455d
7
0
""" 智能重新绑定管理器 负责检测失效窗口并提供智能重新绑定功能: - 窗口失效检测 - 智能窗口匹配 - 自动/手动重新绑定 - 绑定历史记录 """ import re import time from typing import List, Dict, Tuple, Optional, Any from dataclasses import dataclass from datetime import datetime from difflib import SequenceMatcher from core.task_manager import TaskManager, Task, BoundWindow from...
legendxcheng/ContextSwitcher
core/smart_rebind_manager.py
.py
09c0428521a60401
7
0
""" 任务状态管理器 负责任务状态的转换和管理: - 状态转换逻辑 - 状态历史记录 - 状态可视化配置 - 状态统计分析 """ import json from datetime import datetime from typing import Dict, List, Optional, Any from dataclasses import dataclass, asdict from enum import Enum from core.task_manager import TaskStatus, Task, TaskManager from utils.localization import tr @da...
legendxcheng/ContextSwitcher
core/task_status_manager.py
.py
70d15b66590d83aa
7
0
""" 任务时间追踪模块 负责追踪用户在每个任务上花费的时间: - 自动记录任务切换时间 - 计算每个任务的专注时间 - 提供今日/本周/总计时间统计 - 支持时间段查询 """ import time from datetime import datetime, date, timedelta from typing import Dict, List, Optional, Any, Tuple from dataclasses import dataclass, field, asdict import json @dataclass class TimeSession: "...
legendxcheng/ContextSwitcher
core/time_tracker.py
.py
6a15589b52ceef58
7
0
""" Window Manager 模块 重构后的窗口管理器,按功能领域拆分为多个专职模块。 这个文件提供外观模式接口,保持向后兼容性。 """ from typing import List, Tuple, Optional, Dict, Any # 导入数据类和常量 from .window_info import WindowInfo # 导入各个功能模块(延迟导入以避免循环依赖) from .window_enumerator import WindowEnumerator from .window_activator import WindowActivator from .window_analyzer imp...
legendxcheng/ContextSwitcher
core/window_manager/__init__.py
.py
95f6eadbe437e7e0
7
0
""" 缓存管理模块 提供窗口信息的缓存机制,提高性能并减少Windows API调用频率。 """ import time from typing import List, Optional, Dict, Any from .window_info import WindowInfo, DEFAULT_CACHE_DURATION class CacheManager: """缓存管理器 负责管理窗口信息的缓存,提供多种缓存策略和生命周期管理。 """ def __init__(self, cache_duration: float = DEFAULT_CACHE_DU...
legendxcheng/ContextSwitcher
core/window_manager/cache_manager.py
.py
cd58629f0cf88ec0
7
0
""" 切换控制和批量操作模块 提供批量窗口操作和切换控制功能。 """ import time import threading from typing import List, Dict, Optional from .window_activator import WindowActivator from .window_enumerator import WindowEnumerator class SwitchController: """切换控制器""" def __init__(self, activator: WindowActivator, enumerator: WindowE...
legendxcheng/ContextSwitcher
core/window_manager/switch_controller.py
.py
22f8e456c982e908
7
0
""" 窗口激活策略模块 提供多种窗口激活策略,确保在不同Windows环境下都能成功激活窗口。 从原始 window_manager.py 中提取窗口激活逻辑。 """ import time try: import win32gui import win32con import win32process import win32api except ImportError: print("错误: 请先安装pywin32库") print("运行: pip install pywin32") raise from .window_enumerator import W...
legendxcheng/ContextSwitcher
core/window_manager/window_activator.py
.py
01593f4341559a9f
7
0
""" 窗口状态分析模块 分析窗口状态和活跃程度,提供智能窗口检测功能。 """ from typing import Dict, Any, Optional, List try: import win32gui except ImportError: print("错误: 请先安装pywin32库") raise from .window_info import WindowInfo, COMMON_APPS from .window_enumerator import WindowEnumerator class WindowAnalyzer: """窗口分析器 负责分析窗口状...
legendxcheng/ContextSwitcher
core/window_manager/window_analyzer.py
.py
c73148ffa216c5c2
7
0
""" 窗口枚举和基础信息模块 负责与Windows API交互,枚举系统中的窗口并获取窗口基础信息。 从原始 window_manager.py 中提取核心枚举逻辑。 """ from typing import List, Optional try: import win32gui import win32con import win32process import win32api except ImportError: print("错误: 请先安装pywin32库") print("运行: pip install pywin32") raise from .w...
legendxcheng/ContextSwitcher
core/window_manager/window_enumerator.py
.py
cd90fb40359171ee
7
0
#!/usr/bin/env python3 """ 热键调试脚本 - 快速诊断热键问题 """ import sys import time from pathlib import Path # 添加项目根目录到Python路径 project_root = Path(__file__).parent sys.path.insert(0, str(project_root)) def simple_hotkey_test(): """简单的热键测试""" print("🔧 简单热键测试...") try: from pynput import keyboard ...
legendxcheng/ContextSwitcher
debug_hotkey.py
.py
1fa60f955cd774cf
7
0
""" 调试 VSCode 进程工作目录获取功能 """ import win32gui import win32process import win32api import win32con import ctypes from ctypes import windll, c_void_p, c_ulong, byref, c_size_t, Structure, sizeof from ctypes.wintypes import DWORD, HANDLE, ULONG # 加载 ntdll ntdll = windll.ntdll class PROCESS_BASIC_INFORMATION(Structure):...
legendxcheng/ContextSwitcher
debug_vscode_peb.py
.py
f3149db6bc86a9b1
7
0
#!/usr/bin/env python3 """ Unicode符号修复脚本 修复所有Python文件中的Unicode符号,避免GBK编码错误 """ import os import re from pathlib import Path def fix_unicode_in_file(file_path): """修复单个文件中的Unicode符号""" try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # 替换常见的Unicode符号...
legendxcheng/ContextSwitcher
fix_unicode.py
.py
7dc724ede625a05e
7
0
"""Thread-safe Qt boundary for global hotkey events.""" from PySide6.QtCore import QObject, Signal class QtHotkeyProxy(QObject): """Queue listener-thread requests as Qt signals.""" task_switcher_requested = Signal(str) main_window_summon_requested = Signal() hotkey_error = Signal(str) def reque...
legendxcheng/ContextSwitcher
gui/qt/hotkey_proxy.py
.py
26ac559b4e0ad100
7
0
""" PySide6 样式表模块 包含 ContextSwitcher 的所有 UI 样式定义 """ from pathlib import Path from functools import lru_cache import sys from PySide6.QtGui import QIcon def _get_styles_dir() -> Path: if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"): return Path(sys._MEIPASS) / "gui" / "qt" / "styles" r...
legendxcheng/ContextSwitcher
gui/qt/styles/__init__.py
.py
e751473392971cd6
7
0
""" 无边框窗口基类模块 提供无边框窗口的基础功能: - FramelessWindow: 无边框窗口基类 - CustomTitleBar: 自定义标题栏 """ from typing import Optional, Union from PySide6.QtWidgets import ( QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QSystemTrayIcon, QMenu ) from PySide6.QtCore import Qt, QPoint, QSize, Signal, QEvent from...
legendxcheng/ContextSwitcher
gui/qt/widgets/frameless_window.py
.py
794911e6ce3e9bdf
7
0
""" 系统托盘模块 提供 PySide6 的系统托盘功能 """ from pathlib import Path from typing import Optional from PySide6.QtWidgets import QSystemTrayIcon, QMenu from PySide6.QtGui import QIcon, QAction, QPixmap, QPainter, QBrush, QColor from PySide6.QtCore import Qt, Signal from utils.localization import get_localizer, tr class System...
legendxcheng/ContextSwitcher
gui/qt/widgets/system_tray.py
.py
aeb5aa4b32c5f032
7
0
""" 表格数据提供器模块 负责主窗口表格的数据转换和颜色渲染逻辑 从MainWindow中提取,遵循单一职责原则 """ from typing import List, Dict, Any, Optional, Tuple from core.task_manager import TaskManager, Task, TaskStatus from core.time_tracker import get_time_tracker class IDataProvider: """数据提供器接口""" def get_table_data(self) -> List[List[str]]: ...
legendxcheng/ContextSwitcher
gui/table_data_provider.py
.py
01076ca89a9def9f
7
0
"""Small QThreadPool-based helper so CLI calls never block the GUI thread.""" from __future__ import annotations import traceback from PySide6.QtCore import QObject, QRunnable, Signal, Slot class WorkerSignals(QObject): finished = Signal(object) error = Signal(str) # percent (0-100), current item name,...
al3xg0r/protondrive-gui
gui/workers.py
.py
fd51780e62514c2f
7
0
""" AI-powered recipe generation using OpenAI API Infrastructure. """ import json import os import re from dotenv import load_dotenv from openai import OpenAI # Load environment variables load_dotenv() # Initialize client as None, will be created when needed client = None # Modern default; gpt-3.5-turbo is a deprec...
IzonIcy/Ai-Chef
ai_generator.py
.py
1dc106e8e1b0fdb9
7
0
""" Gamification system for AI Chef Tracks cooking streaks, badges/achievements, and weekly challenges """ import contextlib from datetime import UTC, datetime, timedelta from typing import ClassVar from data_dir import get_data_dir from json_store import load_json, save_json_atomic class CookingStreak: """Trac...
IzonIcy/Ai-Chef
gamification.py
.py
ff0b42d2ae0d0291
7
0
"""Shared JSON persistence helpers. Every manager class used to hand-roll the same open/json.load/json.dump pattern, and writes went straight to the live file — a crash mid-write could corrupt saved streaks, plans, or recipes. One implementation on purpose: atomic writes (temp file + os.replace) and consistent error h...
IzonIcy/Ai-Chef
json_store.py
.py
b6fe60efaedce570
7
0
""" Meal planning and grocery list generation """ import csv import re from datetime import UTC, datetime from pathlib import Path from data_dir import get_data_dir from json_store import load_json, save_json_atomic from recipes import RECIPE_DATABASE, filter_recipes, get_recipe_by_name def _normalize_ingredient_na...
IzonIcy/Ai-Chef
meal_planner.py
.py
2b521aa6c530144c
7
0
"""Shared fixtures for AI Chef tests. meal_planner.py and gamification.py both key state off ``datetime.now(timezone.utc)``. To keep tests deterministic we patch each module's ``datetime`` name with a :class:`Clock` whose "now" is a fixed timestamp that tests can advance explicitly. """ import datetime as _real_datet...
IzonIcy/Ai-Chef
tests/conftest.py
.py
386382fb39212a27
7.5
0
"""Tests for the shared atomic JSON store.""" import json from json_store import load_json, save_json_atomic def test_save_then_load_roundtrips(tmp_path): path = tmp_path / "data.json" payload = {"a": 1, "list": ["x", "y"]} save_json_atomic(path, payload) assert load_json(path, None) == payload de...
IzonIcy/Ai-Chef
tests/test_json_store.py
.py
abc32b8760fafd37
7.5
0
"""The child's own boot watchdog: die when the boot stops making progress. Everything an agent does before its `idling -> running` claim is invisible from outside. The row reads 'idling' with no pid whether the child is halfway through its import chain or died on the first import, so the launcher (`ops/agent_launch.py...
zhiyuan-zhang0206/Ava
agent/_boot_deadline.py
.py
c92c07f80aacd891
7
0
"""Boot-phase timing — make the import-dominated gap from process start to the first graph step attributable instead of a black box. The agent cold start is dominated by eager imports (langgraph + the ava SDK + the LLM/redis stacks), amplified on a loaded host by page-cache misses and CPU contention. `mark()` records ...
zhiyuan-zhang0206/Ava
agent/_boot_timing.py
.py
39c8ed77bd2a6062
7
0
"""Per-agent config map retention — the env payloads the agent process pops at boot, kept so the exec subprocess can re-emit them into its child's environment. `agent/loop.py` pops `AVA_AGENT_CONFIG_OVERLAY` / `AVA_AGENT_BIRTH_CONFIG` at boot so the agent's own children (shell sessions, watchers) do not inherit them (...
zhiyuan-zhang0206/Ava
agent/_config_carrier.py
.py
65b99f86b5ab3022
7
0
"""Claim an agent row before importing the heavy runtime. The bootstrap process claims an unowned ``idling`` row directly into ``running``. Status deliberately does not expose a separate boot stage: the pid, start time, and lease written by this CAS carry the ownership facts. This module imports nothing from langgrap...
zhiyuan-zhang0206/Ava
agent/_starting.py
.py
6a8f7442ca4013d9
7
0
"""Render exec tracebacks for two audiences with two different cuts. Agent-written code runs under the pseudo-filename ``<agent_code>`` (the name ``compile()`` stamps in `_exec.py`). When that code raises, the raw traceback threads through the exec harness above it and the SDK / plugin / standard-library frames below ...
zhiyuan-zhang0206/Ava
agent/graph/_agent_traceback.py
.py
e365e8133a153288
7
0
"""Packing of pending attachments into one HumanMessage. Two call sites share the pack: - the exec node (`agent/graph/_exec.py`) drains the attachments registered during the just-finished ``execute_code`` call **immediately**, so the media message lands right after the exec-output ToolMessage in the same turn and...
zhiyuan-zhang0206/Ava
agent/graph/_attach_drain.py
.py
52025abbf1d4a288
7
0
"""The `# Capabilities` index — the system prompt's one listing of what this agent already has (skills + live MCP tool servers). Split out of `_system_prompt.py` so the prompt-assembly module stays inside the per-file line budget. The section function is registered by `_system_prompt` (rather than decorated here) so t...
zhiyuan-zhang0206/Ava
agent/graph/_capabilities.py
.py
b7936b331396ccf7
7
0
"""Batch acquisition for the claim node: the idle wait loop and its upkeep. Extracted from agent/graph/_claim.py (Task #1006 split — the batch-claim axis). Behavior preserved verbatim: 1. First SELECT pending once (guards against race where ava.self.compact has INSERTed but the publish already passed) — lives in _...
zhiyuan-zhang0206/Ava
agent/graph/_claim_batch.py
.py
ec4ab764e1106891
7
0
"""Post-dispatch decision for the claim node: short-circuit rules → one Command. Extracted from agent/graph/_claim.py (Task #1006 split). Every return path flows through decide() — the original's eight return points collapse to one; the ``halted`` formula appears exactly once. Chain: cancel path → veto re-entry → idle...
zhiyuan-zhang0206/Ava
agent/graph/_claim_decide.py
.py
46fef554909f6275
7
0
"""Lifecycle routing for the claim node: where a pass may go + who wins. Holds the ClaimGoto vocabulary (the four targets claim itself routes to), the routing-gated kinds (_ROUTING_KINDS), and the single batch-winner resolution (_Routing / resolve_routing). Extracted from agent/graph/_claim.py (Task #1006 split — the ...
zhiyuan-zhang0206/Ava
agent/graph/_claim_routing.py
.py
e2d8f84e6ff38f62
7
0
"""The ordered registry of standing context notes + the framework's own. A context note is a short system-styled message that sits behind the SystemMessage for the life of a context window. `init_context` lays the whole set down at the two moments a window is established — an agent's first wake, and the turn after any...
zhiyuan-zhang0206/Ava
agent/graph/_context_notes.py
.py
a35ac2a18f1989cf
7
0