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 __future__ import annotations
from typing import TYPE_CHECKING, override
import numpy as np
from .module import Module
if TYPE_CHECKING:
from edutorch.nptypes import NPArray
class BatchNorm(Module):
def __init__(
self,
num_features: int,
train_mode: bool = True,
eps: f... | TylerYep/edutorch | edutorch/nn/batchnorm.py | .py | a08a9ac73b658be2 | 7.48 | 8 |
from __future__ import annotations
from typing import TYPE_CHECKING, override
import numpy as np
from .module import Module
if TYPE_CHECKING:
from edutorch.nptypes import NPArray
class Dropout(Module):
def __init__(
self, p: float, train_mode: bool = True, seed: int | None = None
) -> None:
... | TylerYep/edutorch | edutorch/nn/dropout.py | .py | 523c5eeaeb2c40f9 | 7.48 | 8 |
from typing import override
import numpy as np
from edutorch.nptypes import NPArray, NPIntArray
from .module import Module
class Embedding(Module):
def __init__(self, input_dim: int, output_dim: int) -> None:
super().__init__()
self.W = np.random.normal(scale=1e-3, size=(input_dim, output_dim))... | TylerYep/edutorch | edutorch/nn/embedding.py | .py | 6245d0399e1e17bd | 7.48 | 8 |
"""
This folder contains helper functions for common mathematical functions.
Note: this package is not equivalent to PyTorch's functional API, because
no backwards() methods are provided for these functions!
To use these functions as layers, please use the implementation in
layers/ or losses/ instead.
"""
import nump... | TylerYep/edutorch | edutorch/nn/functional/__init__.py | .py | 80e827e35f9ccdf6 | 7.48 | 8 |
from __future__ import annotations
from typing import TYPE_CHECKING, override
import numpy as np
from .module import Module
if TYPE_CHECKING:
from edutorch.nptypes import NPArray
class Linear(Module):
def __init__(self, input_dim: int, output_dim: int) -> None:
super().__init__()
self.w = ... | TylerYep/edutorch | edutorch/nn/linear.py | .py | ba9d2e1b276a91a8 | 7.48 | 8 |
from typing import override
import numpy as np
from edutorch.nptypes import NPArray
from .module import Module
class ReLU(Module):
@override
def forward(self, x: NPArray) -> NPArray:
"""
Computes the forward pass for a layer of rectified linear units (ReLUs).
Input:
- x: In... | TylerYep/edutorch | edutorch/nn/relu.py | .py | 085a06a8110914b0 | 7.48 | 8 |
from __future__ import annotations
from typing import TYPE_CHECKING, override
import numpy as np
from .module import Module
if TYPE_CHECKING:
from edutorch.nptypes import NPArray
class RNNCell(Module):
def __init__(self, prev_h: NPArray, Wx: NPArray, Wh: NPArray, b: NPArray) -> None:
super().__ini... | TylerYep/edutorch | edutorch/nn/rnn_cell.py | .py | b20b171998f4bc39 | 7.48 | 8 |
from __future__ import annotations
from typing import TYPE_CHECKING, override
from .batchnorm import BatchNorm
if TYPE_CHECKING:
from edutorch.nptypes import NPArray
class SpatialBatchNorm(BatchNorm):
@override
def forward(self, x: NPArray) -> NPArray:
"""
Computes the forward pass for ... | TylerYep/edutorch | edutorch/nn/spatial_batchnorm.py | .py | 644b3a4e4be4a8f0 | 7.48 | 8 |
from __future__ import annotations
from typing import TYPE_CHECKING, override
import numpy as np
from .module import Module
if TYPE_CHECKING:
from edutorch.nptypes import NPArray
class TemporalLinear(Module):
def __init__(self, input_dim: int, output_dim: int) -> None:
super().__init__()
s... | TylerYep/edutorch | edutorch/nn/temporal_linear.py | .py | d0876df7a568cb7c | 7.48 | 8 |
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, override
import numpy as np
from .optimizer import Optimizer
if TYPE_CHECKING:
from edutorch.nn.module import Module
from edutorch.nptypes import NPArray
@dataclass
class Adam(Optimizer):
"""
... | TylerYep/edutorch | edutorch/optim/adam.py | .py | 305e7c833af367ac | 7.48 | 8 |
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from edutorch.nn.module import Module
from edutorch.nptypes import NPArray
@dataclass
class Optimizer:
model: Module
def __post_init__(self) -> None:
self.context = s... | TylerYep/edutorch | edutorch/optim/optimizer.py | .py | ef8cb7136775b078 | 7.48 | 8 |
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, override
import numpy as np
from .optimizer import Optimizer
if TYPE_CHECKING:
from edutorch.nn.module import Module
from edutorch.nptypes import NPArray
@dataclass
class RMSProp(Optimizer):
"""... | TylerYep/edutorch | edutorch/optim/rmsprop.py | .py | 78a31c6a7ddfb4a1 | 7.48 | 8 |
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, override
from edutorch.optim.optimizer import Optimizer
if TYPE_CHECKING:
from edutorch.nn.module import Module
from edutorch.nptypes import NPArray
@dataclass
class SGD(Optimizer):
"""
Perfo... | TylerYep/edutorch | edutorch/optim/sgd.py | .py | f56fbc32533ad213 | 7.48 | 8 |
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, override
import numpy as np
from .optimizer import Optimizer
if TYPE_CHECKING:
from edutorch.nn.module import Module
from edutorch.nptypes import NPArray
@dataclass
class SGDMomentum(Optimizer):
... | TylerYep/edutorch | edutorch/optim/sgd_momentum.py | .py | c76fa092a9f5351e | 7.48 | 8 |
from __future__ import annotations
import random
from typing import TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from collections.abc import Callable
from edutorch.nn import Module
from edutorch.nptypes import NPAnyArray, NPArray
def rel_error(x: NPAnyArray, y: NPAnyArray) -> NPAnyArray:
"""... | TylerYep/edutorch | tests/gradient_check.py | .py | 9766b83b6b2fb5b0 | 7.98 | 8 |
import logging
import gunicorn.glogging
import cdislogging
import mds.config
class CDISLogger(gunicorn.glogging.Logger):
"""
Initialize root and gunicorn loggers with cdislogging configuration.
"""
@staticmethod
def _remove_handlers(logger):
"""
Use Python's built-in logging modu... | uc-cdis/metadata-service | deployment/wsgi/gunicorn.conf.py | .py | ecf1a8390f2bdb5f | 7.65 | 19 |
import logging
from logging.config import fileConfig
import time
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config fi... | uc-cdis/metadata-service | migrations/env.py | .py | 8b0a27fe4de15320 | 7.65 | 19 |
"""alias support
Revision ID: 3354f2c466ec
Revises: 4d93784a25e5
Create Date: 2022-08-04 14:53:41.476049
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "3354f2c466ec"
down_revision = "4d93784a25e5" # pragma: allowlis... | uc-cdis/metadata-service | migrations/versions/3354f2c466ec_alias_support.py | .py | d4e3b6d4e9c9d4c2 | 7.65 | 19 |
"""metadata
Revision ID: f96cb3b2c523
Revises:
Create Date: 2019-12-09 16:23:39.943713
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "f96cb3b2c523"
down_revision = None
branch_labels = None
depends_on = None
def upg... | uc-cdis/metadata-service | migrations/versions/f96cb3b2c523_metadata.py | .py | ca0d081b8e2762d8 | 7.65 | 19 |
"""
Support for aliases (alternative, unique names) for Metadata blobs
that already have a Globally Unique IDentifier (GUID).
It is always more efficient to use GUIDs as primary method
for naming blobs. However, in cases where you want multiple identifiers
to point to the same blob, aliases allow that without duplicat... | uc-cdis/metadata-service | src/mds/aliases.py | .py | 5d90bb3a168b8ea0 | 7.65 | 19 |
import argparse
import asyncio
import sys
from argparse import Namespace
from pathlib import Path
from typing import Any, Dict, List, Optional
from urllib.parse import urlparse
from pathvalidate import ValidationError, sanitize_filepath, validate_filepath
from mds import config, logger
from mds.agg_mds import adapter... | uc-cdis/metadata-service | src/mds/populate.py | .py | 1e3e306f29dd4e90 | 7.65 | 19 |
import respx
from mds.agg_mds.adapters import (
get_metadata,
get_json_path_value,
strip_email,
strip_html,
normalize_value,
normalize_tags,
add_icpsr_source_url,
FieldFilters,
get_json_path_value,
add_clinical_trials_source_url,
uppercase,
strip_leading_double_underscore... | uc-cdis/metadata-service | tests/test_agg_mds_adapters.py | .py | aa94ee7b215fa81c | 7.15 | 19 |
import httpx
import pytest
import urllib.parse
@pytest.mark.parametrize(
"guid,aliases",
[
("test_get_aliases", ["alias_a"]),
("dg.1234/test_get_aliases", ["alias_b"]),
("dg.2345/test_get_aliases", ["alias_b", "alias_b_2"]),
("dg.3456/test_get_aliases", ["1", "2", "3", "4", "5"... | uc-cdis/metadata-service | tests/test_aliases.py | .py | 59bb9a8c5933996c | 7.15 | 19 |
"""Use of this source code is governed by the MIT license found in the LICENSE file.
Plugwise Smile protocol helpers.
"""
from __future__ import annotations
from typing import cast
from plugwise.constants import (
ANNA,
DHW_SETPOINT,
GROUP_TYPES,
NONE,
PRIORITY_DEVICE_CLASSES,
SPECIAL_PLUG_T... | plugwise/python-plugwise | plugwise/common.py | .py | dbb2015db6321de2 | 7.59 | 14 |
"""Use of this source code is governed by the MIT license found in the LICENSE file.
Plugwise Smile protocol data-collection helpers.
"""
from __future__ import annotations
import re
from plugwise.constants import (
ADAM,
ANNA,
MAX_SETPOINT,
MIN_SETPOINT,
OFF,
ActuatorData,
GwEntityData,... | plugwise/python-plugwise | plugwise/data.py | .py | c8d857beffa66244 | 7.59 | 14 |
"""Use of this source code is governed by the MIT license found in the LICENSE file.
Plugwise Smile protocol data-collection helpers for legacy devices.
"""
from __future__ import annotations
# Dict as class
# Version detection
from plugwise.constants import OFF, GwEntityData
from plugwise.legacy.helper import Smile... | plugwise/python-plugwise | plugwise/legacy/data.py | .py | b7712eee102c185f | 7.59 | 14 |
"""Use of this source code is governed by the MIT license found in the LICENSE file.
Plugwise Smile protocol helpers.
"""
from __future__ import annotations
from typing import cast
from plugwise.common import SmileCommon
from plugwise.constants import (
ACTIVE_ACTUATORS,
ACTIVE_KEYS,
ACTUATOR_CLASSES,
... | plugwise/python-plugwise | plugwise/legacy/helper.py | .py | ee802b19f49d921b | 7.59 | 14 |
"""Use of this source code is governed by the MIT license found in the LICENSE file.
Plugwise Smile communication protocol helpers.
"""
from __future__ import annotations
from plugwise.constants import LOGGER
from plugwise.exceptions import (
ConnectionFailedError,
InvalidAuthentication,
InvalidXMLError,... | plugwise/python-plugwise | plugwise/smilecomm.py | .py | 16f2827ceabb23f2 | 7.59 | 14 |
"""Test Plugwise module Adam related functionality."""
import pytest
from .test_init import _LOGGER, TestPlugwise, pw_exceptions
SMILE_TYPE = "adam"
# Reoccuring constants
BADKAMER_SCHEMA = "Badkamer Schema"
CV_JESSIE = "CV Jessie"
GF7_WOONKAMER = "GF7 Woonkamer"
WERKDAG_SCHEMA = "Werkdag schema"
class TestPlugw... | plugwise/python-plugwise | tests/test_adam.py | .py | fbaefd90153047ab | 7.09 | 14 |
"""Test Plugwise module generic functionality."""
from unittest.mock import patch
import pytest
import aiohttp
from .test_init import _LOGGER, TestPlugwise, pw_exceptions
class TestPlugwiseGeneric(TestPlugwise): # pylint: disable=attribute-defined-outside-init
"""Tests for generic functionality."""
@pyt... | plugwise/python-plugwise | tests/test_generic.py | .py | 6ddbbdc07e2e1f9b | 8.09 | 14 |
"""Test Plugwise module Anna related functionality."""
import pytest
from .test_init import _LOGGER, TestPlugwise
SMILE_TYPE = "anna"
# Reoccuring constants
THERMOSTAT_SCHEDULE = "Thermostat schedule"
class TestPlugwiseAnna(TestPlugwise): # pylint: disable=attribute-defined-outside-init
"""Tests for Anna stan... | plugwise/python-plugwise | tests/test_legacy_anna.py | .py | fb81105f8d228097 | 7.09 | 14 |
"""Test Plugwise module generic functionality."""
import pytest
from .test_init import TestPlugwise, pw_exceptions
class TestPlugwiseGeneric(TestPlugwise): # pylint: disable=attribute-defined-outside-init
"""Tests for generic functionality."""
@pytest.mark.asyncio
async def test_fail_legacy_system(sel... | plugwise/python-plugwise | tests/test_legacy_generic.py | .py | 0dd5436c2ed24881 | 8.09 | 14 |
"""Test Plugwise module P1 related functionality."""
import pytest
from .test_init import _LOGGER, TestPlugwise
SMILE_TYPE = "p1"
class TestPlugwiseP1(TestPlugwise): # pylint: disable=attribute-defined-outside-init
"""Tests for P1."""
@pytest.mark.asyncio
async def test_connect_smile_p1_v2(self):
... | plugwise/python-plugwise | tests/test_legacy_p1.py | .py | 0ddd11db40d72177 | 7.09 | 14 |
"""Test Plugwise module Stretch related functionality."""
import pytest
from .test_init import _LOGGER, TestPlugwise
SMILE_TYPE = "stretch"
class TestPlugwiseStretch(TestPlugwise): # pylint: disable=attribute-defined-outside-init
"""Tests for Stretch."""
@pytest.mark.asyncio
async def test_connect_st... | plugwise/python-plugwise | tests/test_legacy_stretch.py | .py | 8e658e71e6f78f31 | 7.09 | 14 |
"""Test Plugwise module P1 related functionality."""
import pytest
from .test_init import _LOGGER, TestPlugwise, pw_exceptions
SMILE_TYPE = "p1"
class TestPlugwiseP1(TestPlugwise): # pylint: disable=attribute-defined-outside-init
"""Tests for P1."""
@pytest.mark.asyncio
async def test_connect_p1v4_44... | plugwise/python-plugwise | tests/test_p1.py | .py | 6c26cb035195c581 | 7.09 | 14 |
"""List relevant release versions from PyPI for the specified package.
Filters based on requested minimum number of releases and release age."""
import argparse
from datetime import datetime, timedelta
import sys
from typing import List
import requests
def get_relevant_releases(package: str, days: int, minimum: int) ... | batfish/docker | get_pypi_versions.py | .py | 34fa025bf57baa02 | 7.59 | 14 |
"""The ``lost_years`` command: install life tables and report on them."""
import argparse
import logging
import sys
from pathlib import Path
from .datasets import DATA_DIR_ENV, ValidationError, data_dir
from .sources import REGISTRY, SourceUnavailableError
from .update import status, update
logger = logging.getLogge... | gojiplus/lost-years | lost_years/cli.py | .py | 68054a011fe4ae20 | 7.48 | 8 |
"""Where life tables live on disk, and how one is replaced without tearing.
Only the SSA table ships inside the wheel. HLD is redistributed under terms that
ask users to fetch their own copy, and the WHO table is large enough that
shipping it makes the package stale the day it is published, so both are
downloaded by `... | gojiplus/lost-years | lost_years/datasets.py | .py | 2b4b387a2275206e | 7.48 | 8 |
"""HLD (Human Life-Table Database) module for lost_years package.
The pooled HLD file is a collection of life tables *as they were published*,
not one estimate per country-year: a single country-year is often covered by
several tables that differ in geography (whole country vs. a province),
sub-population (urban/rural... | gojiplus/lost-years | lost_years/hld.py | .py | 1d96f02cf6124068 | 7.48 | 8 |
"""Fetch the pooled Human Life-Table Database file and derive the lookup table.
lifetable.de asks that users download their own copy rather than be handed one
("Please do not pass your copy of these data to other users. Rather refer them
to the HLD website, where they may download the data for themselves"), so this
pa... | gojiplus/lost-years | lost_years/sources/hld.py | .py | 6a3cc3e906e9c5be | 7.48 | 8 |
"""Fetch the SSA period life table and derive the shipped lookup table.
This is the one table the wheel ships. It is a US federal work in the public
domain and it is 10 KB, so the package answers US questions the moment it is
installed, with no download and no network.
The table is the Actuarial Life Table at
``ssa.g... | gojiplus/lost-years | lost_years/sources/ssa.py | .py | c969574e567174ec | 7.48 | 8 |
"""Fetch WHO life expectancy at birth from the Global Health Observatory.
GHO datasets are CC BY 4.0, so redistribution would be allowed; the table is
fetched rather than shipped because a packaged copy is stale the day WHO
publishes a revision and nothing in the wheel would say so. The OData endpoint
is public and ne... | gojiplus/lost-years | lost_years/sources/who.py | .py | 31298b5c5399c0e2 | 7.48 | 8 |
"""SSA (US Social Security Administration) period life tables for lost_years."""
import argparse
import logging
import sys
import pandas as pd
import pyarrow.parquet as pq
from .datasets import resolve
from .utils import closest, column_exists, fixup_columns
# Setup logger
logger = logging.getLogger(__name__)
# Th... | gojiplus/lost-years | lost_years/ssa.py | .py | c0f2c9b32147fceb | 7.48 | 8 |
"""Install a life table: download, build, validate, then swap it into place.
Nothing is ever written over a working table until a candidate has passed every
check, so an upstream that truncates a file, renames a column, or ships a table
that no longer reproduces the published figures leaves the user with what they
alr... | gojiplus/lost-years | lost_years/update.py | .py | 366a4c10c7656723 | 7.48 | 8 |
"""Shared helpers for reading input frames and matching to life-table rows."""
import logging
from pathlib import Path
from typing import TYPE_CHECKING, Any
import pandas as pd
import requests
if TYPE_CHECKING:
import numpy as np
import numpy.typing as npt
# Setup logger
logger = logging.getLogger(__name__)... | gojiplus/lost-years | lost_years/utils.py | .py | 549b2476cc93edc2 | 7.48 | 8 |
"""WHO (World Health Organization) life expectancy tables for lost_years.
The WHO table is GHO indicator WHOSIS_000001, *life expectancy at birth*. It
has no age dimension: one value per population, year and sex. The lookup
therefore answers questions about age 0 only, and says so in the name of the
column it returns.... | gojiplus/lost-years | lost_years/who.py | .py | 63e18a201902a6dc | 7.48 | 8 |
"""Seed the life-table cache from the repository, so no test needs the network.
The tables the lookups read are not shipped in the wheel; they are installed by
``lost_years update``. The raw upstream artifacts they are built from *are* in
the repository under ``data/<source>/source/``, so the suite builds the tables
f... | gojiplus/lost-years | tests/conftest.py | .py | c09f7f72720f56af | 7.98 | 8 |
"""Tests for lost_years package."""
import logging
import pandas as pd
import pytest
from lost_years import lost_years_hld, lost_years_ssa, lost_years_who
# SSA period life table, 2022, remaining years at exact age.
SSA_2022 = {("M", 0): 74.74, ("F", 0): 80.18, ("M", 30): 46.51, ("F", 65): 20.12}
# WHO indicator W... | gojiplus/lost-years | tests/test_010_lost_years.py | .py | c8f6b6d6fc82a779 | 7.98 | 8 |
"""End-to-end tests for the three command line entry points."""
import pandas as pd
import pytest
from lost_years import TableUnavailableError, hld, ssa, who
@pytest.fixture
def input_csv(tmp_path):
"""Write a small input file.
Args:
tmp_path: pytest temporary directory.
Returns:
Path ... | gojiplus/lost-years | tests/test_cli.py | .py | 600be9fb91ce19ba | 7.98 | 8 |
"""Tests for the update pipeline: schemas, manifests, and refusing bad data.
The point of the pipeline is that a bad upstream cannot become the user's data.
Most of what is asserted here is therefore a *refusal*: a truncated archive, a
scrambled table and an archive with the wrong shape each have to be rejected,
and t... | gojiplus/lost-years | tests/test_data_pipeline.py | .py | 0f3fd208e0963f7f | 7.98 | 8 |
"""Value-level regression tests for the HLD selection rule.
The oracle is the US National Center for Health Statistics. NCHS publishes male
life expectancy at birth of 76.2 (2018), 76.3 (2019), 74.2 (2020) and 73.5
(2021); HLD carries the same tables to two decimals. A wrong table choice moves
these numbers by whole y... | gojiplus/lost-years | tests/test_hld_selection.py | .py | 50b2242c8ad47097 | 7.98 | 8 |
"""Tests for the `lost_years` command and the SSA parse it drives.
The SSA parser is exercised against a real archived ssa.gov page — the
Actuarial Life Table for 2021, a different release from the one the wheel
ships — rather than a fixture written to match the parser. ssa.gov refuses
automated clients from many netw... | gojiplus/lost-years | tests/test_update_cli.py | .py | 2eabcfab7713d41c | 7.98 | 8 |
"""Tests for utils module."""
import logging
import tempfile
from pathlib import Path
from unittest.mock import Mock, patch
import numpy as np
import pandas as pd
import pytest
from lost_years.utils import (
closest,
column_exists,
download_file,
fixup_columns,
isstring,
)
class TestUtilFunctio... | gojiplus/lost-years | tests/test_utils.py | .py | 828fb4bae203cbfa | 7.98 | 8 |
"""Annotation module for Edge AI Person Detection.
Provides:
- AnnotationRenderer: Draws color-coded bounding boxes, confidence labels,
and FPS overlay on video frames
- FPSCalculator: Calculates rolling average FPS over a 2-second window
Uses OpenCV for drawing operations directly on numpy arrays — no image
format... | cradlepoint/container-samples | containers/edge_ai/src/annotation.py | .py | 6413edb2cebe4279 | 7.5 | 9 |
"""RTSP Video Capture module for Edge AI Person Detection.
Manages RTSP connection, frame decoding, disconnection detection,
and automatic reconnection with exponential backoff.
Uses PyAV (ffmpeg wrapper) for RTSP streaming instead of OpenCV
for a smaller container footprint.
Requirements: 1.1, 1.2, 1.3, 1.4, 1.6, 1... | cradlepoint/container-samples | containers/edge_ai/src/capture.py | .py | 06271cb16df680c3 | 7.5 | 9 |
"""Inference Engine for Edge AI Person Detection.
Uses TensorFlow Lite with XNNPACK delegate for optimized ARM64 CPU
inference. Loads a quantized SSD MobileNet V2 model and filters
detections to person class (COCO class 0) above a configurable
confidence threshold.
Performance optimizations:
- Multi-threaded inferenc... | cradlepoint/container-samples | containers/edge_ai/src/inference.py | .py | a9e5da238576452b | 7.5 | 9 |
"""Application entry point for Edge AI Person Detection.
Initializes all components, starts processing and web server threads,
and handles graceful shutdown on SIGTERM/SIGINT.
Requirements: 1.1, 1.6, 2.7, 7.5, 7.7, 8.2, 10.1, 10.4
"""
import sys
import os
import signal
import threading
import time
# Add parent direc... | cradlepoint/container-samples | containers/edge_ai/src/main.py | .py | 9ebb2c5c0219c5e6 | 7.5 | 9 |
"""Shared data models for Edge AI Person Detection.
Defines the core dataclasses used across the application:
- Detection: A single person detection result with normalized coordinates
- AppConfig: Application configuration loaded from router appdata
- RuntimeStats: Operational statistics for monitoring
- validate_dete... | cradlepoint/container-samples | containers/edge_ai/src/models.py | .py | 6e0853494365f9fa | 7.5 | 9 |
"""Frame Processor module for Edge AI Person Detection.
Orchestrates the main processing pipeline: capture -> resize -> infer ->
annotate -> store. Manages frame pacing, adaptive rate control, and
thread-safe access to the current annotated frame.
Performance optimizations:
- Skip annotation when no clients are conne... | cradlepoint/container-samples | containers/edge_ai/src/processor.py | .py | 3fc8172182b62ec3 | 7.5 | 9 |
"""Property-based test for adaptive rate reduction on high latency.
Tests Property 11: Adaptive Rate Reduction on High Latency.
For any current target FPS f > 1 and a sequence of 10 consecutive
inference latencies all exceeding 1000ms, the adjusted target FPS
SHALL equal max(f // 2, 1).
**Validates: Requirements 9.4*... | cradlepoint/container-samples | containers/edge_ai/tests/test_adaptive_rate_property.py | .py | c656bdb22a955fa0 | 8 | 9 |
"""Unit tests for FPSCalculator class."""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
from annotation import FPSCalculator
class TestFPSCalculator:
"""Tests for FPSCalculator."""
def test_returns_zero_with_no_timestamps(self):
"""FPS should be 0.0 w... | cradlepoint/container-samples | containers/edge_ai/tests/test_annotation.py | .py | 612e1ca76634293d | 8 | 9 |
"""Unit tests for AnnotationRenderer class.
Validates: Requirements 3.4, 3.5, 3.7
"""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
import numpy
from annotation import AnnotationRenderer, BBOX_THICKNESS
from models import Detection
class TestAnnotationRendererZeroDe... | cradlepoint/container-samples | containers/edge_ai/tests/test_annotation_renderer.py | .py | b75c0edd50e51dbe | 7 | 9 |
"""Property-based test for exponential backoff computation.
Tests Property 1: Exponential Backoff Computation.
For any retry count n >= 0, the computed backoff delay SHALL equal
min(2^(n+1), 60) seconds, always producing a value in the range [2, 60].
**Validates: Requirements 1.3**
"""
from hypothesis import given, s... | cradlepoint/container-samples | containers/edge_ai/tests/test_backoff_property.py | .py | 148ed0ba2bbd41fe | 8 | 9 |
"""Property-based test for bounding box clipping to frame boundaries.
Tests Property 6: Bounding Box Clipping to Frame Boundaries.
For any bounding box with pixel coordinates (x1, y1, x2, y2) -- including
values outside frame dimensions -- and any frame of size (W, H) where W > 0
and H > 0, the clipped bounding box SH... | cradlepoint/container-samples | containers/edge_ai/tests/test_bbox_clipping_property.py | .py | dee7eb06156f32b4 | 8 | 9 |
"""Unit tests for RTSPCapture module.
Tests specific example scenarios for RTSP connection management,
frame reading, disconnection detection, and exponential backoff.
Requirements: 1.1, 1.3, 1.4, 1.6, 1.7
"""
import time
import threading
from unittest.mock import patch, MagicMock, PropertyMock
import numpy as np
im... | cradlepoint/container-samples | containers/edge_ai/tests/test_capture.py | .py | 3fabfceac9884e48 | 7 | 9 |
"""Property-based test for confidence-to-color mapping and label formatting.
Tests Property 5: Confidence-to-Color Mapping and Label Formatting.
For any confidence score c in [0.0, 1.0]:
- if c < 0.35 the color SHALL be red (BGR: 0, 0, 255)
- if 0.35 <= c < 0.5 the color SHALL be orange (BGR: 0, 128, 255)
- if 0.5 <= ... | cradlepoint/container-samples | containers/edge_ai/tests/test_confidence_color_property.py | .py | 69aa4bb493e0c345 | 8 | 9 |
"""Unit tests for ConfigLoader.
Tests specific example scenarios for configuration loading:
- Missing RTSP URL logs warning and returns empty string
- Invalid config values fall back to defaults
- cp.get_appdata() returns None for missing fields — defaults applied
Validates: Requirements 8.2, 8.3, 8.5
"""
import sys
... | cradlepoint/container-samples | containers/edge_ai/tests/test_config.py | .py | c94dcacfd7318760 | 7 | 9 |
"""Property-based tests for configuration loading with defaults.
Tests Property 9: Configuration Loading with Defaults.
For any appdata dictionary with an arbitrary subset of optional fields missing,
the loaded configuration SHALL use the following defaults for missing fields:
confidence_threshold=0.4, web_port=8080, ... | cradlepoint/container-samples | containers/edge_ai/tests/test_config_loading_defaults.py | .py | c648db1b8a64890e | 8 | 9 |
"""Property-based test for detection filtering.
Tests Property 3: Detection Filtering — Person Class Above Threshold.
For any list of raw detections with mixed class IDs and confidence scores,
and any confidence threshold t in [0.0, 1.0], the filtered result SHALL
contain only detections where class_id == 0 AND confid... | cradlepoint/container-samples | containers/edge_ai/tests/test_detection_filtering_property.py | .py | 96ac1910b0a2c0bf | 7 | 9 |
"""Property-based test for FPS calculation over rolling window.
Tests Property 7: FPS Calculation Over Rolling Window.
For any sequence of N >= 2 monotonically increasing timestamps within a
2-second window, the calculated FPS SHALL equal (N-1) / (last - first),
rounded to 1 decimal place. For fewer than 2 timestamps,... | cradlepoint/container-samples | containers/edge_ai/tests/test_fps_property.py | .py | 63275295831d9e43 | 8 | 9 |
"""Property-based test for frame pacing sleep duration.
Tests Property 10: Frame Pacing Sleep Duration.
For any target_fps in [1, 60] and any elapsed processing time e >= 0,
the computed sleep duration SHALL equal max(0, (1.0 / target_fps) - e).
The sleep duration SHALL never be negative.
**Validates: Requirements 1.... | cradlepoint/container-samples | containers/edge_ai/tests/test_frame_pacing_property.py | .py | 79df94b8ef3959d6 | 8 | 9 |
"""Property-based test for frame resize dimensions.
Tests Property 2: Frame Resize Preserves Target Dimensions.
For any input frame with dimensions (w, h) where w > 0 and h > 0,
and any target model input size (tw, th) where tw > 0 and th > 0,
resizing the frame SHALL produce an output with dimensions exactly (tw, th)... | cradlepoint/container-samples | containers/edge_ai/tests/test_frame_resize_property.py | .py | 639568f1d8cd1d13 | 7 | 9 |
"""Unit tests for InferenceEngine.
Tests specific example scenarios for inference engine behavior:
- Model load failure prevents inference attempts
- Inference failure on frame logs error and continues
- Threshold update applies to subsequent detections
Validates: Requirements 2.7, 2.8, 6.2
"""
import sys
from unitte... | cradlepoint/container-samples | containers/edge_ai/tests/test_inference.py | .py | f73965338d6ce7fa | 7 | 9 |
"""Unit tests for main.py initialization.
Tests specific example scenarios for application entry point behavior:
- Startup with missing RTSP URL serves config page (web server only)
- Startup logs version, model name, RTSP URL, and threshold
- Model load failure exits non-zero
Validates: Requirements 8.2, 10.1, 7.7
"... | cradlepoint/container-samples | containers/edge_ai/tests/test_main.py | .py | b5d8ac23e431e74c | 7 | 9 |
"""Property-based tests for Detection output normalization.
Tests Property 4: Detection Output Normalization Invariant.
For any Detection, all bounding box coordinates are in [0.0, 1.0],
x_min < x_max, y_min < y_max, confidence in [0.0, 1.0].
**Validates: Requirements 2.3**
"""
from hypothesis import given, settings,... | cradlepoint/container-samples | containers/edge_ai/tests/test_models.py | .py | 03507913fc07c05d | 7 | 9 |
"""Unit tests for FrameProcessor.
Tests specific example scenarios for frame processor behavior:
- resize_frame produces correct output dimensions
- compute_sleep_duration returns correct values
- check_adaptive_rate reduces and restores FPS correctly
- current_frame property is thread-safe
- process_loop orchestrates... | cradlepoint/container-samples | containers/edge_ai/tests/test_processor.py | .py | c9f12dabee7a7bd2 | 7 | 9 |
"""Property-based test for rate restoration on recovered latency.
Tests Property 12: Rate Restoration on Recovered Latency.
For any reduced operating FPS and configured target FPS, when 10 consecutive
inference latencies are all below 500ms, the operating FPS SHALL be restored
to the configured target FPS value.
**Va... | cradlepoint/container-samples | containers/edge_ai/tests/test_rate_restoration_property.py | .py | c668793557d50c5d | 8 | 9 |
"""Configuration via NCOS appdata.
Every setting is read with ``cp.get_appdata()`` and self-provisions its default
with ``cp.put_appdata()`` on first run, so a fresh deployment produces a
complete, editable set of fields in NCM without the user guessing key names.
All appdata values are strings. Everything here parse... | cradlepoint/container-samples | containers/gpsd_server/src/config.py | .py | 9c839c314bfe7a9d | 7.5 | 9 |
"""Poll the router's Config Store for GPS fixes.
Polling was chosen over consuming the router's native NMEA stream so the data
path through cs.sock stays explicit and the sample works on any model without
first configuring a GPS connection. ``status/gps`` is common across models.
The poller emits a Fix on every cycle... | cradlepoint/container-samples | containers/gpsd_server/src/gps_source.py | .py | 663489d1f7d7b72e | 7.5 | 9 |
"""Data models for the gpsd server.
Kept as plain dataclasses so the whole application stays dependency-free
beyond the standard library and cp.py.
"""
import math
import time
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
@dataclass
class Fix:
"""A single GPS fix sampled ... | cradlepoint/container-samples | containers/gpsd_server/src/models.py | .py | 5f208036638dad93 | 7.5 | 9 |
"""NMEA 0183 sentence synthesis from a Config Store fix.
The router reports position as degrees/minutes/seconds with the sign carried on
the degree component. cp.dec() converts that to signed decimal degrees; NMEA
then wants it back as ``ddmm.mmmm`` plus a separate hemisphere character, so the
sign has to be stripped ... | cradlepoint/container-samples | containers/gpsd_server/src/nmea.py | .py | 154e53f3de0c060d | 7.5 | 9 |
#!/usr/bin/env python3
"""Read SNMP config from router config + appdata, write snmpd.conf."""
import cp
def get_appdata(name):
return cp.get_appdata(name) or ''
def main():
snmp_port = get_appdata('snmp_port') or '1161'
# Read router's SNMP config so our agent matches
snmp_cfg = cp.get('config/syst... | cradlepoint/container-samples | containers/snmp_agent/gen_conf.py | .py | 55759a9e839fbdc2 | 7.5 | 9 |
import os
from time import time
import traceback
import h5py
from lume.base import CommandWrapper
import lume.tools as lume_tools
from genesis import parsers, tools, lattice, writers, archive
from genesis.particles import final_particles
class Genesis2(CommandWrapper):
"""
Files will be written into a temp... | lume-science/lume-genesis | genesis/genesis2.py | .py | b6ce9cf005e82c49 | 7.54 | 11 |
#
# Interactive plotting using bokeh
from bokeh import palettes
from bokeh.plotting import figure, ColumnDataSource
from bokeh.models.widgets import Slider
from bokeh.layouts import column
import numpy as np
pal = palettes.Viridis[256]
def interactive_field_history(doc, fld=None, islice=0, dgrid=0):
"""
U... | lume-science/lume-genesis | genesis/interactive.py | .py | 2b9ccd893760cf9e | 7.54 | 11 |
from genesis import archive, lattice, parsers, tools, writers
from genesis.particles import final_particles
import lume.tools as lume_tools
import h5py
import tempfile
from time import time
from copy import deepcopy
import shutil
import os
def find_genesis2_executable(genesis_exe=None, verbose=False):
"""
S... | lume-science/lume-genesis | genesis/old_genesis.py | .py | 165f8cf38b9c88ef | 7.54 | 11 |
import copy
from contextlib import contextmanager
from typing import Sequence
import h5py
import matplotlib.animation
import matplotlib.pyplot as plt
import numpy as np
import prettytable
import pytest
from typing import Literal
from ... import tools
from ...tools import DisplayOptions
from ...version4 import Genesis... | lume-science/lume-genesis | genesis/tests/genesis4/conftest.py | .py | 3ed259afa0bdbb50 | 7.04 | 11 |
"""
This file contains conversions of example notebooks to regular Python.
The goal here is to run those example notebooks relatively quickly so that
the majority of their functionality can be covered in the test suite.
Running the notebooks themselves (as in `jupyter execute`) will be performed
as part of the docume... | lume-science/lume-genesis | genesis/tests/genesis4/test_notebooks.py | .py | 7f5a373e1c60d399 | 7.04 | 11 |
import pathlib
import time
from math import pi, sqrt
import matplotlib.pyplot as plt
import numpy as np
import pytest
from beamphysics import ParticleGroup
from scipy.constants import c
from ...version4 import Genesis4, Genesis4Input, Lattice, MainInput, Reference
from ...version4.input import (
Beam,
Drift,
... | lume-science/lume-genesis | genesis/tests/genesis4/test_run_particles.py | .py | e135f0100373aff0 | 7.04 | 11 |
from __future__ import annotations
import datetime
import json
import logging
import pathlib
from typing import (
Any,
Dict,
Literal,
Optional,
Tuple,
TypeVar,
Union,
)
import h5py
import numpy as np
import pydantic
from beamphysics import ParticleGroup
from beamphysics.units import pmd_un... | lume-science/lume-genesis | genesis/version4/archive.py | .py | 0869a94f482c58e0 | 7.54 | 11 |
from __future__ import annotations
import pathlib
import pydantic
from typing import Union
from beamphysics import Wavefront
from beamphysics.units import Z0
import h5py
import numpy as np
from . import readers
from .types import (
AnyPath,
BaseModel,
FieldFileParams,
FileKey,
NDArray,
)
def g... | lume-science/lume-genesis | genesis/version4/field.py | .py | 7ed84251d59addf8 | 7.54 | 11 |
from __future__ import annotations
import ast
import functools
import pathlib
from typing import Dict, Optional, Set, Tuple, TypedDict, Union
AnyPath = Union[pathlib.Path, str]
MODULE_PATH = pathlib.Path(__file__).resolve().parent
dataclasses_template = MODULE_PATH / "dataclasses.tpl"
renames = {
# NOTE: 'type'... | lume-science/lume-genesis | genesis/version4/input/manual.py | .py | 88c140d54dde6699 | 7.54 | 11 |
from __future__ import annotations
from pydantic import BaseModel
from typing import (
Any,
Dict,
Tuple,
Type,
)
import pathlib
import lark
from ..types import (
AnyPath,
ValueType,
Reference,
)
MAIN_INPUT_GRAMMAR = pathlib.Path("version4") / "input" / "main_input.lark"
LATTICE_GRAMMAR = ... | lume-science/lume-genesis | genesis/version4/input/parsers.py | .py | 3a4fdfd13cc2da41 | 7.54 | 11 |
import uuid
from typing import Iterable
from ..types import ValueType
def python_to_namelist_value(value: ValueType) -> str:
"""
Convert a Python value to its NameList representation.
Parameters
----------
value : ValueType
The Python value to convert.
Returns
-------
str
... | lume-science/lume-genesis | genesis/version4/input/util.py | .py | 2f21d1f1694c62c2 | 7.54 | 11 |
from ..input import Quadrupole, Corrector, Drift, Marker, Undulator
from ..input import Setup, Field, Track, Beam
from beamphysics.units import mec2
from scipy.constants import c
from math import pi, sqrt
import numpy as np
def label_from_bmad_name(bmad_name: str) -> str:
"""
Formats a label by standardizi... | lume-science/lume-genesis | genesis/version4/interfaces/bmad.py | .py | db6adaf3c498de91 | 7.54 | 11 |
from __future__ import annotations
import pathlib
from typing import Any, Literal
import h5py
from beamphysics import ParticleGroup
from .field import FieldFile
from .particles import load_particle_group
from .types import BaseModel, FileKey
class HDF5ReferenceFile(BaseModel):
"""An externally-referenced HDF5 ... | lume-science/lume-genesis | genesis/version4/loadable.py | .py | 2481c7b140a7a5bb | 7.54 | 11 |
import keyword
import os
import re
import warnings
from typing import Union
import h5py
import numpy as np
import pydantic.alias_generators
from lume import tools
from lume.parsers.namelist import parse_simple_namelist, parse_unrolled_namelist
from beamphysics.units import e_charge, known_unit, mec2, pmd_unit
# Patch... | lume-science/lume-genesis | genesis/version4/parsers.py | .py | 5e669fd56aaeb8be | 7.54 | 11 |
import numpy as np
def FEL_process_real(
npart,
z_steps,
kappa_1,
density,
Kai,
ku,
delt,
dels,
deta,
thet_init,
eta_init,
N_real,
s_steps,
E02=0,
verbose=False,
):
"""
SASE FEL process.
(opt=='sase')
"""
if verbose:
print("FEL... | slaclab/zfel | zfel/fel.py | .py | 71ad5966d4faa2b6 | 7.56 | 12 |
import numpy as np
def general_load_bucket(
npart,
Ns,
coopLength,
s_steps,
dels,
hist_rule="square-root",
particle_position=None,
gbar=0,
delg=None,
iopt="sase",
):
"""
random initialization of the beam load_bucket
inputs:
npart # n-macro-particles... | slaclab/zfel | zfel/particles.py | .py | ee6951ab992575fb | 7.56 | 12 |
import numpy as np
import scipy
from scipy import special
from zfel.particles import general_load_bucket
from zfel.fel import FEL_process_complex, final_calc
# Some constant values
alfvenCurrent = 17045.0 # Alfven current ~ 17 kA
mc2 = 0.51099906e6 # 510.99906E-3 # Electron rest mass in eV
c = 2.99792458e8 # ... | slaclab/zfel | zfel/sase1d.py | .py | 5ea1ee202a390e6a | 7.56 | 12 |
"""
Script of extracting data from pickle files
By Bin Wang
"""
# import numpy as np
import glob
import os
import pickle
import sys
import pandas as pd
# define a function of extracting data from files in .pickle
def get_pickled_data(key):
datalist = []
# single run
filelist = glob.glob(key + "_" + "202... | DEMENT-Model/DEMENTpy | SPA/scripts/data_extraction.py | .py | 3b9af55c79e2bba1 | 7.62 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.