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 |
|---|---|---|---|---|---|---|
"""Dedupe module."""
import logging
from pathlib import Path
from datoso.database.models.dat import Dat
from datoso.repositories.dat_file import ClrMameProDatFile, DatFile
class DatDedupe:
"""Dat Dedupe class."""
_datdb: Dat
_datfile: DatFile
_file: str | Path
@property
def datdb(self) -> D... | laromicas/datoso | src/datoso/repositories/dedupe.py | .py | 2ef396194bbf7e94 | 7.52 | 10 |
"""Hashes index module."""
class HashesIndex:
"""Index of hashes."""
valid_hashes: list
sha256: dict
sha1: dict
md5: dict
crc: dict
sizes: dict
def __init__(self) -> None:
"""Initialize the index."""
self.sha256 = {}
self.sha1 = {}
self.md5 = {}
... | laromicas/datoso | src/datoso/repositories/hashes_index.py | .py | 55e13eefa3aa676d | 7.52 | 10 |
"""Rules class."""
from pydoc import locate
from datoso.helpers.plugins import installed_seeds
class Rules:
"""Rules class."""
_rules: list | None
def __init__(self) -> None:
"""Initialize Rules."""
self._rules = []
for seed in installed_seeds():
rules = locate(f'{se... | laromicas/datoso | src/datoso/seeds/rules.py | .py | 9d5dc9ec04210085 | 7.52 | 10 |
import unittest
import os
from unittest import mock
from pathlib import Path
import configparser
import sys
# Attempt to import from src. This might require PYTHONPATH to be set correctly
# for the test execution environment. If /app is the project root, /app/src should be
# on PYTHONPATH.
try:
from src.datoso.con... | laromicas/datoso | tests/datoso/configuration/test_configuration.py | .py | 3fff001f4dfc5110 | 7.02 | 10 |
import unittest
from unittest import mock
import hashlib # For calculate_sha1 testing (if found later)
import os
import shutil
from pathlib import Path
import sys
import subprocess # For mocking Popen
# Ensure src is discoverable for imports
project_root_for_imports = Path(__file__).parent.parent.parent.parent
if str(... | laromicas/datoso | tests/datoso/helpers/test_download.py | .py | 8545751656ed4c4b | 7.02 | 10 |
import unittest
from unittest import mock
import os
import shutil
import tempfile
from pathlib import Path
import sys
# Ensure src is discoverable for imports
project_root_for_imports = Path(__file__).parent.parent.parent.parent
if str(project_root_for_imports) not in sys.path:
sys.path.insert(0, str(project_root_... | laromicas/datoso | tests/datoso/helpers/test_file_utils.py | .py | ea7b65ec26906810 | 8.02 | 10 |
from pathlib import Path
from typing import Any
import polars as pl
import polars.selectors as cs
def _read_parquet_with_timezone_correction(
path_to_file: str | Path, **kwargs: Any
) -> pl.DataFrame:
"""Read Parquet data, interpreting timezone-naive timestamps as UTC."""
df = pl.read_parquet(path_to_fil... | CDCgov/cfa-stf-forecasttools | cfa/stf/forecasttools/utils.py | .py | ddea0acbbf77074a | 7.54 | 11 |
import copy
import datetime as dt
import tempfile
from pathlib import Path
import numpy as np
import pytest
import xarray as xr
import cfa.stf.forecasttools as ft
TESTDATA_DIR = Path(__file__).resolve().parent / "test_data"
IDATA_WO_DATES = xr.open_datatree(
TESTDATA_DIR / "test_idata.nc", engine="h5netcdf"
).lo... | CDCgov/cfa-stf-forecasttools | tests/cfa/stf/forecasttools/test_arviz.py | .py | 0163968e7f858d2a | 7.04 | 11 |
"""
Base adapter interface for the Cardsharp engine.
This module defines the interface that platform-specific adapters must implement
to interact with the Cardsharp engine.
"""
from abc import ABC, abstractmethod
from typing import List, Dict, Any, Optional, Union, Awaitable
import asyncio
from enum import Enum
# Im... | mmichie/cardsharp | cardsharp/adapters/base.py | .py | 257c4dacbe11e68c | 7.52 | 10 |
"""
Command-line interface adapter for the Cardsharp engine.
This module provides an adapter for console-based interactions with the
Cardsharp engine, enabling backward compatibility with the current interface.
"""
import asyncio
import sys
from typing import List, Dict, Any, Optional, Union, Awaitable, TYPE_CHECKING... | mmichie/cardsharp | cardsharp/adapters/cli.py | .py | 9c8749b4971d295c | 7.52 | 10 |
"""
Dummy adapter for the Cardsharp engine, used for testing and simulation.
This module provides a non-interactive adapter that can be used for automated
testing, simulations, and benchmarks where no user interaction is needed.
"""
from typing import List, Dict, Any, Optional, Union, Awaitable
from enum import Enum
... | mmichie/cardsharp | cardsharp/adapters/dummy.py | .py | 8fe68fb475536c35 | 7.52 | 10 |
"""
Blackjack API module for Cardsharp.
This module provides a high-level, platform-agnostic API for working with the
Cardsharp Blackjack engine, supporting both synchronous and asynchronous operation.
"""
import asyncio
from typing import Dict, Any, List, Optional, Union, Callable, TYPE_CHECKING
from cardsharp.adap... | mmichie/cardsharp | cardsharp/api/blackjack.py | .py | c2208e4210487664 | 7.52 | 10 |
"""
High Card API module for Cardsharp.
This module provides a high-level, platform-agnostic API for working with the
Cardsharp High Card engine, supporting both synchronous and asynchronous operation.
"""
import asyncio
from typing import Dict, Any, List, Optional
from cardsharp.adapters import PlatformAdapter
from... | mmichie/cardsharp | cardsharp/api/high_card.py | .py | ded57999afb36aa8 | 7.52 | 10 |
"""
War card game API module for Cardsharp.
This module provides a high-level, platform-agnostic API for working with the
Cardsharp War engine, supporting both synchronous and asynchronous operation.
"""
import asyncio
from typing import Dict, Any, List, Optional
from cardsharp.adapters import PlatformAdapter
from c... | mmichie/cardsharp | cardsharp/api/war.py | .py | be81700e848f68ac | 7.52 | 10 |
"""
Baccarat game CLI and simulation interface.
Run simulations and analyze the house edge for different bet types.
"""
import argparse
import time
from typing import Dict
from cardsharp.baccarat.game import BaccaratGame, BetType, Outcome
from cardsharp.baccarat.rules import BaccaratRules
def run_simulation(num_ga... | mmichie/cardsharp | cardsharp/baccarat/baccarat.py | .py | a9fb4a2056e7f7f2 | 7.52 | 10 |
"""
Baccarat game engine.
Implements the complete Baccarat game logic including dealing, drawing rules,
and outcome determination.
"""
from enum import Enum
from typing import Optional
from dataclasses import dataclass
from cardsharp.common.shoe import Shoe
from cardsharp.baccarat.hand import BaccaratHand
from cards... | mmichie/cardsharp | cardsharp/baccarat/game.py | .py | fd3b23e4243a37c8 | 7.52 | 10 |
"""
Baccarat hand implementation.
In Baccarat, hand values are calculated differently than blackjack:
- Cards 2-9 are worth face value
- 10, J, Q, K are worth 0
- Aces are worth 1
- Only the rightmost digit of the sum counts (17 = 7, 23 = 3)
"""
from typing import List
from cardsharp.common.card import Card, Rank
c... | mmichie/cardsharp | cardsharp/baccarat/hand.py | .py | ac3e2f5c61e1fd5f | 7.52 | 10 |
"""
Baccarat rules and drawing logic.
Baccarat has fixed drawing rules - no player decisions after betting.
The rules determine when Player and Banker draw a third card.
"""
from dataclasses import dataclass
@dataclass
class BaccaratRules:
"""
Configuration for Baccarat game rules.
Attributes:
... | mmichie/cardsharp | cardsharp/baccarat/rules.py | .py | aa772ada53f04a43 | 7.52 | 10 |
"""
This module provides the `Player` and `Dealer` classes for a game of Blackjack.
The `Player` class represents a player in the game. It maintains the state of the player's current hand,
the amount of money the player has, the player's current bet, and whether the player's turn is done. The
`Player` class also provi... | mmichie/cardsharp | cardsharp/blackjack/actor.py | .py | a1b1ea2fa4f57a5a | 7.52 | 10 |
"""Common Random Numbers (CRN) for blackjack rule comparison.
When estimating the EV difference between two rule sets via Monte Carlo,
running each rule set on the same shuffled shoes (rather than independent
streams) makes the variance of the difference proportional to the strategy
divergence between the rules, not t... | mmichie/cardsharp | cardsharp/blackjack/comparison.py | .py | d0f73ebc9e1af9fe | 7.52 | 10 |
"""Interactive console blackjack on the fast core (beads-i2s.2).
Drives `cardsharp_core.Session` (via cardsharp.fastsim.open_session) and
narrates rounds in the exact line format the retired state-machine
console used, so scripted transcripts diff clean against the old flow
(tests/blackjack/test_console_transcript_par... | mmichie/cardsharp | cardsharp/blackjack/console.py | .py | 9d6e9d2d09391b42 | 7.52 | 10 |
"""
Comprehensive logging system for blackjack decision paths.
Tracks all decisions, rule evaluations, and game state changes.
"""
import logging
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from datetime import datetime
import os
from ..common.card import Card
from .action imp... | mmichie/cardsharp | cardsharp/blackjack/decision_logger.py | .py | 1f7dab2f61c17dc1 | 7.52 | 10 |
"""
Variance and deviation modeling for strategy execution.
This module provides implementations of strategy execution variance,
including counting errors for card counting strategies, bet sizing variation,
and decision timing effects.
"""
import random
import time
from enum import Enum, auto
from typing import Any, ... | mmichie/cardsharp | cardsharp/blackjack/execution_variance.py | .py | bdfec06839d8b578 | 7.52 | 10 |
"""
Optimized BlackjackHand implementation with improved cache handling.
"""
from typing import Any, Dict
from cardsharp.common.card import Card, Rank
from cardsharp.common.hand import Hand
from cardsharp.blackjack.constants import get_blackjack_value
class BlackjackHand(Hand):
"""A hand in the game of Blackjack... | mmichie/cardsharp | cardsharp/blackjack/hand.py | .py | 4b596c10a0a03c8f | 7.52 | 10 |
"""
Realistic player behavior modeling for blackjack simulations.
This module provides implementations of player strategies that exhibit realistic
behavior such as skill level variation, decision fatigue, and psychological factors.
"""
import random
from enum import Enum, auto
from typing import Any, Dict, List, Opti... | mmichie/cardsharp | cardsharp/blackjack/realistic_strategy.py | .py | 6a9985e4d8a7dba8 | 7.52 | 10 |
from cardsharp.common.hand import Hand
from cardsharp.common.card import Rank
from cardsharp.blackjack.variants import VariantRegistry, BlackjackVariant
from cardsharp.blackjack.hand import BlackjackHand
class Rules:
def __init__(
self,
blackjack_payout: float = 1.5,
dealer_hit_soft_17: bo... | mmichie/cardsharp | cardsharp/blackjack/rules.py | .py | 481cead847949ac4 | 7.52 | 10 |
"""Dealer outcome probability computation.
Computes the exact probability distribution over dealer final totals
(17-21 + bust) for each upcard, by recursive expansion of all possible
draws weighted by card probabilities.
Supports both infinite-deck (constant probs) and finite-deck
(composition-dependent probs that ch... | mmichie/cardsharp | cardsharp/blackjack/solver/dealer.py | .py | ccfc58b9a8f5ad91 | 7.52 | 10 |
"""Solver orchestrator: Rules -> house edge + optimal strategy table.
Supports both infinite-deck (fast, constant probabilities) and
finite-deck (exact, composition-dependent probabilities).
"""
import csv
from typing import NamedTuple
from cardsharp.blackjack.action import Action
from cardsharp.blackjack.rules impo... | mmichie/cardsharp | cardsharp/blackjack/solver/engine.py | .py | 6bb07785d6b860a4 | 7.52 | 10 |
"""Player expected value computation.
Computes the exact EV of each action (hit, stand, double, split, surrender)
for every possible player hand state vs every dealer upcard.
Supports both infinite-deck and finite-deck via the Deck interface.
"""
import math
from cardsharp.blackjack.action import Action
from .type... | mmichie/cardsharp | cardsharp/blackjack/solver/player.py | .py | 917321ed7a91540f | 7.52 | 10 |
"""Types and constants for the probabilistic solver."""
from typing import NamedTuple
from cardsharp.blackjack.action import Action
# Card values in blackjack: Ace=1, 2-9, 10 (covers T/J/Q/K)
CARD_VALUES = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# Infinite-deck draw probabilities: 1/13 each for A-9, 4/13 for 10-value
INF_D... | mmichie/cardsharp | cardsharp/blackjack/solver/types.py | .py | 264c160d48dff8d0 | 7.52 | 10 |
"""
This module contains the SimulationStats class which is responsible for
tracking and updating the statistics of the blackjack game simulation.
It accumulates per-round outcomes via Welford's online algorithm so that
sample mean, variance, and a delta-method confidence interval for the
house edge can be reported wi... | mmichie/cardsharp | cardsharp/blackjack/stats.py | .py | bb65105d82df21a7 | 7.52 | 10 |
"""
Test support classes for blackjack engine validation.
This module provides enhanced game components that record actions and outcomes
for test validation purposes.
"""
from dataclasses import dataclass, field
from typing import List, Optional, Dict, Any
from enum import Enum
from .actor import Player, Dealer
from... | mmichie/cardsharp | cardsharp/blackjack/test_support.py | .py | a3c1e6242c416904 | 8.02 | 10 |
"""Classic blackjack variant."""
from typing import List, Optional, Dict
from cardsharp.common.card import Card, Rank, Suit
from cardsharp.common.deck import Deck
from cardsharp.blackjack.actor import BlackjackHand
from .base import (
BlackjackVariant,
ActionValidator,
WinResolver,
PayoutCalculator,
... | mmichie/cardsharp | cardsharp/blackjack/variants/classic.py | .py | c361968319c70850 | 7.52 | 10 |
"""Registry for blackjack variants."""
from typing import Dict, Type, List
from .base import BlackjackVariant
class VariantRegistry:
"""Registry for managing blackjack variants."""
_variants: Dict[str, Type[BlackjackVariant]] = {}
@classmethod
def register(cls, name: str, variant_class: Type[Blackj... | mmichie/cardsharp | cardsharp/blackjack/variants/registry.py | .py | 4edd11ae27a8faa6 | 7.52 | 10 |
"""Spanish 21 blackjack variant."""
from typing import List, Optional, Dict
from cardsharp.common.card import Card, Rank, Suit
from cardsharp.blackjack.actor import BlackjackHand
from .base import (
BlackjackVariant,
ActionValidator,
WinResolver,
PayoutCalculator,
SpecialHand,
)
class Spanish21Ac... | mmichie/cardsharp | cardsharp/blackjack/variants/spanish21.py | .py | ac0d54811d5b61c7 | 7.52 | 10 |
"""Utility function to decode fields in _meshcop._udp.local. mDNS services.
The implementation is based on the Open Thread implementation:
https://github.com/openthread/ot-br-posix/blob/8a8b2411abcf68659c25bb97672bdd2e5e724dcc/src/border_agent/border_agent.cpp#L109
"""
from dataclasses import dataclass
from enum impo... | home-assistant-libs/python-otbr-api | python_otbr_api/mdns.py | .py | 6f01e59a74b75b3d | 7.52 | 10 |
"""Data models."""
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from typing import Any
import voluptuous as vol # type: ignore[import]
class EphemeralKeyState(Enum):
"""State of the border agent ephemeral key (ePSKc) session.
Reported by the `/node/ba-epskc/k... | home-assistant-libs/python-otbr-api | python_otbr_api/models.py | .py | 5fda05e58cad172b | 7.52 | 10 |
"""Calculate Thread PSKc.
Based on https://github.com/openthread/ot-br-posix/blob/main/src/utils/pskc.cpp
"""
import struct
from cryptography.hazmat.primitives import cmac
from cryptography.hazmat.primitives.ciphers import algorithms
AES_128_KEY_LEN = 16
ITERATION_COUNTS = 16384
BLKSIZE = 16
SALT_PREFIX = "Thread".... | home-assistant-libs/python-otbr-api | python_otbr_api/pskc.py | .py | 0a808b72e2213001 | 7.52 | 10 |
"""Parse datasets TLV encoded as specified by Thread."""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import IntEnum
import struct
import logging
_LOGGER = logging.getLogger(__name__)
class TLVError(Exception):
"""TLV error."""
class MeshcopTLVType(IntEnum):
"""Ty... | home-assistant-libs/python-otbr-api | python_otbr_api/tlv_parser.py | .py | 92c3d289a24bce2e | 7.52 | 10 |
"""Tests for the ephemeral key (ePSKc) REST API."""
from http import HTTPStatus
import pytest
import python_otbr_api
from python_otbr_api import EphemeralKeyState, KeyFormat
from tests.test_util.aiohttp import AiohttpClientMocker
BASE_URL = "http://core-openthread-border-router:8081"
def _otbr(aioclient_mock: Aio... | home-assistant-libs/python-otbr-api | tests/test_ephemeral_key.py | .py | 9859d3a4ae026e60 | 7.02 | 10 |
"""Test decoding fields in _meshcop._udp.local. services."""
import pytest
from python_otbr_api.mdns import (
Availability,
ConnectionMode,
StateBitmap,
ThreadInterfaceStatus,
)
@pytest.mark.parametrize(
"encoded, decoded",
[
(
b"\x00\x00\x01\xb1",
StateBitmap... | home-assistant-libs/python-otbr-api | tests/test_mdns.py | .py | 4787923692b7c526 | 8.02 | 10 |
"""Test data models."""
import python_otbr_api
ACTIVE_DATASET_CAMEL = {
"activeTimestamp": {"seconds": 1, "ticks": 0, "authoritative": False},
"networkKey": "00112233445566778899aabbccddeeff",
"networkName": "OpenThread-1234",
"extPanId": "dead00beef00cafe",
"meshLocalPrefix": "fd11:2222:3333::/64... | home-assistant-libs/python-otbr-api | tests/test_models.py | .py | ee76c38fee4ec7d3 | 8.02 | 10 |
"""Test calculating PSKc."""
import pytest
from python_otbr_api.pskc import compute_pskc
@pytest.mark.parametrize(
"ext_pan_id, network_name, passphrase, expected_pskc",
[
# Example from https://openthread.io/guides/border-router/tools#pskc_generator
(
bytes.fromhex("1234AAAA1234... | home-assistant-libs/python-otbr-api | tests/test_pskc.py | .py | 2c8afade593becfd | 7.02 | 10 |
"""Aiohttp test utils."""
import asyncio
from contextlib import contextmanager
from http import HTTPStatus
from json import dumps as json_dumps, loads as json_loads
import re
from unittest import mock
from urllib.parse import parse_qs
from aiohttp import ClientSession
from aiohttp.client_exceptions import ClientError... | home-assistant-libs/python-otbr-api | tests/test_util/aiohttp.py | .py | 0c7ab48f610ee124 | 8.02 | 10 |
"""Tests for the /.well-known/thread/br-rest API discovery endpoint."""
from http import HTTPStatus
import pytest
import python_otbr_api
from tests.test_util.aiohttp import AiohttpClientMocker
BASE_URL = "http://core-openthread-border-router:8081"
WELL_KNOWN_JSON = {
"api": {"version": "0.3.0", "base": "/api/"... | home-assistant-libs/python-otbr-api | tests/test_well_known.py | .py | 4ff6f34606cf961b | 7.02 | 10 |
"""MkDocs hook: append a "Run on Compiler Explorer" link to runnable C++ blocks.
For every top-level fenced ```cpp block whose source contains `int main`,
generates a Compiler Explorer URL that opens the code in an editor + executor
pane (no assembly view) and inserts a small link immediately below the block.
Blocks ... | markaren/E-book_cpp | hooks/compiler_explorer.py | .py | cb3fee53c790890d | 7.65 | 19 |
"""MkDocs hook: turn a ```quiz fenced block into a multiple-choice question.
Authoring syntax — put it in any `docs/*.md` file, usually just below a code
block the question asks about. Use a **four-backtick** fence, so the
explanation is free to contain an ordinary ```cpp block:
````quiz
What does this print?... | markaren/E-book_cpp | hooks/quiz.py | .py | 3990126dfb058416 | 7.65 | 19 |
from importlib.util import find_spec
from logging import getLogger
from pydantic import BaseModel
__all__ = ("DagInstantiateMixin",)
have_airflow_config = find_spec("airflow_config") is not None
_log = getLogger(__name__)
class DagInstantiateMixin:
def instantiate(self: BaseModel, **kwargs):
# NOTE: a... | airflow-laminar/airflow-pydantic | airflow_pydantic/core/instantiate/dag.py | .py | 180def3fcc6b838c | 7.5 | 9 |
import ast
import os
from logging import getLogger
from pathlib import Path
from shutil import which
from subprocess import call
from tempfile import NamedTemporaryFile
from ...utils import _task_id_to_python_name
from .task import render_base_task_args
from .utils import _get_parts_from_value
__all__ = ("DagRenderMi... | airflow-laminar/airflow-pydantic | airflow_pydantic/core/render/dag.py | .py | 9ce461408858e20d | 7.5 | 9 |
from datetime import timedelta
from typing import Union
from pydantic import Field, field_validator, model_validator
from ..utils import DatetimeArg, ImportPath, Pool, TriggerRule
from .base import BaseModel
from .instantiate import TaskInstantiateMixin
from .render import TaskRenderMixin
__all__ = (
"Task",
... | airflow-laminar/airflow-pydantic | airflow_pydantic/core/task.py | .py | facabc19c51ab450 | 7.5 | 9 |
from collections.abc import Callable
from logging import getLogger
from pathlib import Path
from random import choice
from typing import Self
from pydantic import Field, model_validator
from ...core import BaseModel
from ...utils import Pool, Variable
from .host import Host
from .pool_manager import PoolManagerConfig... | airflow-laminar/airflow-pydantic | airflow_pydantic/extras/balancer/balancer.py | .py | 64b2cf39cf04d96a | 7.5 | 9 |
from collections.abc import Callable
from fnmatch import fnmatch
from logging import getLogger
from random import choice
from typing import Literal
from pkn.pydantic import CallablePath
from pydantic import Field
from ...core import BaseModel
from .balancer import BalancerConfiguration
from .host import Host
__all__... | airflow-laminar/airflow-pydantic | airflow_pydantic/extras/balancer/query.py | .py | 7437d333de3c24ce | 7.5 | 9 |
import os
from datetime import datetime, timedelta
from logging import getLogger
from urllib.parse import quote
from pytz import UTC
from ...airflow import AirflowFailException, AirflowSkipException
__all__ = (
"clean_dag_runs",
"clean_dag_runs_api",
"clean_dags",
"clean_dags_api",
"fail",
"p... | airflow-laminar/airflow-pydantic | airflow_pydantic/extras/common/airflow_functions.py | .py | ba9a263a79167383 | 7.5 | 9 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
import warnings
import xarray as xr
from ocean_preprocessing.schema import (
ds_input_coords_schema,
ds_input_schema,
ds_prediction_coords_schema,
ds_prediction_schema,
ds_processed_coords_schema,
ds_proces... | m2lines/Samudra | data/ocean_preprocessing/dataset_validation.py | .py | fdd239bcd1fcd15d | 7.6 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
"""CLI for fetching and preparing observation products.
python -m ocean_preprocessing.obs_preprocessing download oisst --output_dir=...
python -m ocean_preprocessing.obs_preprocessing prepare all --raw_root=... --output_root=...
""... | m2lines/Samudra | data/ocean_preprocessing/obs_preprocessing/__main__.py | .py | 63775fab0a96de8f | 7.6 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
"""Download the raw observation products, as distributed by their providers.
Every downloader is restartable: files already present at a plausible size are
never requested, and anything that arrives truncated is deleted rather than... | m2lines/Samudra | data/ocean_preprocessing/obs_preprocessing/download.py | .py | d81bfb0a42dbdefa | 7.6 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
"""Build analysis-ready observation stores from the raw archive.
The target timestamps come from the published **OM4 dataset** rather than from a
particular model rollout. Reading the time axis out of one `predictions.zarr`
would w... | m2lines/Samudra | data/ocean_preprocessing/obs_preprocessing/prepare.py | .py | a7041f9997e3028a | 7.6 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
import warnings
import xarray as xr
from ocean_preprocessing.dataset_validation import ds_input_validate
from ocean_preprocessing.utils import assert_mask_match
def post_processor(ds: xr.Dataset, ds_truth: xr.Dataset) -> xr.Data... | m2lines/Samudra | data/ocean_preprocessing/postprocessing.py | .py | 1798ebffd761045c | 7.6 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
"""Preprocess arbitrary datasets to standardized naming, grids."""
import logging
import cf_xarray
import gcm_filters
import numpy as np
import xarray as xr
from xgcm import Grid
from ocean_preprocessing.schema import vars_3d
fro... | m2lines/Samudra | data/ocean_preprocessing/preprocessing.py | .py | 166cc914b0058ced | 7.6 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
import fsspec
import numpy as np
import xarray as xr
from xgcm import Grid
from .gfdl_om4 import om4_preprocessing
from .interpolate import interpolate_to_cell_centers
def sis2_preprocessing(zarr_data_path, backend_kwargs=None):
... | m2lines/Samudra | data/ocean_preprocessing/simulation_preprocessing/gfdl_cm4.py | .py | b5fc72dde4bfd606 | 7.6 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
import fsspec
import numpy as np
import xarray as xr
from xarrera import SchemaError
from xgcm import Grid
from ocean_preprocessing.dataset_validation import ds_processed_validate
from ocean_preprocessing.utils import apply_mask
f... | m2lines/Samudra | data/ocean_preprocessing/simulation_preprocessing/gfdl_om4.py | .py | 04010ec8100724d7 | 7.6 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
import subprocess
import numpy as np
import xarray as xr
def get_git_url_hash():
github_server_url = "https://github.com"
# Get the repository's remote origin URL
try:
repo_origin_url = subprocess.check_output... | m2lines/Samudra | data/ocean_preprocessing/utils.py | .py | b046a4a44de77bcf | 7.6 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
"""This is s bit silly. It would be better to be able to create datasets from the schema dynamically, so the schema serve as source of truth, and when they are updated, the test data is too. But for now lets at least test that our t... | m2lines/Samudra | data/tests/test_data.py | .py | 5edf1b44dceb3479 | 8.1 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
import xarray as xr
from ocean_preprocessing.postprocessing import post_processor, prediction_data_test
from tests.data import ( # noqa # Might want to put these in conftest.py (see https://stackoverflow.com/questions/73191533/usi... | m2lines/Samudra | data/tests/test_postprocessing.py | .py | d7ba3e9c53b7c29e | 7.1 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
import xarray as xr
from ocean_preprocessing.preprocessing import (
flatten_by_depth_level,
horizontal_regrid,
rotate_vectors,
)
from tests import requires_xesmf
from tests.data import (... | m2lines/Samudra | data/tests/test_preprocessing.py | .py | 71a847e0af06d2b6 | 8.1 | 15 |
# SPDX-FileCopyrightText: 2026 Ocean Emulator Authors
#
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import xarray as xr
from ocean_preprocessing.simulation_preprocessing.gfdl_om4 import (
normalize_vertical_coords,
)
def _ds_with_vertical(names):
"""Build a tiny dataset whose vertical dimension ... | m2lines/Samudra | data/tests/test_simulation_preprocessing.py | .py | b72031a67ef544e2 | 8.1 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
import xarray as xr
from ocean_preprocessing.utils import (
apply_mask,
assert_mask_match,
ensure_nan_consistency,
)
from tests.data import (
input_data, # noqa # Might want to put ... | m2lines/Samudra | data/tests/test_utils.py | .py | 8b7e423987bc0465 | 7.1 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
# %%
"""
Regrid all basin data to match higher resolution data using a KDTree.
Was used to create emulators/jr7309/basins/basin_masks_regridded.zarr for half-degree resolution.
This script:
1. Loads all basin files from BASINS_PAT... | m2lines/Samudra | notebooks/regrid_basins.py | .py | 02fc6b261f938e0d | 7.6 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
"""Generate ``notebooks/quickstart.ipynb`` from reviewable cell sources.
Run this script whenever a quickstart cell changes:
uv run python scripts/build_quickstart_notebook.py
"""
import argparse
from pathlib import Path
imp... | m2lines/Samudra | scripts/build_quickstart_notebook.py | .py | 7788d44fe9daa23e | 7.6 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
"""Script to clone remote Oceans Emulator data locally."""
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "xarray[io]",
# "zarr<3",
# "dask",
# "requests",
# "aiohttp",
# "gcsfs",
# "numcodecs>=0.15",
#... | m2lines/Samudra | scripts/clone_data.py | .py | f56d0e07b5e3c5e3 | 7.6 | 15 |
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
"""Trivial runtime smoke test for the containerized project environment."""
from __future__ import annotations
import importlib
import importlib.metadata as metadata
import torch
import torch.nn.functional... | m2lines/Samudra | scripts/container/smoke_test.py | .py | 1e154404565f36f0 | 8.1 | 15 |
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
"""Verify image-provided package versions satisfy project requirements."""
from __future__ import annotations
import argparse
import importlib.metadata as metadata
import sys
import tomllib
from pathlib imp... | m2lines/Samudra | scripts/container/verify_image_packages.py | .py | 72c21b928265d371 | 7.6 | 15 |
# SPDX-FileCopyrightText: 2026 Samudra Authors
#
# SPDX-License-Identifier: Apache-2.0
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "xarray[io]",
# "zarr<3", # Zarr v2 --> change to `zarr<3`; Zarr v3 --> change to `zarr>=3`.
# "dask",
# "requests",
# "aiohttp",
# "numcodecs>=0.15",
# ]
... | m2lines/Samudra | scripts/open_zarr_tuning.py | .py | e3d846b16822653a | 7.6 | 15 |
from decimal import Decimal
from fractions import Fraction
from math import ceil, floor
from .abc_timestamps import ABCTimestamps
from .rounding_method import RoundingMethod
from .time_type import TimeType
__all__ = ["FPSTimestamps"]
class FPSTimestamps(ABCTimestamps):
"""Create a Timestamps object from a fps.
... | moi15moi/VideoTimestamps | video_timestamps/fps_timestamps.py | .py | c6d9379d7749f34e | 7.48 | 8 |
from collections.abc import Callable
from enum import Enum, auto
from fractions import Fraction
from math import ceil, floor
__all__ = ["RoundingMethod"]
RoundingCallType = Callable[[Fraction], int]
def floor_method(number: Fraction) -> int:
return floor(number)
def round_method(number: Fraction) -> int:
i... | moi15moi/VideoTimestamps | video_timestamps/rounding_method.py | .py | b5143b8d1096adbe | 7.48 | 8 |
from fractions import Fraction
from io import StringIO
from pathlib import Path
from .abc_timestamps import ABCTimestamps
from .fps_timestamps import FPSTimestamps
from .rounding_method import RoundingMethod
from .time_type import TimeType
from .timestamps_file_parser import TimestampsFileParser
from .video_timestamps... | moi15moi/VideoTimestamps | video_timestamps/text_file_timestamps.py | .py | f29f523ca6d0fcc6 | 7.48 | 8 |
from __future__ import annotations
from bisect import bisect_left, bisect_right
from decimal import Decimal, localcontext
from fractions import Fraction
from pathlib import Path
from typing import Literal, overload
from .abc_timestamps import ABCTimestamps
from .rounding_method import RoundingCallType, RoundingMethod... | moi15moi/VideoTimestamps | video_timestamps/video_timestamps.py | .py | 7bacdd685e6ee47e | 7.48 | 8 |
import logging
import time
from collections.abc import Callable
from enum import IntEnum
from ipaddress import ip_address
from pathlib import Path
from socket import AF_INET, AF_INET6, IPPROTO_TCP, TCP_NODELAY
from socket import socket as sock
from threading import Thread
from rlbot import flat
from rlbot.utils.loggin... | RLBot/python-interface | rlbot/interface.py | .py | c1013eb9ab90cdca | 7.42 | 6 |
import os
from traceback import print_exc
from rlbot import flat
from rlbot.interface import (
RLBOT_SERVER_IP,
RLBOT_SERVER_PORT,
MsgHandlingResult,
SocketRelay,
)
from rlbot.managers.rendering import Renderer
from rlbot.utils import fill_desired_game_state
from rlbot.utils.logging import DEFAULT_LOGG... | RLBot/python-interface | rlbot/managers/bot.py | .py | 1b8bab43aa83b404 | 7.42 | 6 |
import os
from logging import Logger
from traceback import print_exc
from rlbot import flat
from rlbot.interface import (
RLBOT_SERVER_IP,
RLBOT_SERVER_PORT,
MsgHandlingResult,
SocketRelay,
)
from rlbot.managers import Renderer
from rlbot.utils import fill_desired_game_state
from rlbot.utils.logging im... | RLBot/python-interface | rlbot/managers/hivemind.py | .py | 9b58fdf5c8105ac7 | 7.42 | 6 |
import os
import stat
from pathlib import Path
from time import sleep
import psutil
from rlbot import flat
from rlbot.interface import RLBOT_SERVER_IP, RLBOT_SERVER_PORT, SocketRelay
from rlbot.utils import fill_desired_game_state, gateway
from rlbot.utils.logging import DEFAULT_LOGGER
from rlbot.utils.os_detector im... | RLBot/python-interface | rlbot/managers/match.py | .py | b1d6e74431444da1 | 7.42 | 6 |
import math
from collections.abc import Callable, Sequence
from contextlib import contextmanager
from rlbot import flat
from rlbot.interface import SocketRelay
from rlbot.utils.logging import get_logger
MAX_INT = 2147483647 // 2
DEFAULT_GROUP_ID = "default"
def _get_anchor(
anchor: flat.RenderAnchor | flat.Ball... | RLBot/python-interface | rlbot/managers/rendering.py | .py | 7da1cafc8a3d5b57 | 7.42 | 6 |
import os
from traceback import print_exc
from rlbot import flat
from rlbot.interface import (
RLBOT_SERVER_IP,
RLBOT_SERVER_PORT,
MsgHandlingResult,
SocketRelay,
)
from rlbot.managers import Renderer
from rlbot.utils import fill_desired_game_state
from rlbot.utils.logging import DEFAULT_LOGGER, get_lo... | RLBot/python-interface | rlbot/managers/script.py | .py | a94a3a765355e67b | 7.42 | 6 |
import socket
import subprocess
from pathlib import Path
import psutil
from rlbot.interface import RLBOT_SERVER_PORT
from rlbot.utils.logging import DEFAULT_LOGGER
from rlbot.utils.os_detector import CURRENT_OS
if CURRENT_OS != "Windows":
import shlex
def find_file(base_dir: Path, file_name: str) -> Path | Non... | RLBot/python-interface | rlbot/utils/gateway.py | .py | 5943cff88e9ec0b7 | 7.42 | 6 |
# Copyright 2023 Simone Chemelli and contributors
# SPDX-License-Identifier: Apache-2.0
"""Support for Vodafone Station."""
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import UTC, datetime
from http import HTTPStatus
from http.cookies import SimpleCookie
from io import BytesIO
... | chemelli74/aiovodafone | src/aiovodafone/api.py | .py | 266804f1650f848e | 7.56 | 12 |
# Copyright 2023 Simone Chemelli and contributors
# SPDX-License-Identifier: Apache-2.0
"""Constants for Vodafone Station."""
import logging
from enum import StrEnum
from typing import Any
from aiohttp import ClientTimeout
_LOGGER = logging.getLogger(__package__)
HEADERS = {
"User-Agent": (
"Mozilla/5.... | chemelli74/aiovodafone | src/aiovodafone/const.py | .py | 4f960c50861fa562 | 7.56 | 12 |
# Copyright 2023 Simone Chemelli and contributors
# SPDX-License-Identifier: Apache-2.0
"""Homeware Vodafone Station model API implementation."""
import datetime as dt
import hashlib
import hmac
import re
import secrets
from http import HTTPMethod
from typing import TYPE_CHECKING, Any, Final, cast
import orjson
fro... | chemelli74/aiovodafone | src/aiovodafone/models/homeware.py | .py | 78442af0f35c4ae3 | 7.56 | 12 |
# Copyright 2023 Simone Chemelli and contributors
# SPDX-License-Identifier: Apache-2.0
"""Technicolor Vodafone Station model API implementation."""
import asyncio
import hashlib
from datetime import UTC, datetime, timedelta
from http import HTTPMethod
from typing import Any
from aiohttp import ClientResponseError
... | chemelli74/aiovodafone | src/aiovodafone/models/technicolor.py | .py | 3eb3127285364852 | 7.56 | 12 |
# Copyright 2023 Simone Chemelli and contributors
# SPDX-License-Identifier: Apache-2.0
"""UltraHub Vodafone Station model API implementation."""
import base64
import contextlib
from datetime import UTC, datetime, timedelta
from http import HTTPMethod
from typing import Any, cast
import orjson
from aiohttp import (
... | chemelli74/aiovodafone | src/aiovodafone/models/ultrahub.py | .py | 2a29be65ddd0dbd6 | 7.56 | 12 |
# Copyright 2023 Simone Chemelli and contributors
# SPDX-License-Identifier: Apache-2.0
"""Decrypt and encrypt messages compatible to the "SJCL" message format.
Credits to https://github.com/berlincode/sjcl
"""
import base64
from typing import Any, cast
import orjson
from Crypto.Cipher import AES
from Crypto.Hash i... | chemelli74/aiovodafone | src/aiovodafone/sjcl.py | .py | 5a7d3e300915b4e4 | 7.56 | 12 |
# Copyright 2023 Simone Chemelli and contributors
# SPDX-License-Identifier: Apache-2.0
"""Shared pytest fixtures and lightweight async HTTP fakes."""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
import pytest
from yarl import URL
if TYPE_CHECKING:
from ... | chemelli74/aiovodafone | tests/conftest.py | .py | f5329f0607670aae | 8.06 | 12 |
# Copyright 2023 Simone Chemelli and contributors
# SPDX-License-Identifier: Apache-2.0
"""Tests for common API base helpers."""
from __future__ import annotations
import asyncio
from datetime import UTC, datetime
from http import HTTPMethod
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any, ca... | chemelli74/aiovodafone | tests/test_api_base.py | .py | 3fa76888c01b5dfa | 8.06 | 12 |
# Copyright 2023 Simone Chemelli and contributors
# SPDX-License-Identifier: Apache-2.0
"""Base tests for aiovodafone."""
from aiovodafone.api import (
VodafoneStationCommonApi,
VodafoneStationDevice,
)
from aiovodafone.exceptions import (
AlreadyLogged,
CannotAuthenticate,
CannotConnect,
Gene... | chemelli74/aiovodafone | tests/test_init.py | .py | 31638801cff3deb4 | 7.06 | 12 |
# Copyright 2023 Simone Chemelli and contributors
# SPDX-License-Identifier: Apache-2.0
"""Tests for model registry and device detection."""
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Any, cast
import pytest
from aiohttp import ClientConnectorError
from aiovodafone.exceptio... | chemelli74/aiovodafone | tests/test_models_init.py | .py | f4f9f7b3fb67dd73 | 8.06 | 12 |
# Copyright 2023 Simone Chemelli and contributors
# SPDX-License-Identifier: Apache-2.0
"""Fixture-based tests for SJCL encryption/decryption compatibility."""
from __future__ import annotations
import base64
import urllib.parse
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
import orjson
impo... | chemelli74/aiovodafone | tests/test_sjcl.py | .py | ec7ac1ffb5ecac5d | 8.06 | 12 |
"""vCon lifecycle hook — no-op default implementation.
Called when vCons are created or deleted via the REST API.
Replace this file at Docker build time with any custom implementation
(e.g. audit logging, metrics, notifications).
"""
from typing import Dict, List, Optional
def on_vcon_created(
vcon_id: str,
... | vcon-dev/vcon-server | api/vcon_hook.py | .py | c6e6bc621c9810c5 | 7.04 | 11 |
import settings
import yaml
_config: dict = None
def get_config() -> dict:
"""This is to keep logic of accessing config in one place"""
global _config
with open(settings.CONSERVER_CONFIG_FILE) as file:
_config = yaml.safe_load(file) or {}
return _config
def get_worker_count() -> int:
""... | vcon-dev/vcon-server | common/config.py | .py | 7a68faa04f517b73 | 7.54 | 11 |
import random
from typing import Literal, Optional, TypedDict
from lib.logging_utils import init_logger
from vcon import Vcon
logger = init_logger(__name__)
class OnlyIfFilter(TypedDict, total=False):
"""``only_if`` clause inside :class:`FilterOptions`.
Exactly one of ``type`` or ``purpose`` should be suppl... | vcon-dev/vcon-server | common/lib/links/filters.py | .py | a295fc905066e8e6 | 7.54 | 11 |
import atexit
import logging
import os
import socket
from opentelemetry import metrics
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.... | vcon-dev/vcon-server | common/lib/metrics.py | .py | c0bd531cbb0a8c93 | 7.54 | 11 |
"""
Shared OpenAI/Azure/LiteLLM client for vcon-server.
When LITELLM_PROXY_URL and LITELLM_MASTER_KEY are set in opts,
returns an OpenAI client configured to use the LiteLLM proxy. Otherwise uses
direct OpenAI or Azure OpenAI credentials from opts.
All links and storage that call OpenAI should use get_openai_client(o... | vcon-dev/vcon-server | common/lib/openai_client.py | .py | 81a8a014b6ed5918 | 7.54 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.