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
from ..calculation_functions_typing import * from ...data_types import File import cv2 import numpy as np def read_jpg_image(file_path): """ Чтение jpg изображения """ return cv2.imread(file_path, cv2.IMREAD_GRAYSCALE) def read_xcr_file(file_path, shape=(1024, 1024)): """ Читает файл XCR ...
EgorPlehanov/node_data_editor
units/calculation_functions/input/read.py
.py
c49e214c83dafba9
7.42
6
from ..calculation_functions_typing import * from ...data_types import File from ..input.read import read_file import numpy as np import cv2 import math # Функция для прямого 2-D преобразования Фурье def Fourier2D(image): return np.fft.fft2(image) # Функция для обратного 2-D преобразования Фурье def inverseFou...
EgorPlehanov/node_data_editor
units/calculation_functions/lab/lab10.py
.py
a26497ef5d114de0
7.42
6
from ..calculation_functions_typing import * from ...data_types import File from ..input.read import read_file import cv2 import numpy as np def apply_low_pass_filter(image, cutoff_frequency): """ Применить фильтр Лопаса к входному изображению """ dft = cv2.dft(np.float32(image), flags=cv2.DFT_COMPL...
EgorPlehanov/node_data_editor
units/calculation_functions/lab/lab11.py
.py
d4cd8a540b03e230
7.42
6
from ..calculation_functions_typing import * from ...data_types import File from ..input.read import read_file import cv2 import numpy as np def gradient_sobel(image): # Применение операторов Собеля для вычисления градиентов по X и Y sobelx = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3) sobely = cv2.Sobe...
EgorPlehanov/node_data_editor
units/calculation_functions/lab/lab12.py
.py
2b27988e6f3c72d9
7.42
6
from ..calculation_functions_typing import * from ...data_types import File from ..input.read import read_file import cv2 import numpy as np def erosion(image, kernel_size): """ Выделения контуров объектов на изображении методом ЭРОЗИИ """ kernel = np.ones((kernel_size, kernel_size), np.uint8) e...
EgorPlehanov/node_data_editor
units/calculation_functions/lab/lab13.py
.py
28689c80d186310d
7.42
6
from ..calculation_functions_typing import * from ...data_types import File from ..input.read import read_file import numpy as np import pandas as pd import matplotlib.pyplot as plt import plotly.express as px def rotate_image_90_degrees(image, angle: int): """ Поворачивает растровое изображение на угол, кра...
EgorPlehanov/node_data_editor
units/calculation_functions/lab/lab6.py
.py
50d08d8083000152
7.42
6
from ..calculation_functions_typing import * from ...data_types import File from ..input.read import read_file import cv2 import numpy as np def compute_difference_image(image1, image2): """ Вычисляет разностное изображение между двумя входными изображениями. """ if image1 is None or image2 is None:...
EgorPlehanov/node_data_editor
units/calculation_functions/statistics/analysis.py
.py
29967284b9034161
7.42
6
from ..calculation_functions_typing import * from ...data_types import File from ..input.read import read_file import cv2 import matplotlib.pyplot as plt import plotly.graph_objects as go import numpy as np def plot_image_histogram(image): """ Строит гистограмму распределения цветов изображения по каналам и...
EgorPlehanov/node_data_editor
units/calculation_functions/statistics/histogram.py
.py
de8e494ac3abfa02
7.42
6
from enum import Enum from random import choice class Color(Enum): ''' Цвет ''' RED = "#ff0000" PINK = "#ff0072" PURPLE = "#AA00FF" DEEP_PURPLE = "#6a00ff" INDIGO = "#0026ff" BLUE = "#2962FF" LIGHT_BLUE = "#0091EA" CYAN = "#00ddff" ...
EgorPlehanov/node_data_editor
units/data_types/colors_enum.py
.py
71e422475b30e75f
7.42
6
from dataclasses import dataclass import os @dataclass class File: ''' Файл path - путь к файлу name - имя файла extension - расширение файла size - размер файла (байт) size_formatted - размер файла в строку formatted_name - имя файла и его размер data_path - путь к файлу вну...
EgorPlehanov/node_data_editor
units/data_types/file.py
.py
dd283867743568b9
7.42
6
from typing import TYPE_CHECKING if TYPE_CHECKING: from ..workplace import Workplace from ..configs import * from ..node import NodeConfig from flet import * from typing import List class FunctionMenuBar(MenuBar): """ Меню бар приложения Содержит пункты меню: ноды, инструменты """ def __in...
EgorPlehanov/node_data_editor
units/menubar/menubar.py
.py
03b0374ddb7ceb51
7.42
6
from typing import TYPE_CHECKING if TYPE_CHECKING: from ..node_area.node_area import NodeArea from ..parameters import ParameterInterface from .node_connection import NodeConnection from .node_config import NodeConfig from ..calculation_functions import NodeResult from ..result_area import ResultView from ...
EgorPlehanov/node_data_editor
units/node/node.py
.py
14b629127db2923e
7.42
6
from typing import TYPE_CHECKING if TYPE_CHECKING: from .node import Node from ..parameters import ParameterInterface from ..parameters.parameter_typing.parameter_connect_point import ParameterConnectPoint from .node_config import NodeConfig from ..data_types import ParameterConnectType from ..paramete...
EgorPlehanov/node_data_editor
units/node/node_view.py
.py
5990e99a91871a66
7.42
6
from typing import TYPE_CHECKING if TYPE_CHECKING: from ..workplace import Workplace from .node_area_background_grid import NodeAreaBackgroundGrid from .node_area_selection_box import NodeAreaSelectionBox from .node_area_connections import NodeAreaConnections from ..node import Node, NodeConfig, NodeConnection fro...
EgorPlehanov/node_data_editor
units/node_area/node_area.py
.py
778dc350de824fee
7.42
6
from typing import TYPE_CHECKING if TYPE_CHECKING: from .node_area import NodeArea from flet import * import flet.canvas as cv class NodeAreaBackgroundGrid(cv.Canvas): """ Фоновая сетка c точками в рабочей области с нодами """ def __init__( self, page: Page, node_area: ...
EgorPlehanov/node_data_editor
units/node_area/node_area_background_grid.py
.py
7f7a38908d970f8d
7.42
6
from typing import TYPE_CHECKING if TYPE_CHECKING: from .node_area import NodeArea from ..node.node import Node from ..node import NodeConnection from flet import * import flet.canvas as cv from typing import List class NodeAreaConnections(cv.Canvas): """ Облисть отрисовки линий соединений нод ...
EgorPlehanov/node_data_editor
units/node_area/node_area_connections.py
.py
736aea32569b1503
7.42
6
from typing import TYPE_CHECKING if TYPE_CHECKING: from .node_area import NodeArea from flet import * import flet.canvas as cv import keyboard class NodeAreaSelectionBox(cv.Canvas): """ Область выделения нод управляемая курсором """ def __init__( self, page: Page, node_ar...
EgorPlehanov/node_data_editor
units/node_area/node_area_selection_box.py
.py
5deeaec9f3341e48
7.42
6
""" Solace-AI API Gateway - JWT Authentication Plugin. Implements JWT validation, token verification, and role-based access control. """ from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass, field from datetime import datetime, timezone, timedelta from enum import Enu...
Rayyan9477/Solace-AI
infrastructure/api_gateway/auth_plugin.py
.py
19099735606a5454
7.64
18
""" Solace-AI API Gateway - Rate Limiting. Implements rate limiting policies with Redis-backed storage and sliding window algorithm. """ from __future__ import annotations from dataclasses import dataclass, field from datetime import datetime, timezone from enum import Enum from typing import Any import time import has...
Rayyan9477/Solace-AI
infrastructure/api_gateway/rate_limiting.py
.py
1d0cb919d8304e9a
7.64
18
"""Alembic environment configuration for Solace-AI database migrations.""" from __future__ import annotations import asyncio import os from logging.config import fileConfig from alembic import context from sqlalchemy import pool from sqlalchemy.engine import Connection from sqlalchemy.ext.asyncio import async_engine_...
Rayyan9477/Solace-AI
migrations/env.py
.py
753ace8bdda09076
7.64
18
"""Enable Row-Level Security on highest-risk PHI tables (H-56 partial). Revision ID: 002_enable_rls Revises: 001_initial Create Date: 2026-04-22 This migration enables PostgreSQL Row-Level Security on the three clinical tables that carry the highest PHI exposure risk: - ``diagnosis_sessions`` — conversation histor...
Rayyan9477/Solace-AI
migrations/versions/002_enable_rls_clinical_tables.py
.py
174f31d8e5b29933
7.64
18
"""Safety escalations persistence table (H-04). Revision ID: 003_escalations Revises: 002_enable_rls Create Date: 2026-04-24 Creates the ``escalations`` table used by ``PostgresEscalationRepository`` in the safety service. Before this migration the escalation state lived in process memory (``InMemoryEscalationReposit...
Rayyan9477/Solace-AI
migrations/versions/003_safety_escalations_table.py
.py
1cb9c03c12243cd4
7.64
18
"""OAuth account linkage table (Sprint 8 Google OAuth). Revision ID: 004_oauth_accounts Revises: 003_escalations Create Date: 2026-04-25 Creates the ``oauth_accounts`` table that links internal users to external OAuth providers (Google now; Apple post-MVP). One user may link multiple providers; a (provider, provider_...
Rayyan9477/Solace-AI
migrations/versions/004_oauth_accounts.py
.py
1493c47200de7a3f
7.64
18
"""Widen encrypted PHI columns from VARCHAR(n) to TEXT (REV-13). Revision ID: 005_widen_phi_columns Revises: 004_oauth_accounts Create Date: 2026-07-24 Four PHI fields are encrypted at the application layer into a ``v1$`` envelope (nonce + ciphertext + tag, base64) that is much longer than the plaintext. They were de...
Rayyan9477/Solace-AI
migrations/versions/005_widen_encrypted_phi_columns.py
.py
d13a1e8e5345daf3
7.64
18
"""Extend Row-Level Security to the remaining PHI tables (H-56 full / C.2). Revision ID: 006_extend_rls Revises: 005_widen_phi_columns Create Date: 2026-07-28 Migration 002 enabled PostgreSQL Row-Level Security on three clinical tables as the MVP cut. This migration extends the same per-user policy to the remaining P...
Rayyan9477/Solace-AI
migrations/versions/006_extend_rls_phi_tables.py
.py
4227beabb02fa392
7.64
18
"""Add the outbox ``claimed_at`` column for the atomic-claim poller (REV-39). Revision ID: 007_outbox_claimed_at Revises: 006_extend_rls Create Date: 2026-07-30 The transactional-outbox poller now CLAIMS records atomically (PENDING -> PUBLISHING with a ``claimed_at`` stamp) instead of a bare ``SELECT ... FOR UPDATE S...
Rayyan9477/Solace-AI
migrations/versions/007_outbox_claimed_at.py
.py
993b303501ed4281
7.64
18
"""Extend Row-Level Security to the personality PHI tables (C.2 / A2). Revision ID: 008_rls_personality Revises: 007_outbox_claimed_at Create Date: 2026-07-30 Migration 006 enabled RLS on the 9 tables written under an authenticated USER request (``get_current_user`` sets the ``app.current_user_id`` GUC). It DEFERRED ...
Rayyan9477/Solace-AI
migrations/versions/008_rls_personality_tables.py
.py
88707ea2597f84a4
7.64
18
""" Solace-AI Analytics Service - API Endpoints. REST API for analytics queries, report generation, and metrics access. Implements query validation, caching, and rate limiting. Architecture Layer: Infrastructure (API) Principles: Clean API Design, Request Validation, Response Caching """ from __future__ import annota...
Rayyan9477/Solace-AI
services/analytics-service/src/api.py
.py
99be7ee66c9f79df
7.64
18
""" Solace-AI Analytics Service - Configuration. Centralized configuration management for analytics service components. Supports environment-based configuration with validation. Architecture Layer: Infrastructure Principles: 12-Factor App, Configuration Externalization, Type Safety """ from __future__ import annotati...
Rayyan9477/Solace-AI
services/analytics-service/src/config.py
.py
9a92a33e12a09454
7.64
18
"""REV-17: analytics-service GDPR right-to-erasure wiring. The analytics service persists one user-tagged store: the ClickHouse ``analytics_events`` table (raw per-user events, including their payloads). This module registers that store's delete (``AnalyticsRepository.delete_user_data``) with the shared, fail-loud :cl...
Rayyan9477/Solace-AI
services/analytics-service/src/erasure.py
.py
b48f8e9bcaf9c11d
7.64
18
""" Solace-AI Analytics Service - Data Models. Data transfer objects for analytics storage operations. These models represent the storage schema for events, metrics, and aggregations. Architecture Layer: Infrastructure Principles: Data Transfer Objects, Immutable Records, Type Safety """ from __future__ import annota...
Rayyan9477/Solace-AI
services/analytics-service/src/models.py
.py
087733ce1623f494
7.64
18
""" Pytest configuration and fixtures for analytics service tests. """ import sys from pathlib import Path # Add src directory to path for imports src_path = Path(__file__).parent.parent / "src" sys.path.insert(0, str(src_path)) import pytest from datetime import datetime, timezone from decimal import Decimal from uu...
Rayyan9477/Solace-AI
services/analytics-service/tests/conftest.py
.py
81e98c1fd9cc8a7f
7.14
18
""" Unit tests for analytics aggregations module. """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent / "src")) import pytest from datetime import datetime, timedelta, timezone from decimal import Decimal from uuid import uuid4 from aggregations import ( AggregationWindow, ...
Rayyan9477/Solace-AI
services/analytics-service/tests/test_aggregations.py
.py
b9f250c1596f984b
8.14
18
""" Unit tests for analytics API endpoints. """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent / "src")) import pytest from datetime import datetime, timedelta, timezone from decimal import Decimal from uuid import uuid4 from unittest.mock import MagicMock, AsyncMock from fast...
Rayyan9477/Solace-AI
services/analytics-service/tests/test_api.py
.py
b747249a90171083
7.14
18
""" Unit tests for analytics service configuration. """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent / "src")) import pytest from datetime import timedelta from pydantic import ValidationError from config import ( Environment, ServiceConfiguration, ClickHouseConf...
Rayyan9477/Solace-AI
services/analytics-service/tests/test_config.py
.py
c978f79da2ab0970
8.14
18
""" Unit tests for analytics consumer module. """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent / "src")) import pytest from datetime import datetime, timezone from decimal import Decimal from uuid import uuid4 from consumer import ( EventCategory, AnalyticsEvent, ...
Rayyan9477/Solace-AI
services/analytics-service/tests/test_consumer.py
.py
8b0ed1f848468d08
7.14
18
"""Phase B / A-1b (P1) verification: full ingest -> store -> report path. Proves the fix end-to-end through the REAL consumer (raw event dict -> AnalyticsConsumer.process_event -> aggregator -> MetricsStore), not just the aggregator's public API: a safety crisis event pushed through the consumer must surface as non-ze...
Rayyan9477/Solace-AI
services/analytics-service/tests/test_consumer_to_report_e2e.py
.py
53db3a7d279f5519
8.14
18
""" Phase C P1-9 regression for the analytics service. The runtime gate is ``ServiceConfig`` (src/main.py) with ``env_prefix="ANALYTICS_SERVICE_"`` and field ``env`` -> binds ``ANALYTICS_SERVICE_ENV``. The production behaviour (docs/redoc disabled, CORS locked, PHI log sanitizer required at main.py:216) reads ``settin...
Rayyan9477/Solace-AI
services/analytics-service/tests/test_env_binding_p1_9.py
.py
aeb6cea2eb9638d8
8.14
18
""" Unit tests for analytics main module and observability configuration. """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent / "src")) import pytest from unittest.mock import MagicMock, patch, AsyncMock from fastapi import FastAPI from fastapi.testclient import TestClient cla...
Rayyan9477/Solace-AI
services/analytics-service/tests/test_main.py
.py
bc3aafc61b5650fb
7.14
18
""" Unit tests for analytics reports module. """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent / "src")) import pytest from datetime import datetime, timedelta, timezone from decimal import Decimal from uuid import uuid4 from reports import ( ReportType, ReportFormat,...
Rayyan9477/Solace-AI
services/analytics-service/tests/test_reports.py
.py
56e900616efd787f
7.14
18
"""Phase B / A-1b (P1): report generators must render REAL data, not zeros. Two root causes made every report read zero (existing report tests only asserted keys EXIST, never that values were non-zero): 1. Granularity: data is recorded in MINUTE windows but reports query HOUR/DAY -> the window-type filter dropped ...
Rayyan9477/Solace-AI
services/analytics-service/tests/test_reports_render_data.py
.py
2bb1fbe3293de65d
8.14
18
""" Unit tests for analytics repository. """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent / "src")) import pytest from datetime import datetime, timezone, timedelta from decimal import Decimal from uuid import uuid4 from repository import ( ClickHouseConfig, Analytic...
Rayyan9477/Solace-AI
services/analytics-service/tests/test_repository.py
.py
a0d17eeb135b4ef8
7.14
18
"""Phase B Gate G2 re-hunt: safety metrics must count the REAL event shapes. Two confirmed defects in the A-1b analytics change (caught because the first tests injected values the real event plane never emits): 1. Double-count: a single CRITICAL incident emits BOTH `safety.assessment.completed` AND `safety.crisis....
Rayyan9477/Solace-AI
services/analytics-service/tests/test_safety_event_counting.py
.py
a7f90d0a18e109f9
8.14
18
"""Phase B / A-1b (P1): metric window-granularity rollup. Root cause: MetricsStore.record() defaults to a MINUTE window and record_counter/ gauge/timing never override it, so EVERYTHING is stored in MINUTE buckets. But every report generator (and get_dashboard_metrics) queries get_aggregated(window_type=HOUR|DAY), and...
Rayyan9477/Solace-AI
services/analytics-service/tests/test_window_rollup.py
.py
0b9b7353c6d9d03a
8.14
18
""" Solace-AI Configuration Service API Endpoints. RESTful API for configuration, secrets, and feature flag management. """ from __future__ import annotations import hmac from datetime import datetime, timezone from typing import Any from fastapi import APIRouter, Depends, HTTPException, Query, Header, status from pyda...
Rayyan9477/Solace-AI
services/config_service/src/api.py
.py
7d4d1ebfe2dff458
7.64
18
# This module uses Micropython and needs to be set-up on the Raspberry Pico # board, to read values from capacitive soil moisture sensors (v1.2). import gc import ujson import utime from machine import ADC, I2C, WDT, Pin from ssd1306 import SSD1306_I2C # Configuration POLLING_INTERVAL_SEC = 2 # Display configuration...
smallwat3r/rpi-gardener
pico/main.py
.py
b794880775f618d2
7.48
8
"""Database cleanup script for scheduled execution via cron. Deletes records older than the configured retention period. Run via cron, e.g.: 0 3 * * * python -m rpi.cron.db_cleanup """ import asyncio import sys from datetime import UTC, datetime, timedelta from pathlib import Path import aiosqlite from rpi.lib.con...
smallwat3r/rpi-gardener
rpi/cron/db_cleanup.py
.py
73ce7d34b2df70ab
7.48
8
"""Poll DHT22 sensor for new data, and persist results in SQLite. Initializes the database on first run. Default polling frequency is 2 seconds (configurable via PollingSettings). The DHT22 sensor updates every 2 seconds, so polling faster would return cached results. """ import asyncio from datetime import UTC, date...
smallwat3r/rpi-gardener
rpi/dht/polling.py
.py
fb36c68559764068
7.48
8
"""Humidifier service that controls humidity via a TP-Link Kasa smart plug. Subscribes to the event bus ALERT topic and controls a smart plug to turn a humidifier on/off based on humidity levels. - Humidifier turns ON when humidity is too LOW (alert triggered) - Humidifier turns OFF when humidity recovers (alert reso...
smallwat3r/rpi-gardener
rpi/humidifier/service.py
.py
dd63056d70f46f4c
7.48
8
"""LCD 1602A display module for showing alert status with scrolling. Provides a Display class for rendering active alerts on a 16x2 character LCD connected via I2C (PCF8574 backpack). """ from typing import Protocol, Self from rpi.lib.config import get_settings class DisplayProtocol(Protocol): """Protocol for ...
smallwat3r/rpi-gardener
rpi/lcd/display.py
.py
db9faf4c05692727
7.48
8
"""LCD service that displays active alerts with scrolling text. Subscribes to the event bus ALERT topic and maintains a display of currently active alerts on a 16x2 character LCD. """ import asyncio from contextlib import suppress from rpi.lcd.display import DisplayProtocol from rpi.lib.alerts import AlertEvent, Nam...
smallwat3r/rpi-gardener
rpi/lcd/service.py
.py
9423aaca288a87de
7.48
8
"""Alert state tracking for sensor threshold violations. Provides a unified AlertTracker singleton that tracks per-sensor alert states across different namespaces (DHT, Pico) and triggers callbacks only on state transitions (to prevent notification spam). Uses hysteresis to prevent flapping when values oscillate arou...
smallwat3r/rpi-gardener
rpi/lib/alerts.py
.py
45cc3b9889765849
7.48
8
"""Enumerations for the RPi Gardener application.""" from enum import IntEnum, StrEnum class NotificationBackend(StrEnum): GMAIL = "gmail" SLACK = "slack" class Unit(StrEnum): """Measurement units for sensor readings.""" CELSIUS = "°C" PERCENT = "%" class ThresholdType(StrEnum): """Type ...
smallwat3r/rpi-gardener
rpi/lib/config/enums.py
.py
fec8b7d863579e6c
7.48
8
"""Settings models and configuration loading for the RPi Gardener application.""" import os import re from functools import cached_property, lru_cache from typing import Annotated, Any, Self from pydantic import ( AfterValidator, BaseModel, BeforeValidator, ConfigDict, Field, HttpUrl, Secr...
smallwat3r/rpi-gardener
rpi/lib/config/settings.py
.py
afeb0ad961396e29
7.48
8
"""Database connection management. Provides async database operations using aiosqlite for non-blocking database access throughout the application. Connection Patterns ------------------- Two connection patterns are supported, chosen automatically by get_db(): 1. **Persistent Connection** (polling services) - Call...
smallwat3r/rpi-gardener
rpi/lib/db/connection.py
.py
af186e1ede148c51
7.48
8
"""Database query functions.""" from __future__ import annotations from datetime import UTC, datetime from functools import cache from pathlib import Path from typing import cast from rpi.lib.db.connection import get_db from rpi.lib.db.types import DHTReading, PicoReading # SQL templates directory _SQL_DIR = Path(_...
smallwat3r/rpi-gardener
rpi/lib/db/queries.py
.py
19ebad252d00201d
7.48
8
"""Settings cache and database operations.""" from __future__ import annotations import time from typing import cast import aiosqlite from rpi.lib.config import SettingsKey, get_settings from rpi.lib.db.connection import get_db from rpi.logging import get_logger _logger = get_logger("lib.db.settings") class _Set...
smallwat3r/rpi-gardener
rpi/lib/db/settings.py
.py
1977cf754845649e
7.48
8
"""Type definitions for database operations.""" from typing import Any, TypedDict type SQLParams = tuple[Any, ...] | dict[str, Any] """SQL parameter types: positional tuple or named dict for query binding.""" class DHTReading(TypedDict): """DHT22 sensor reading from the database.""" temperature: float ...
smallwat3r/rpi-gardener
rpi/lib/db/types.py
.py
a9464d657278fc8c
7.48
8
"""Redis-based event bus for real-time sensor data broadcasting. Provides pub/sub messaging between polling services (publishers) and the web server/notification service (subscribers) for real-time updates. Includes automatic reconnection with exponential backoff on connection failures. """ import asyncio import jso...
smallwat3r/rpi-gardener
rpi/lib/eventbus.py
.py
a6b58f46ed751557
7.48
8
"""Custom exceptions for the RPi Gardener application. Provides a hierarchy of domain-specific exceptions for better error handling and more informative error messages throughout the application. """ class RpiGardenerError(Exception): """Base exception for all application errors.""" class DatabaseError(RpiGard...
smallwat3r/rpi-gardener
rpi/lib/exceptions.py
.py
22ce84850254dd0c
7.48
8
"""Mock sensor data generators for development. Provides mock implementations of sensor interfaces that generate realistic data without requiring hardware. Used by polling/reader services when MOCK_SENSORS=1 is set. The random_walk function is shared with scripts/seed_data.py for consistent data patterns between seed...
smallwat3r/rpi-gardener
rpi/lib/mock.py
.py
9b6fe182438a9355
7.48
8
"""Notification system for sensor alerts. Provides an abstract notification interface with pluggable backends. Currently includes Gmail and Slack backends, with support for both simultaneously. """ import asyncio import ssl from abc import ABC, abstractmethod from email.message import EmailMessage from pathlib import...
smallwat3r/rpi-gardener
rpi/lib/notifications.py
.py
19b120325cd12276
7.48
8
"""Generic async polling service abstraction. Provides a reusable base class for sensor polling services that follow the poll → audit → persist pattern with configurable intervals. """ import asyncio import signal from abc import ABC, abstractmethod from collections.abc import Callable from types import FrameType fr...
smallwat3r/rpi-gardener
rpi/lib/polling.py
.py
f280ea622c6af22f
7.48
8
"""TP-Link Kasa smart plug control module. Provides async interface to control Kasa smart plugs with retry logic and proper error handling. """ from typing import Protocol, Self from kasa import Device, Discover from rpi.lib.config import get_settings from rpi.lib.retry import with_retry from rpi.logging import get...
smallwat3r/rpi-gardener
rpi/lib/smartplug.py
.py
f985f0d29b1c9ed7
7.48
8
"""Logging configuration for the RPi Gardener application.""" import logging import sys from functools import lru_cache LOG_FORMAT = "%(asctime)s %(name)s %(levelname)s - %(message)s" @lru_cache(maxsize=1) def configure(level: int = logging.INFO) -> None: """Configure logging for the application. Safe to c...
smallwat3r/rpi-gardener
rpi/logging.py
.py
6b54acc43573a873
7.48
8
"""Notification service that listens to alert events and sends notifications. Subscribes to the event bus ALERT topic and dispatches notifications via configured backends (Gmail, Slack, etc.). """ from rpi.lib.alerts import safe_parse_alert_event from rpi.lib.eventbus import EventSubscriber, Topic from rpi.lib.notifi...
smallwat3r/rpi-gardener
rpi/notifications/service.py
.py
3feda3bdacad2d34
7.48
8
"""OLED display module for rendering sensor readings. Provides a Display class for rendering temperature and humidity readings on an SSD1306 OLED display connected via I2C. """ from typing import Protocol, Self from rpi.lib.config import Unit, get_settings class DisplayProtocol(Protocol): """Protocol for OLED ...
smallwat3r/rpi-gardener
rpi/oled/display.py
.py
72152a0bd19d0612
7.48
8
"""OLED service that displays temperature and humidity readings. Subscribes to the event bus DHT_READING topic and renders the latest readings on an SSD1306 OLED display. """ from rpi.lib.config import get_settings from rpi.lib.eventbus import EventSubscriber, Topic from rpi.lib.service import run_service from rpi.lo...
smallwat3r/rpi-gardener
rpi/oled/service.py
.py
88a908f7b36f4f8a
7.48
8
"""Domain models for Pico moisture sensor readings.""" from __future__ import annotations from dataclasses import dataclass from datetime import datetime from rpi.lib.config import PlantIdValue, get_settings, parse_pico_plant_id class ValidationError(Exception): """Raised when input validation fails.""" @dat...
smallwat3r/rpi-gardener
rpi/pico/models.py
.py
859774a53b96988d
7.48
8
"""Read Pico moisture readings via USB serial. Reads JSON lines from the Pico's USB serial output and persists moisture readings to the database. """ import asyncio import json from datetime import UTC, datetime from typing import Protocol, override from rpi.lib.alerts import AlertTracker, Namespace, setup_alert_pub...
smallwat3r/rpi-gardener
rpi/pico/reader.py
.py
74ecaa6d16147580
7.48
8
import re from unicodedata import normalize from jinja2.ext import Extension SLUG_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_" def slug(text: str, separator: str = "_", permitted_chars: str = SLUG_CHARS): """Generate a slug for the `text`. >>> slug(' ÁLVARO justen% ') 'alv...
PythonicCafe/cookiecutter-dokku-django
extensions.py
.py
a0cda74eb27a2489
7.42
6
import os import signal import threading import time from uvicorn_worker import UvicornWorker class _AliveWatcher(threading.Thread): """Workaround for gunicorn's reloader not restarting UvicornWorker correctly. Gunicorn's reloader sets `worker.alive = False` and calls `sys.exit(0)`, which in `UvicornWorker`...
PythonicCafe/cookiecutter-dokku-django
{{ cookiecutter.project_slug }}/app_server.py
.py
2b6cbae97c307e26
7.42
6
import json import logging from channels.generic.websocket import WebsocketConsumer logger = logging.getLogger(__name__) class EchoConsumer(WebsocketConsumer): """Test consumer that echoes messages back to the client. Accepts only authenticated users. To test in the browser, open a page of the system, auth...
PythonicCafe/cookiecutter-dokku-django
{{ cookiecutter.project_slug }}/core/consumers.py
.py
75aa35484f733701
7.42
6
import json from urllib.parse import urljoin import boto3 from django.conf import settings class S3FileStorage: def __init__(self): self.session = boto3.session.Session() self.client = self.session.client( "s3", endpoint_url=settings.AWS_S3_ENDPOINT_URL, aws_ac...
PythonicCafe/cookiecutter-dokku-django
{{ cookiecutter.project_slug }}/project/storage.py
.py
7333535fe8f6a409
7.42
6
import hashlib import logging import pickle import threading import time from typing import Any from celery import Task from django.conf import settings from django.core.cache import caches logger = logging.getLogger(__name__) class LockedTask(Task): """A Celery Task subclass that prevents concurrent execution ...
PythonicCafe/cookiecutter-dokku-django
{{ cookiecutter.project_slug }}/project/utils/celery.py
.py
b9d154da320fb037
7.42
6
from django.contrib.postgres.search import SearchHeadline, SearchQuery, SearchRank # TODO: we may want to get the available languages by running the query in the current database # Mapping created from joining results of `SELECT cfgname FROM pg_ts_config` # and the table found in <https://en.wikipedia.org/wiki/List_of...
PythonicCafe/cookiecutter-dokku-django
{{ cookiecutter.project_slug }}/project/utils/search.py
.py
e299f7e496df4def
7.42
6
import os from pathlib import Path import toml __all__ = ("get_config", "get_config_flex") def get_pyproject_toml(): cwd = os.getcwd() local_path = Path(cwd) / "pyproject.toml" if local_path.exists(): return toml.loads(local_path.read_text()) raise FileNotFoundError(str(local_path)) def ge...
python-project-templates/yardang
yardang/utils.py
.py
6ecc694d8a4ce7e4
7.42
6
import numpy as np import scipy import matplotlib.pyplot as plt import fh_comm as fhc def trotterized_time_evolution(hlist, method: fhc.SplittingMethod, dt: float, nsteps: int): """ Compute the numeric ODE flow operator of the quantum time evolution based on the provided splitting method. """ V = ...
qc-tum/fermi_hubbard_commutators
examples/fh_comm_1d.py
.py
e2a94131893a409e
7.42
6
from scipy.special import binom def multinomial(params): """ Multinomial coefficient. """ if len(params) == 1: return 1 return binom(sum(params), params[-1]) * multinomial(params[:-1]) def integer_sum_tuples(s: int, nbins: int): """ Generate lexicographically sorted non-negative ...
qc-tum/fermi_hubbard_commutators
fh_comm/combinatorics.py
.py
4643567055f0ce06
7.42
6
import math from fractions import Fraction import numpy as np from fh_comm.combinatorics import multinomial, integer_sum_tuples from fh_comm.splitting_method import SplittingMethod class WeightedNestedCommutator: """ Symbolic weighted nested commutator. A commutation index `i` is interpreted as [A_{i...
qc-tum/fermi_hubbard_commutators
fh_comm/comm_bound.py
.py
e73bc38e9291f3b6
7.42
6
from collections.abc import Sequence from fh_comm.lattice import SubLattice from fh_comm.hamiltonian_ops import HamiltonianOp from fh_comm.commutator import commutator, commutator_translation from fh_comm.simplification import simplify, translate_origin class NestedCommutatorTable: """ Evaluate all nested com...
qc-tum/fermi_hubbard_commutators
fh_comm/comm_table.py
.py
bdf5ec79dad114c4
7.42
6
import math import enum from numbers import Rational from collections.abc import Sequence from functools import cache import numpy as np from scipy import sparse from fh_comm.lattice import latt_coord_to_index, SubLattice class FieldOpType(enum.Enum): """ Fermionic field operator type. """ FERMI_CREAT...
qc-tum/fermi_hubbard_commutators
fh_comm/field_ops.py
.py
30b331f2561aa3ab
7.42
6
import math from itertools import product from collections.abc import Sequence import numpy as np def periodic_wrap(c: Sequence[int], shape: Sequence[int]) -> tuple: """ Periodic wrapping of coordinate `c` due to periodic boundary conditions for a rectangular unit cell of dimension `shape`. """ re...
qc-tum/fermi_hubbard_commutators
fh_comm/lattice.py
.py
1f7b20d9c299a461
7.42
6
import numpy as np class SplittingMethod: """ Splitting method described by the number of (Hamiltonian) terms (typically two, as for even-odd splitting), indices into these terms, and corresponding coefficients (time sub-step coefficients). """ def __init__(self, nterms: int, indices, coeffs, ...
qc-tum/fermi_hubbard_commutators
fh_comm/splitting_method.py
.py
503ad907c0eaf5a7
7.42
6
import itertools import unittest import fh_comm as fhc class TestCombinatorics(unittest.TestCase): def test_multinomial(self): """ Test multinomial evaluation. """ self.assertEqual(fhc.multinomial((3, 2, 7)), 7920) def test_integer_sum_tuples(self): """ Test i...
qc-tum/fermi_hubbard_commutators
test/test_combinatorics.py
.py
d11d60b082adf331
7.92
6
import itertools import unittest import scipy.sparse.linalg as spla import fh_comm as fhc class TestCommTable(unittest.TestCase): def test(self): # lattice size L = 4 # construct a sub-lattice for translations translatt = fhc.SubLattice([[2]]) # operators hlist = [...
qc-tum/fermi_hubbard_commutators
test/test_comm_table.py
.py
b525b76cbcb8b64b
7.92
6
from fractions import Fraction import unittest import numpy as np from scipy import sparse import scipy.sparse.linalg as spla import fh_comm as fhc class TestHamiltonianOps(unittest.TestCase): def test_hopping_op(self): """ Test hopping operator functionality. """ # lattice size ...
qc-tum/fermi_hubbard_commutators
test/test_hamiltonian_ops.py
.py
94a7500564fd3a1c
7.92
6
from __future__ import annotations import dataclasses from enum import IntEnum, StrEnum class BluetoothScanningMode(StrEnum): PASSIVE = "passive" ACTIVE = "active" class WeightUnit(IntEnum): """Weight units.""" KG = 0 # Kilograms LB = 1 # Pounds ST = 2 # Stones @dataclasses.dataclass ...
ronnnnnnnnnnnnn/etekcity_esf551_ble
src/etekcity_esf551_ble/data.py
.py
1f42037a230672b3
7.48
8
"""Advertisement-based scale model detection. Two manufacturer-data frame families are recognized. Company ID 1744 (Etekcity platform):: [0] bit-packed header: the low nibble is the advertisement format generation (0-2 all share this layout), the upper bits are flags that may vary betwee...
ronnnnnnnnnnnnn/etekcity_esf551_ble
src/etekcity_esf551_ble/detection.py
.py
808af83edf3e5277
7.48
8
"""EFS-A591S-KUS (Apex HR) scale — encrypted A5 GATT client.""" from __future__ import annotations from bleak.backends.characteristic import BleakGATTCharacteristic from bleak.backends.device import BLEDevice from ..const import ( ALIRO_CHARACTERISTIC_UUID, HEART_RATE_KEY, IMPEDANCE_KEY, WEIGHT_CHARA...
ronnnnnnnnnnnnn/etekcity_esf551_ble
src/etekcity_esf551_ble/efsa591s/scale.py
.py
04e2343f1f438992
7.48
8
"""EFS-C651-specific decoding layered on the shared encrypted A5 protocol.""" from __future__ import annotations from ..efsa591s import protocol as a5 _IMPEDANCE_OFFSET = 25 _IMPEDANCE_SIZE = 4 _NO_MEASUREMENT = 0xFFFFFF _MIN_IMPEDANCE_OHMS = 200 _MAX_IMPEDANCE_OHMS = 1200 def decode_impedance(plaintext: bytes) -...
ronnnnnnnnnnnnn/etekcity_esf551_ble
src/etekcity_esf551_ble/efsc651/protocol.py
.py
c1577f9f0afa6770
7.48
8
import struct import time from typing import NamedTuple from ..const import IMPEDANCE_500KHZ_KEY, IMPEDANCE_KEY, WEIGHT_KEY from ..data import WeightUnit CMD_SET_DISPLAY_UNIT = bytearray.fromhex("1309150010283700a0") CMD_END_MEASUREMENT = bytearray.fromhex("1f05151049") _EPOCH_OFFSET = 946656000 def build_unit_upda...
ronnnnnnnnnnnnn/etekcity_esf551_ble
src/etekcity_esf551_ble/esf24/protocol.py
.py
ad42d28efae308fc
7.48
8
"""ESF-24 scale implementation (experimental).""" import logging from bleak.backends.characteristic import BleakGATTCharacteristic from bleak.backends.device import BLEDevice from ..const import ( ALIRO_CHARACTERISTIC_UUID, WEIGHT_CHARACTERISTIC_UUID_NOTIFY, ) from ..scale import GattScale, ScaleSessionError...
ronnnnnnnnnnnnn/etekcity_esf551_ble
src/etekcity_esf551_ble/esf24/scale.py
.py
03eaf33f1df33a71
7.48
8
import struct from ..const import DISPLAY_UNIT_KEY, IMPEDANCE_KEY, WEIGHT_KEY UNIT_UPDATE_COMMAND = bytearray.fromhex("a522030500000163a10000") def parse(payload: bytearray) -> dict[str, int | float | None]: """ Parse raw data received from the ESF-551 scale. Args: payload (bytearray): Raw data...
ronnnnnnnnnnnnn/etekcity_esf551_ble
src/etekcity_esf551_ble/esf551/protocol.py
.py
1f3f5f89d8a7b563
7.48
8
"""ESF-551 scale implementation.""" from bleak.backends.characteristic import BleakGATTCharacteristic from bleak.backends.device import BLEDevice from ..scale import GattScale, ScaleSessionError from ..data import ScaleData, WeightUnit from ..const import ( ALIRO_CHARACTERISTIC_UUID, HW_REVISION_STRING_CHARAC...
ronnnnnnnnnnnnn/etekcity_esf551_ble
src/etekcity_esf551_ble/esf551/scale.py
.py
1cd9b7fb36ace33e
7.48
8
"""FIT8S scale implementation (advertisement-based).""" import logging from collections.abc import Callable from bleak.backends.scanner import BaseBleakScanner from ..const import DISPLAY_UNIT_KEY from ..scale import AdvertisementScale from ..data import BluetoothScanningMode, ScaleData, WeightUnit from .protocol im...
ronnnnnnnnnnnnn/etekcity_esf551_ble
src/etekcity_esf551_ble/fit8s/scale.py
.py
80f9ed0a70168120
7.48
8
"""Tests for advertisement-based model detection. Fixtures are real captured payloads (manufacturer-data value as reported by bleak/HA — the two-byte company ID already stripped). """ import logging from src.etekcity_esf551_ble import detection as detection_module from src.etekcity_esf551_ble.detection import ( ...
ronnnnnnnnnnnnn/etekcity_esf551_ble
tests/unit/test_detection.py
.py
3d99e514cb5d7521
7.98
8
""" Unit tests for the EFS-A591S A5 encrypted transport, validated against real captured frames from a live measurement session. Session-1 ground truth (recovered from captured frames): MAC = CF:EA:01:28:86:45 KE req d=41983 e=31 f=9840 -> g=16 KE resp h=20670 shared = 20670**16 mod 41983 = ...
ronnnnnnnnnnnnn/etekcity_esf551_ble
tests/unit/test_efsa591s_protocol.py
.py
1fdb7cd520ec24fc
7.98
8
""" Tests for the EFS-C651 protocol layer. Ground truth: two decrypted 0x4422 result frames captured from a real EFS-C651 (PacketLogger, 2026-08-05), together with the body fat percentage the vendor app displayed for the same measurement. Both frames decode to physiologically normal impedances, and each reproduces the...
ronnnnnnnnnnnnn/etekcity_esf551_ble
tests/unit/test_efsc651_protocol.py
.py
d8864c1cf74b9c37
7.98
8
""" Type shims for occasional missing types in certain edge cases. """ from . import deadcells from typing import Dict, Any def shims_for(name: str) -> Dict[str, Any]: match name: case "deadcells": return deadcells.TYPES raise ValueError("No such shim library! Maybe open a PR to add one?")...
N3rdL0rd/alivecells
savetool/web/py/hxbit/shims/init.py
.py
2564f574800a15f3
7.66
20