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
# Copyright (c) 2021 Paul Saunders """--- Day 7: The Treachery of Whales --- A giant whale has decided your submarine is its next meal, and it's much faster than you are. There's nowhere to run! Suddenly, a swarm of crabs (each in its own tiny submarine - it's too deep for them otherwise) zooms in to rescue you! They ...
darac/adventofcode
src/aoc/year2021/day07.py
.py
989c03293e09ecf6
7
0
# Copyright (c) 2021 Paul Saunders # spell-checker: disable """--- Day 9: Smoke Basin --- These caves seem to be lava tubes. Parts are even still volcanically active; small hydrothermal vents release smoke into the caves that slowly settles like rain. If you can model how the smoke flows through the caves, you might b...
darac/adventofcode
src/aoc/year2021/day09.py
.py
4bd8e0d347c964c9
7
0
# Copyright (c) 2021 Paul Saunders """ --- Day 11: Dumbo Octopus --- """ import logging from typing import Literal import numpy as np from aocd import submit from aocd.models import Puzzle from aoc.visualisations.Numpy import Visualiser LOG = logging.getLogger(__name__) def get_neighbours( r: int, c: int, row...
darac/adventofcode
src/aoc/year2021/day11.py
.py
ab3e89a6ec612ca4
7
0
# Copyright (c) 2021 Paul Saunders """ --- Day 13: Transparent Origami --- """ import logging import os import re import sys from typing import Literal import numpy as np from aocd import submit from aocd.models import Puzzle from aoc.visualisations.Numpy import Visualiser LOG = logging.getLogger(__name__) def cr...
darac/adventofcode
src/aoc/year2021/day13.py
.py
b2cf8fd3e755feb1
7
0
# Copyright (c) 2023 Paul Saunders # spell-checker: disable """ --- Day 1: Trebuchet?! --- Something is wrong with global snow production, and you've been selected to take a look. The Elves have even given you a map; on it, they've used stars to mark the top fifty locations that are likely to be having problems. You'v...
darac/adventofcode
src/aoc/year2023/day01.py
.py
73fcd9de7f070b15
7
0
# Copyright (c) 2023 Paul Saunders # spell-checker: disable """ --- Day 2: Cube Conundrum --- You're launched high into the atmosphere! The apex of your trajectory just barely reaches the surface of a large island floating in the sky. You gently land in a fluffy pile of leaves. It's quite cold, but you don't see much ...
darac/adventofcode
src/aoc/year2023/day02.py
.py
ad00cbe0edc5f66e
7
0
# Copyright (c) 2023 Paul Saunders # spell-checker: disable """ --- Day 6: Wait For It --- The ferry quickly brings you across Island Island. After asking around, you discover that there is indeed normally a large pile of sand somewhere near here, but you don't see anything besides lots of water and the small island w...
darac/adventofcode
src/aoc/year2023/day06.py
.py
104a204ddc8657f9
7
0
# Copyright (c) 2023 Paul Saunders # spell-checker: disable """ --- Day 7: Camel Cards --- Your all-expenses-paid trip turns out to be a one-way, five-minute ride in an airship. (At least it's a cool airship!) It drops you off at the edge of a vast desert and descends back to Island Island. "Did you bring the parts?"...
darac/adventofcode
src/aoc/year2023/day07.py
.py
5214c01fd9d43dea
7
0
"""Tests for calculator module""" import pytest from src.calculator import add, subtract, multiply, divide, power, absolute class TestAddition: """Tests for add function""" def test_add_positive_numbers(self): """Test adding two positive numbers""" assert add(2, 3) == 5 def test_add_neg...
paramraghavan/beginners-py-learn
quick101/code_review/coverage_example/tests/test_calculator.py
.py
2fadf8e3cf63a7cf
7.65
1
"""Functional Tests for User Management Workflows""" import pytest from src.user import UserService, UserAlreadyExistsError, InvalidCredentialsError @pytest.fixture def user_service(): """Fresh user service for each test""" return UserService() class TestUserSignupWorkflow: """FUNCTIONAL TEST: Complete...
paramraghavan/beginners-py-learn
quick101/code_review/functional_test_example/tests/functional/test_user_workflows.py
.py
a2c5a907955e8244
7.65
1
""" # Inherit from Exception (or a more specific exception type) # Use pass for simple exceptions that don't need custom behavior # Override __init__() to accept custom parameters # Call super().__init__() to properly initialize the base exception # Override __str__() for better error messages """ # Basic custom exce...
paramraghavan/beginners-py-learn
quick101/custom_exeption.py
.py
73e60dda152936f1
7.15
1
#!/usr/bin/env python3 """ Scan all files in that folder (recursively) and generate: cheatsheet/index.md (Markdown index — Markdown files open as rendered Markdown on GitHub) cheatsheet/index.html (HTML index — HTML files render as HTML in a browser) In index.md, HTML links include a “Preview” link that renders HTML vi...
paramraghavan/beginners-py-learn
quick101/folder_to_index_file_generator.py
.py
ac9e11674618abc9
7.15
1
import pkg_resources import subprocess import sys from collections import defaultdict def is_package_installed(package_name): """ Check if a package is installed in the current environment. Args: package_name (str): Name of the package to check Returns: bool: True if installed, False...
paramraghavan/beginners-py-learn
quick101/package_dependency_analyzer.py
.py
4105c202bc74c4fc
7.15
1
#!/usr/bin/env python3 """ Import Path Analyzer - Tracks imports and execution paths Usage: python import_path_analyzer.py your_script.py [script arguments] Options: --user-only Show only user-defined packages (non-standard library) --export=FORMAT Export results (json, csv, html) """ import sys ...
paramraghavan/beginners-py-learn
quick101/python_import_order/import_path_analyzer.py
.py
a09697cc53dd2acc
7.15
1
#!/usr/bin/env python3 """ Import Tracker - A cleaner alternative to python -v Usage: python import_tracker.py your_script.py [script arguments] Options: --user-only Show only user-defined packages (non-standard library) --detail Show import timing and location information """ import sys import os i...
paramraghavan/beginners-py-learn
quick101/python_import_order/import_tracker.py
.py
a4326318c19a1e96
7.15
1
#!/usr/bin/env python3 """ Static Module Dependency Mapper This tool maps static import dependencies in Python code and combines with runtime analysis to show which imports are actually used in different execution paths. Usage: python module_mapper.py path/to/project [options] Options: --run SCRIPT Run ...
paramraghavan/beginners-py-learn
quick101/python_import_order/static_analyser.py
.py
4ca0fe5171778156
7.15
1
import os import ast import sys import re import subprocess import pkg_resources from pathlib import Path from collections import defaultdict, Counter import argparse class RequirementsGenerator: def __init__(self): # Standard library modules (Python 3.x) self.stdlib_modules = self._get_stdlib_mod...
paramraghavan/beginners-py-learn
quick101/requirements_generator.py
.py
74a9e38ace1234a4
7.15
1
import pickle import os """ Demo class: Contains a picklable value and a non-picklable unpicklable attribute (file handle). __getstate__: Excludes unpicklable so pickling doesn't fail. __setstate__: Restores everything except the file, setting unpicklable to None. Creates the object. Saves it to pickl...
paramraghavan/beginners-py-learn
quick101/serialization/save_myclass_state.py
.py
f31baebaaf1a2193
7.15
1
import pickle import os import signal import sys import atexit import tempfile DICT_PATH = 'state.pickle' def save_state(d): """ Atomically saves the given dictionary to DICT_PATH. """ fd, tmp_name = tempfile.mkstemp(prefix='state.', suffix='.tmp', dir='.') try: with os.fdopen(fd, 'wb') as...
paramraghavan/beginners-py-learn
quick101/serialization/save_state.py
.py
d4da8dd330d54677
7.15
1
""" Example: Visual Tracer ====================== Just ONE line needed! """ # Basic usage - trace everything from visual_tracer import trace; trace() # OR: Only trace functions matching patterns # from visual_tracer import trace; trace(include=['process', 'fetch']) # OR: Skip certain functions # from visual_tracer i...
paramraghavan/beginners-py-learn
quick101/setup-and-debugging/visual_code_tracer/example.py
.py
da7273b8afca156c
7.15
1
""" Test file with path manipulation vulnerabilities """ import os import sys from pathlib import Path # BAD: Path from command-line argument without validation def read_user_file_bad1(): filename = sys.argv[1] with open(filename, 'r') as f: return f.read() # BAD: Path from environment variable withou...
paramraghavan/beginners-py-learn
security_scanner/path_manipulation_test.py
.py
cc0630efa9ffd5ac
7.65
1
from __future__ import annotations __all__ = [ "KeyPath", ] ###### import dis import inspect from bisect import bisect_right from collections.abc import Sequence from threading import current_thread from typing import TYPE_CHECKING, Any, Final, Generic, Protocol, TypeVar, cast, overload from runt...
Azureblade3808/py-runtime-keypath
runtime_keypath/_core/_key_path/_impl.py
.py
90a1720b6bcd0274
7
0
"""Abstract classes and functions for username management backends.""" from typing import Optional from waldur_api_client.models.offering_user import OfferingUser from waldur_site_agent.backend.backends import AbstractUsernameManagementBackend class BaseUsernameManagementBackend(AbstractUsernameManagementBackend):...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/basic_username_management/waldur_site_agent_basic_username_management/backend.py
.py
24b337fe71708905
7.24
2
"""Tests for CroitS3Client.""" import json import pytest import requests from unittest.mock import Mock, patch from waldur_site_agent_croit_s3.client import CroitS3Client from waldur_site_agent_croit_s3.exceptions import ( CroitS3APIError, CroitS3AuthenticationError, CroitS3UserExistsError, CroitS3Use...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/croit-s3/tests/test_client.py
.py
6f9a96ee73c590b9
7.74
2
"""Croit S3 API client for managing S3 users and buckets.""" import logging from typing import Optional import requests import urllib3 from requests.adapters import HTTPAdapter from requests.auth import HTTPBasicAuth from urllib3.util.retry import Retry from waldur_site_agent.backend.clients import BaseClient from w...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/croit-s3/waldur_site_agent_croit_s3/client.py
.py
6da95d2d5d7606d3
7.24
2
"""Tests for CSCS HPC Storage sync script.""" import tempfile from unittest.mock import Mock, patch from uuid import uuid4 import pytest from waldur_site_agent_cscs_hpc_storage.sync_script import ( main, setup_logging, sync_offering_resources, ) class TestSyncScript: """Test cases for CSCS HPC Stora...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/cscs-hpc-storage/tests/test_sync_script.py
.py
032f897025e34d19
7.74
2
"""CSCS HPC User API client implementation.""" import logging from datetime import datetime, timedelta, timezone from typing import Any, Optional import httpx logger = logging.getLogger(__name__) HTTP_OK = 200 class CSCSHpcUserClient: """Client for interacting with CSCS HPC User API for project information.""...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/cscs-hpc-storage/waldur_site_agent_cscs_hpc_storage/hpc_user_client.py
.py
c47afc39bcd5d44a
7.24
2
"""CSCS HPC Storage synchronization script. This script fetches all storage resources from Waldur API and generates the complete all.json file. It should be run separately from individual order processing to efficiently handle bulk resource synchronization. """ import argparse import logging import sys from pathlib i...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/cscs-hpc-storage/waldur_site_agent_cscs_hpc_storage/sync_script.py
.py
32f5fe5310e9297b
7.24
2
"""Configuration loader for CSCS Storage Proxy.""" import logging from dataclasses import dataclass from pathlib import Path from typing import Any, Optional, Union import yaml logger = logging.getLogger(__name__) @dataclass class AuthConfig: """Authentication configuration.""" disable_auth: bool = False ...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/cscs-hpc-storage/waldur_site_agent_cscs_hpc_storage/waldur_storage_proxy/config.py
.py
6460802940616779
7.24
2
"""Tests for Harbor backend.""" import pytest from unittest.mock import Mock, patch, MagicMock from waldur_api_client.models.resource import Resource as WaldurResource from waldur_site_agent.backend import structures from waldur_site_agent_harbor.backend import HarborBackend from waldur_site_agent_harbor.client impo...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/harbor/tests/test_harbor_backend.py
.py
8b57eb9becfc4731
7.74
2
"""Tests for Harbor client.""" import pytest from unittest.mock import Mock, patch, MagicMock import requests from waldur_site_agent_harbor.client import HarborClient from waldur_site_agent_harbor.exceptions import ( HarborAPIError, HarborAuthenticationError, HarborProjectError, HarborQuotaError, ...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/harbor/tests/test_harbor_client.py
.py
b7592b9fe176a338
7.74
2
"""Integration tests for Harbor backend. These tests are designed to run against a real Harbor instance. They can be skipped if no Harbor instance is available. """ import os import pytest from unittest.mock import Mock from waldur_api_client.models.resource import Resource as WaldurResource from waldur_site_agent_h...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/harbor/tests/test_integration.py
.py
a09ed786d55ae786
7.74
2
"""Moab-specific backend classes and functions.""" from typing import Optional from waldur_api_client.models.resource import Resource as WaldurResource from waldur_site_agent.backend import BackendType, logger from waldur_site_agent.backend import utils as backend_utils from waldur_site_agent.backend.backends import...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/moab/waldur_site_agent_moab/backend.py
.py
66ce7c2960cba35c
7.24
2
"""CLI-client for MOAB.""" from __future__ import annotations from typing import Optional from waldur_site_agent.backend import clients, exceptions, logger from waldur_site_agent.backend import utils as backend_utils from waldur_site_agent.backend.structures import Association, ClientResource from waldur_site_agent_...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/moab/waldur_site_agent_moab/client.py
.py
e5a12ee48bb29e3a
7.24
2
"""Parsing classes for MOAB.""" import decimal from functools import cached_property class MoabReportLine: """Parser for report lines from MOAB.""" def __init__(self, line: str) -> None: """Constructor.""" self._parts = line.split("|") @cached_property def account(self) -> str: ...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/moab/waldur_site_agent_moab/parser.py
.py
c364b3fad2c58f43
7.24
2
"""Test fixtures for MUP backend tests""" import uuid from waldur_site_agent.common.structures import Offering # MUP-specific offering configuration MUP_OFFERING = Offering( uuid="d629d5e45567425da9cdbdc1af67b32c", name="mup-test-offering", api_url="http://localhost:8081/api/", api_token="9e1132b9616...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/mup/tests/test_mup_fixtures.py
.py
2ae21f20c46e2ef5
7.74
2
"""MUP Client for waldur site agent. This module provides HTTP client for communicating with MUP (Portuguese project allocation portal) API. It implements the BaseClient interface for managing projects, allocations, and users. """ import base64 import logging from typing import Any, Optional, cast from urllib.parse i...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/mup/waldur_site_agent_mup/client.py
.py
b75dbe016680a3dd
7.24
2
"""Tests for OKD backend implementation.""" import unittest from unittest.mock import MagicMock, patch from waldur_api_client.models.resource import Resource as WaldurResource from waldur_api_client.models.offering_user import OfferingUser from waldur_site_agent.backend.exceptions import BackendError from waldur_site...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/okd/tests/test_okd_backend.py
.py
ef6940bba7f075dd
7.74
2
"""OKD/OpenShift backend implementation for Waldur Site Agent.""" import pprint from typing import Optional from waldur_api_client.models.offering_user import OfferingUser from waldur_api_client.models.resource import Resource as WaldurResource from waldur_site_agent_okd.client import OkdClient from waldur_site_agen...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/okd/waldur_site_agent_okd/backend.py
.py
35232e88b88a8e5b
7.24
2
"""Token management for OKD authentication.""" import logging import time from pathlib import Path from typing import TYPE_CHECKING, Any, Optional from waldur_site_agent.backend.exceptions import BackendError if TYPE_CHECKING: import requests logger = logging.getLogger(__name__) class TokenManager: """Man...
waldur/waldur-docs
docs/admin-guide/providers/site-agent/plugins/okd/waldur_site_agent_okd/token_manager.py
.py
8d9634ac7732496d
7.24
2
""" A maintenance workflow that you can deploy into Airflow to periodically clean out the DagRun, TaskInstance, Log, XCom, Job DB and SlaMiss entries to avoid having too much data in your Airflow MetaStore. ## Authors The DAG is a fork of [teamclairvoyant repository.](https://github.com/teamclairvoyant/airflow-mainte...
RockFlow-AI/airflow-dags
dags/rockflow/dags/housekeeper.py
.py
bd2c1bbc1c517a66
7.3
3
import os import numpy as np import copernicusmarine def from_misc_pres_2_std_depth( a_pcm, ds_profiles, feature_name="temperature", max_pres_delta=50 ): """Convert Argo dataset from irregular pressure to standard depth levels. Since PCM operates on standard depth levels, we first need to interpolate Arg...
euroargodev/boundary_currents_pcm
pcmbc/utilities.py
.py
26f5bcfb5f16805d
7.15
1
"""Enumerations of possible configurations for echo model components.""" from enum import Enum class Units(Enum): """Enumeration object containing units in which the optimisation is undertaken.""" NA = 0 """Used for initialisation but optimisation will fail if units not set prior to execution.""" KW...
bsgip/echo
src/echo/configuration.py
.py
b36a6d3c83dcb511
7.3
3
import pandas as pd import pyomo.environ as en from pydantic import root_validator from pyomo.core.expr import EqualityExpression from echo.configuration import Units from echo.exceptions import ConfigurationError from echo.models.agnostic.flex import FlexSink from echo.models.base import Node from echo.models.scenari...
bsgip/echo
src/echo/models/agnostic/aggregation.py
.py
0b5335ad5ff6850a
7.3
3
import numpy as np import pandas as pd import pyomo.environ as en from pydantic import root_validator, validator from pyomo.core.expr import InequalityExpression from echo.configuration import FlowConstraint, Flows, OptimisationType from echo.models.agnostic.flex import FlexPort from echo.models.base import Port from ...
bsgip/echo
src/echo/models/agnostic/base.py
.py
2b8ec0e61ef31381
7.3
3
import pandas as pd from pydantic import root_validator, validator from echo.configuration import FlowConstraint from echo.models.agnostic.flex import FlexPort from echo.models.scenario import EchoConcreteModel from echo.utils import ( generate_array_constraint, set_var_bounds_from_dict, ) from echo.validators...
bsgip/echo
src/echo/models/agnostic/bounded.py
.py
d65f7854def8ff28
7.3
3
import pandas as pd import pyomo.environ as en from pydantic import Field from pyomo.core.expr import InequalityExpression from echo.configuration import Flows, Units from echo.models.agnostic.flex import FlexPort from echo.models.scenario import EchoConcreteModel from echo.utils import ( set_float_var_bounds, ) ...
bsgip/echo
src/echo/models/agnostic/controlled.py
.py
14f2dfd7774464f6
7.3
3
from echo.configuration import FlowConstraint, Flows, OptimisationType from echo.models.base import Port class FlexPort(Port): """Flexible variable port, which can import and export without constraints.""" flows = Flows.Both import_constraint = FlowConstraint.NoConstraint export_constraint = FlowCons...
bsgip/echo
src/echo/models/agnostic/flex.py
.py
2dc2bad353e5611c
7.3
3
from echo.configuration import Units from echo.models.agnostic.flex import FlexPort from echo.models.base.node import Node class InputOutputNode(Node): """ An input-output node has one input port and one output port. A custom transformation can be defined between input and output. """ # TODO: Thi...
bsgip/echo
src/echo/models/agnostic/input_output.py
.py
e2a385a7555034d5
7.3
3
import pandas as pd import pyomo.environ as en from pydantic import PositiveFloat, root_validator from pyomo.core.expr import EqualityExpression, InequalityExpression from echo.configuration import FlowConstraint, Flows, OptimisationType from echo.exceptions import validate from echo.models.base import Port from echo....
bsgip/echo
src/echo/models/agnostic/storage.py
.py
2fba78a22ed8483a
7.3
3
from collections.abc import Iterable from functools import partial import pyomo.environ as en from pyomo.core.expr import EqualityExpression from echo.models.base import Node, Port from echo.models.scenario import EchoConcreteModel class MultiCommodityTellegenNode(Node): """ A node with ports that have mult...
bsgip/echo
src/echo/models/agnostic/tellegen/multi_commodity.py
.py
a68809e8caae8d40
7.3
3
from collections.abc import Iterable from functools import partial import pyomo.environ as en from pydantic import Field, root_validator from pyomo.core.expr import EqualityExpression from echo.exceptions import ConfigurationError from echo.models.base import Node, Port from echo.models.scenario import EchoConcreteMo...
bsgip/echo
src/echo/models/agnostic/tellegen/partitioned_multi_commodity.py
.py
578144945904fcba
7.3
3
import pandas as pd import pyomo.environ as en from pyomo.core.expr import InequalityExpression from echo.configuration import Units from echo.models.agnostic.flex import FlexSink, FlexSource from echo.models.agnostic.tellegen.base import TellegenNode from echo.models.scenario import EchoConcreteModel class ThreeWay...
bsgip/echo
src/echo/models/agnostic/tellegen/three_way_valve.py
.py
893f21d1025bf414
7.3
3
import pyomo.environ as en from pyomo.core.expr import InequalityExpression from echo.models.agnostic.flex import FlexSink, FlexSource from echo.models.agnostic.input_output import InputOutputNode from echo.models.scenario import EchoConcreteModel class TimeDelayNode(InputOutputNode): """A time delay node is an ...
bsgip/echo
src/echo/models/agnostic/time_delay.py
.py
0bb9bf0fc2067495
7.3
3
import pandas as pd import pyomo.environ as en from pydantic import root_validator from echo.exceptions import validate from echo.models.agnostic.input_output import InputOutputNode from echo.models.scenario import EchoConcreteModel from echo.utils import ( populate_values_across_time_and_expansion_indices, se...
bsgip/echo
src/echo/models/agnostic/time_varying.py
.py
67b5d2c06bad5267
7.3
3
from __future__ import annotations # Deprecating in python 3.15 in favour of lazy annotations (PEP 649 and 749) import pyomo.environ as en import shortuuid from pydantic import Field from pyomo.core.expr.relational_expr import EqualityExpression from echo.configuration import Flows from echo.exceptions import Config...
bsgip/echo
src/echo/models/base/edge.py
.py
fb53c23c2ff5a94a
7.3
3
from __future__ import annotations # Deprecating in python 3.15 in favour of lazy annotations (PEP 649 and 749) from collections.abc import Iterable import pandas as pd import pyomo.environ as en import shortuuid from pydantic import Field from echo.exceptions import ConfigurationError from echo.models.base import ...
bsgip/echo
src/echo/models/base/node.py
.py
096e5cd2b888107f
7.3
3
from __future__ import annotations # Deprecating in python 3.15 in favour of lazy annotations (PEP 649 and 749) from dataclasses import dataclass import pyomo.environ as en import shortuuid from pydantic import Field from pyomo.core.expr.relational_expr import EqualityExpression from echo.configuration import Trans...
bsgip/echo
src/echo/models/base/transform.py
.py
a350715bd311999e
7.3
3
import pandas as pd import pyomo.environ as en from pyomo.core.expr import EqualityExpression from echo.models.base import Node from echo.models.scenario import EchoConcreteModel class CarbonAggregation(Node): """This node has an additional variable, 'total', which equals the sum of all ports defined on the node...
bsgip/echo
src/echo/models/carbon/aggregation.py
.py
c49f39bcaab16533
7.3
3
import numpy as np from echo.configuration import ( EVChargeMode, FlowConstraint, Flows, OptimisationType, TransformRule, Units, ) from echo.exceptions import ConfigurationError, validate from echo.models.agnostic import MobileStorage from echo.models.base import Transform, TransformNode, Trans...
bsgip/echo
src/echo/models/electrical/ev/base.py
.py
c608cd9073bc7ec8
7.3
3
""" Internal backwards-compatibility helpers. This module provides reusable machinery for deprecating old names within the batconf.sources package. It is not part of the public API. """ import warnings def deprecated_module(path: str | None, module: str | None) -> str | None: """Map the deprecated ``module`` key...
lundybernard/batconf
batconf/sources/_compat.py
.py
4a67d54502f97362
7.39
5
from typing import ( Iterable, Any, cast, TypeAlias, ) from dataclasses import _MISSING_TYPE from ..source import SourceInterface from ..types import ConfigP, FieldP from ._compat import deprecated_module class DataclassConfig(SourceInterface): def __init__( self, ConfigClass: ConfigP | ...
lundybernard/batconf
batconf/sources/dataclass.py
.py
e2c02ac69570d8e0
7.39
5
from unittest import TestCase from ..args import CliArgsConfig, Namespace class TestCliArgsConfig(TestCase): """For now Argparse Namespace objects are not nested all args are top-level properties. This should be changed in the future to avoid overriding default values in one module with cli args ...
lundybernard/batconf
batconf/sources/tests/args_test.py
.py
3a4d9307db116ce8
7.89
5
import warnings from unittest import TestCase from unittest.mock import Mock, patch, mock_open, create_autospec, PropertyMock from ..ini import ( # Under Test _IniConfig, IniSource, ConfigFileFormats, _load_ini_file, _load_ini_file_flat, _load_ini, _getter_methods, _get_envs, _...
lundybernard/batconf
batconf/sources/tests/ini_test.py
.py
27145eceb18d14e5
7.89
5
from unittest import TestCase from unittest.mock import ( patch, mock_open, Mock, MagicMock, create_autospec, sentinel, ) from pathlib import Path as _PathClass import warnings from ..toml import ( TomlSource, EmptyConfigDict, _load_toml, _load_toml_file, _missing_file_han...
lundybernard/batconf
batconf/sources/tests/toml_test.py
.py
b576fd0230eaf4a1
7.89
5
"""Verify the public batconf.sources.types namespace.""" import warnings from unittest import TestCase from .. import types class SourcesTypesTests(TestCase): """Verify all intended symbols are importable from batconf.sources.types.""" def test_type_aliases(t): t.assertTrue(hasattr(types, 'ConfigFil...
lundybernard/batconf
batconf/sources/tests/types_test.py
.py
10ca1edecb6c2cbf
7.89
5
import warnings from unittest import TestCase from unittest.mock import ( patch, mock_open, Mock, MagicMock, PropertyMock, create_autospec, ) from pathlib import Path as _PathClass from ..yaml import ( YamlSource, EmptyYamlConfig, YamlConfig, get_file_path, _load_yaml, ...
lundybernard/batconf
batconf/sources/tests/yaml_test.py
.py
4a7d9f6efab64a7b
7.89
5
from unittest import TestCase from unittest.mock import Mock, patch, sentinel from dataclasses import dataclass from ..lib import ConfigSingleton, insert_source, Configuration SRC = 'batconf.lib' def get_config(): """get_config always returns a new Configuration instance""" return Mock(key1='+value1+') ...
lundybernard/batconf
batconf/tests/lib_test.py
.py
191db238c1d2f06d
7.89
5
"""Verify the public batconf root namespace.""" from unittest import TestCase import batconf class BatconfNamespaceTests(TestCase): """Verify all intended symbols are importable from the root namespace.""" def test_core(t): t.assertTrue(hasattr(batconf, 'Configuration')) t.assertTrue(hasattr...
lundybernard/batconf
batconf/tests/namespace_test.py
.py
abae688677e0c467
7.89
5
from unittest import TestCase from dataclasses import dataclass from ..source import ( SourceList, SourceInterface, ) class TestSourceInterfaceABC(TestCase): def test_config_source_interface(t): SourceInterface.__abstractmethods__ = set() @dataclass class Source(SourceInterface)...
lundybernard/batconf
batconf/tests/source_test.py
.py
7351c50f1dc75ab1
7.89
5
"""Verify the public batconf.types namespace.""" import warnings from unittest import TestCase import batconf.types as types class BatconfTypesTests(TestCase): """Verify all intended symbols are importable from batconf.types.""" def test_protocols(t): t.assertTrue(hasattr(types, 'ConfigP')) ...
lundybernard/batconf
batconf/tests/types_test.py
.py
d1ee5eb69dc552fb
7.89
5
from typing import Any, Sequence from pathlib import Path from batconf.manager import Configuration from batconf.types import ConfigP from batconf.source import SourceList, SourceInterface from batconf.types import SourceInterfaceP from batconf.sources.ini import IniConfig # === Configuration Schema === # from data...
lundybernard/batconf
notebooks/config.py
.py
8a40334dd430e012
7.39
5
from unittest import TestCase from os import environ from concurrent.futures import ThreadPoolExecutor from project.conf import get_config from project.submodule.client import MyClient class ThreadSafetyTests(TestCase): """Ensure thread safety when using python with free-threading Supported behavior: ...
lundybernard/batconf
tests/example/freethreading_test.py
.py
9dfc0bf12887fde1
7.89
5
from typing import Sequence from sys import exit import logging from argparse import ArgumentParser, Namespace, Action from .lib import ( hello_world, get_config_str, get_data_from_server, get_opt, get_data_from_server_config, ) from .conf import CFG, NamespaceSource, insert_source log = logging....
lundybernard/batconf
tests/example/project/cli.py
.py
ac1fc5dde1afcbfa
7.89
5
from typing import Any, Sequence from os import path from batconf import ( insert_source, ConfigSingleton, Configuration, SourceList, NamespaceSource, Namespace, EnvSource, IniSource, ) from batconf.types import ConfigP, FileSourceP, SourceInterfaceP from .submodule import MyClient #...
lundybernard/batconf
tests/example/project/conf.py
.py
c3ddfc9e982b58c5
7.89
5
""" This example library module, demonstrates use of batconf's Configuration manager. Notes ----- - Conf.py provides a Global CFG object - The application UI (CLI, GUI, Rest API, etc.) is responsible for updating the global Configuration, using insert_source as needed. - While this is a useful pattern, it is not req...
lundybernard/batconf
tests/example/project/lib.py
.py
e180f9ece31263f4
7.89
5
from dataclasses import dataclass KEY2_DEFAULT = 'DEFAULT VALUE' class MyClient: """Example class that utilizes batconf Attributes ---------- Config : dataclasses.DataClass Define a dataclass with the configuration keys your class requires. We chose the builtin dataclass for this p...
lundybernard/batconf
tests/example/project/submodule/client.py
.py
0e462828f49c5667
7.89
5
from unittest import TestCase from unittest.mock import patch from dataclasses import dataclass from os import path from batconf.manager import Configuration, SourceList from batconf.sources.ini import IniConfig from batconf.sources.env import EnvConfig # === Configuration Schema === # @dataclass class Level2Config...
lundybernard/batconf
tests/integration/configuration_test.py
.py
54c972c663542d0f
7.89
5
#!/usr/bin/env python3 import argparse import sys def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description="""WHOTS FILE DOWNLOADER Example: If you want to download the raw system 1 from WHOTS 17, type: python3 make_whots_dataset.py -w 17 -s 1""...
hot-dogs/whots-buoy-downloader
src/data/whots_parse.py
.py
f4a03c0be560574c
7.24
2
#!/usr/bin/env python3 """ check_commit_format hook for Claude Code. PreToolUse hook on Bash. When `git commit` carries a message (heredoc or `-m` / `--message`), validates: - subject: must match `<area>: <Capital-imperative> [<tag>...]` (regex `^\\S+: [A-Z]`), <= 72 chars (hard), <= 50 chars (soft) - body li...
h2suzuki/terminal-configs
files/claude_managed-hooks/check_commit_format.py
.py
a3fae872281564d9
7
0
#!/usr/bin/env python3 """PreToolUse:Edit/Write/MultiEdit hook: block edits whose content contains dangling-prone references (terminal paths, project CLAUDE.md citation, ephemeral tags). Enforces writing-code「No dangling-prone refs in persistent files」. Opt-out: include `dangling-ref-check: allow` anywhere in the cont...
h2suzuki/terminal-configs
files/claude_managed-hooks/check_dangling_refs.py
.py
cd3587a3060b0d8e
7
0
#!/usr/bin/env python3 r"""PreToolUse:^(Edit|Write|MultiEdit)$ deny-gate — code comment rationale block. writing-code §"Restrict comment length" forbids task / fix / 経緯 reference in code comments ("rationale belongs in commit message, not in code"). This hook scans Edit/Write/MultiEdit new_string for code-comment line...
h2suzuki/terminal-configs
files/claude_managed-hooks/comment_rationale_gate.py
.py
36e8937fde0f31f4
7
0
#!/usr/bin/env python3 """SendMessage 発信文の承認断定語を送信前に検査する gate。""" from __future__ import annotations import io import json from pathlib import Path import re import sys import unittest from unittest import mock ASSERTION_RE = re.compile( r"(承認|裁定|決定|合意)(済み|されました|が出た|を得た|いただいた)" ) QUOTE_RE = re.compile(r"「[^」]*」...
h2suzuki/terminal-configs
files/claude_managed-hooks/cross_session_send_gate.py
.py
145327872e4416c4
7
0
#!/usr/bin/env python3 """ PreToolUse(Bash) hook: keep `git add` safe in a shared working tree. Two denials, both protecting the staged state from cross-session damage: 1. Compound `git add` (with `&&`, `||`, `;`, `|`) — forces a standalone call so the index is settled before the `git commit` PreToolUse hooks f...
h2suzuki/terminal-configs
files/claude_managed-hooks/deny_compound_git_add.py
.py
a0a948348f93e000
7
0
#!/usr/bin/env python3 """ PreToolUse(Bash) hook: keep `git commit` safe in a shared git index. Two denials, both protecting the staged state from cross-session damage: 1. Compound `git commit` (with `&&`, `||`, `;`, `|`) — forces a standalone call so the sibling check_commit_format / check_commit_author hooks ...
h2suzuki/terminal-configs
files/claude_managed-hooks/deny_compound_git_commit.py
.py
29ddc652a5df9d99
7
0
#!/usr/bin/env python3 """PreToolUse(Write|Edit|MultiEdit) hook: block LLM calls written into hooks. Exit: 0: allow the tool call or fail-open on parse/matcher errors. 2: deny matching text in an in-scope hook file. Always exits 0 on any parse / matcher error (fail-open). """ import json import os import re impo...
h2suzuki/terminal-configs
files/claude_managed-hooks/deny_llm_call_in_hook.py
.py
4df06cc59899a8ac
7
0
#!/usr/bin/env python3 """ detect_cwd_pollution hook for Claude Code. PostToolUseFailure hook on Bash (PostToolUse does not fire on failures by design). On a failed Bash command whose output matches cwd-pollution patterns, emits a brief advisory via hookSpecificOutput.additionalContext naming payload.cwd. The advisory...
h2suzuki/terminal-configs
files/claude_managed-hooks/detect_cwd_pollution.py
.py
99c8f5ddacf4126a
7
0
#!/usr/bin/env python3 """Black-box contract tests for memory_routing_gate.py check:/when: rules. Contract (each claim maps to one or more tests): N1 new entry (target path does not exist on disk) with no non-empty check: line in frontmatter -> deny naming check: (existing entries are exempt) N2 check: pre...
h2suzuki/terminal-configs
files/claude_managed-hooks/memory_routing_gate.test.py
.py
a9597f39906fda50
7.5
0
#!/usr/bin/env python3 """SessionStart hook: freshen the shared memory clone in the background. clone ok -> unless git's own FETCH_HEAD is fresher than PULL_THROTTLE, spawn a detached `claude_memory_sync --pull` and return immediately, so the session never waits on the network (pull lands ~1...
h2suzuki/terminal-configs
files/claude_managed-hooks/memory_sync_pull.py
.py
81c0c568c92e4670
7
0
#!/usr/bin/env python3 """PreToolUse hook: keep Playwright listener registrations scoped to snippets. Exit: 0: allow the tool call or fail-open on parse/matcher errors. 2: deny a page.on() registration without page.off() in the same snippet. Always exits 0 on any parse / matcher error (fail-open). """ import jso...
h2suzuki/terminal-configs
files/claude_managed-hooks/playwright_listener_gate.py
.py
7ef2ff171edabcbc
7
0
#!/usr/bin/env python3 """ Shared excludedCommands roster for the sandbox hooks. `sandbox.excludedCommands` varies per host, so the roster is always rendered from the live settings files rather than hardcoded. The sandbox hooks import from here so the advice is written once and stays identical across them. """ from _...
h2suzuki/terminal-configs
files/claude_managed-hooks/sandbox_exclusions.py
.py
5337de9f3777a590
7
0
#!/usr/bin/env python3 """ Sandbox-server-unreachable-from-host advisory hook for Claude Code. PreToolUse hook on Bash. Detects commands that start a long-running dev/ preview server inside the sandbox (`npm run dev`, `vite`, `python -m http.server`, `cargo run --bin dsa-server`, ...) and emits hookSpecificOutput.addi...
h2suzuki/terminal-configs
files/claude_managed-hooks/sandbox_server_gate.py
.py
898c62cc83eace94
7
0
#!/usr/bin/env python3 """PreToolUse:^(Task|Agent)$ hook — subagent-gate overuse warning (advisory). Inspects tool_input (prompt / subagent_type / description) and emits a stderr advisory when a spawn looks unlikely to amortize its context-switch + result-integration + token overhead. Always exits 0 (warn-only) — the ...
h2suzuki/terminal-configs
files/claude_managed-hooks/subagent_gate_warn.py
.py
013d56eee84dac42
7
0
#!/usr/bin/env python3 """ TMPDIR scratch gate for Claude Code. PreToolUse hook on Bash. We cannot persistently force TMPDIR (no managed shell profile; shell state does not survive across Bash calls), so instead we CHECK at call time that temp files route to the per-session scratch dir /tmp/claude-scratch-$CLAUDE_CODE...
h2suzuki/terminal-configs
files/claude_managed-hooks/tmpdir_scratch_gate.py
.py
1d2a3c0e6af330f6
7
0
#!/usr/bin/python # -*- coding: utf-8 -*- """Circuit breaker pattern implementation for plugin initialization.""" import threading import time from enum import Enum from typing import Any, Callable, Dict, Optional class CircuitState(Enum): """Circuit breaker states.""" CLOSED = "closed" OPEN = "open" ...
ideabosque/silvaengine_base
silvaengine_base/boosters/plugin/circuit_breaker.py
.py
bc2d1001c8b5ecd7
7
0
#!/usr/bin/python # -*- coding: utf-8 -*- """Configuration validator for plugin management.""" import re from dataclasses import dataclass, field from enum import Enum from typing import Any, Callable, Dict, List, Optional, Set, Union SENSITIVE_VALUE_MIN_LENGTH = 8 DEFAULT_PLUGIN_NAME_MIN_LENGTH = 1 DEFAULT_PLUGIN_N...
ideabosque/silvaengine_base
silvaengine_base/boosters/plugin/config_validator.py
.py
b30ee27a1c96e373
7
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Unified Plugin Initialization Utilities. This module provides unified plugin initialization logic to eliminate code duplication across multiple modules (__init__.py, async_initializer.py, context.py, parallel_scheduler.py). @since 2.0.0 """ import logging import time...
ideabosque/silvaengine_base
silvaengine_base/boosters/plugin/initializer_utils.py
.py
928a66465b6304e4
7
0
#!/usr/bin/python # -*- coding: utf-8 -*- """Plugin context injector for automatic plugin injection.""" import threading from contextlib import contextmanager from typing import TYPE_CHECKING, Any, Optional from .context import AbstractPluginContext if TYPE_CHECKING: from .context import PluginContext _context_...
ideabosque/silvaengine_base
silvaengine_base/boosters/plugin/injector.py
.py
1a34d8b37edf7ec4
7
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Unified Thread Pool Manager for silvaengine_base. This module provides a centralized thread pool management system to: - Avoid resource competition between multiple ThreadPoolExecutor instances - Provide consistent thread pool configuration - Enable efficient resource ...
ideabosque/silvaengine_base
silvaengine_base/boosters/plugin/thread_pool_manager.py
.py
1d2f1afa2eb3f3f4
7
0
#!/usr/bin/python # -*- coding: utf-8 -*- """ Resources Handler for silvaengine_base. This module provides the plugin management functionality that was previously in the Resources class. All plugin-related operations are now centralized here. [REFACTORED] This module now reuses AsyncPluginInitializer for all async in...
ideabosque/silvaengine_base
silvaengine_base/boosters/plugin_initializer.py
.py
1439d53af0dca133
7
0