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
import logging from collections.abc import Mapping from pprint import pformat from typing import Annotated, Any from django.conf import settings from mpt_extension_sdk.core.extension import Extension from mpt_extension_sdk.core.security import JWTAuth from mpt_extension_sdk.mpt_http.base import MPTClient from mpt_exte...
softwareone-platform/swo-adobe-vipm-extension
adobe_vipm/extension.py
.py
12091accf50d06f4
7.6
15
import logging import traceback from adobe_vipm.adobe.errors import AdobeTransportError from adobe_vipm.flows.constants import OrderType from adobe_vipm.flows.fulfillment.change import fulfill_change_order from adobe_vipm.flows.fulfillment.configuration import fulfill_configuration_order from adobe_vipm.flows.fulfillm...
softwareone-platform/swo-adobe-vipm-extension
adobe_vipm/flows/fulfillment/base.py
.py
7a561cf8e38a4221
7.6
15
""" This module contains the logic to implement the configuration fulfillment flow. It exposes a single function that is the entrypoint for configuration order processing. """ import logging from adobe_vipm.adobe.client import get_adobe_client from adobe_vipm.adobe.errors import AdobeError, SubscriptionUpdateError f...
softwareone-platform/swo-adobe-vipm-extension
adobe_vipm/flows/fulfillment/configuration.py
.py
5f218c43eed86bce
7.6
15
""" This module contains the logic to implement the purchase fulfillment flow. It exposes a single function that is the entrypoint for purchase order processing. """ import logging from mpt_extension_sdk.mpt_http.mpt import update_agreement, update_order from adobe_vipm.adobe.client import get_adobe_client from ado...
softwareone-platform/swo-adobe-vipm-extension
adobe_vipm/flows/fulfillment/purchase.py
.py
b86818e8bea2dbbc
7.6
15
import logging from mpt_extension_sdk.mpt_http.mpt import update_agreement, update_order from adobe_vipm.adobe.client import get_adobe_client from adobe_vipm.adobe.constants import AdobeOrderStatus, ResellerChangeAction from adobe_vipm.adobe.errors import AdobeAPIError from adobe_vipm.airtable.models import get_trans...
softwareone-platform/swo-adobe-vipm-extension
adobe_vipm/flows/fulfillment/reseller_transfer.py
.py
18a008d96b101452
7.6
15
""" This module contains the logic to implement the switch fulfillment flow. It exposes a single function that is the entrypoint for change orders that carry a mid-term upgrade (SWITCH) payload computed from an Adobe recommendation. """ import logging from mpt_extension_sdk.mpt_http.mpt import update_order from ado...
softwareone-platform/swo-adobe-vipm-extension
adobe_vipm/flows/fulfillment/switch.py
.py
72830c6d4aee26bf
7.6
15
""" This module contains the logic to implement the termination fulfillment flow. It exposes a single function that is the entrypoint for termination order processing. """ import logging from adobe_vipm.adobe.client import get_adobe_client from adobe_vipm.adobe.constants import AdobeErrorCode from adobe_vipm.adobe.e...
softwareone-platform/swo-adobe-vipm-extension
adobe_vipm/flows/fulfillment/termination.py
.py
5b18b6d07348fbd5
7.6
15
import logging from django.conf import settings from mpt_extension_sdk.mpt_http.base import MPTClient from mpt_extension_sdk.mpt_http.mpt import get_agreements_by_query from adobe_vipm.adobe.constants import ThreeYearCommitmentStatus from adobe_vipm.flows.constants import Param logger = logging.getLogger(__name__) ...
softwareone-platform/swo-adobe-vipm-extension
adobe_vipm/flows/mpt.py
.py
0a3359b5292d4110
7.6
15
import copy import datetime as dt import json import logging from pathlib import Path from urllib.parse import urljoin import requests from django.conf import settings logger = logging.getLogger(__name__) TOKEN_CACHE_FILE = Path.home() / ".nav-token-cache.json" def get_token_from_disk() -> str | None: """Retri...
softwareone-platform/swo-adobe-vipm-extension
adobe_vipm/flows/nav.py
.py
194377f78ab958b3
7.6
15
from abc import ABC, abstractmethod from collections.abc import Callable from mpt_extension_sdk.mpt_http.base import MPTClient from adobe_vipm.flows.context import Context NextStep = Callable[[MPTClient, Context], None] # TODO: why it is still here and not in SDK??? class Step(ABC): @abstractmethod def __c...
softwareone-platform/swo-adobe-vipm-extension
adobe_vipm/flows/pipeline.py
.py
9be611299c14d662
7.6
15
from mpt_extension_sdk.mpt_http import mpt from adobe_vipm.airtable import models from adobe_vipm.flows import utils as flows_utils from adobe_vipm.utils import get_commitment_start_date class PriceManager: """ PriceManager class to manage the prices to update the agreement or subscription. Attributes: ...
softwareone-platform/swo-adobe-vipm-extension
adobe_vipm/flows/sync/price_manager.py
.py
37b24ea0fdba54c7
7.6
15
""" Evolutionary Utilities """ import glob import json import os import sys from typing import List, Optional import numpy as np from absl import logging class Individual: """Single Individual in an Island""" def __init__( self, island_id: int, generation_id: int, counter_id...
RishiHazra/Revolve
evolutionary_utils/entities.py
.py
ac79f939b72db6c5
7.66
20
import os import sys sys.path.append(os.environ["ROOT_PATH"]) from rewards_database import RevolveDatabase, EurekaDatabase from modules import * import utils import prompts from evolutionary_utils.custom_environment import CustomEnvironment import absl.logging as logging from functools import partial from utils import...
RishiHazra/Revolve
main.py
.py
7168618f1f3a9633
7.66
20
""" Various stages of individual generation, training, and evaluation: 1. Reward Function Generation 2. Policy Training 3. Policy Evaluation """ import concurrent.futures import json import multiprocessing import os import time from typing import Tuple, Optional, Dict import absl.logging as logging import hydra impor...
RishiHazra/Revolve
modules.py
.py
a66ae505f195227d
7.66
20
import os import random import sys from typing import Tuple, List, Dict import numpy as np from absl import logging from evolutionary_utils.entities import Island def normalized(x: List[float], temp: float = 1): x = np.array(x) return np.exp(x / temp) / np.sum(np.exp(x / temp), axis=0) class RevolveDataba...
RishiHazra/Revolve
rewards_database.py
.py
84917d92b129fe07
7.66
20
import json def read_json_lines(file_path): data = [] try: with open(file_path, "r") as file: for line in file: if line.strip(): # Ensuring the line is not empty data.append(json.loads(line)) except FileNotFoundError: print(f"Error: The file...
RishiHazra/Revolve
rl_agent/add_files.py
.py
b0f9c953ca1e0176
7.66
20
import inspect import os import random import math import fcntl from copy import copy, deepcopy from collections import Counter from typing import Optional, Callable, List, Tuple, Dict import torch import numpy as np class DataLogger: def __init__(self, log_file_path: str): self.log_file_path = log_file_...
RishiHazra/Revolve
utils.py
.py
8e649dfa65efba9c
7.66
20
from tensorflow import keras import numpy as np import os class Load_data_RNA(keras.utils.Sequence): """generate data in sequence mode for training the neural network""" def __init__(self, batch_size, N_batches, path, files_list, chunck_size, labels, batch_loading, max_seq_len): self.batch...
mem3nto0/ModiDeC-RNA-modification-classifier
Load_data_for_training_V2.py
.py
b5b7e8720928e264
7.57
13
from typing import Annotated import dagger from dagger import Doc, function, object_type @object_type class Chart: """chart""" source: dagger.Directory helm: dagger.Helm uuid: str @function async def push( self, registry: Annotated[str, Doc("Helm registry")] = "", v...
GitGuardian/ggbridge
dagger/src/ggbridge/chart.py
.py
a2c19e47746ac781
7.45
7
from typing import Annotated import dagger from dagger import Doc, Name, dag, function, object_type from .repository import Repository @object_type class Image: """image""" source: dagger.Directory repository: Repository container_: dagger.Container apko: dagger.Apko cosign: dagger.Cosign ...
GitGuardian/ggbridge
dagger/src/ggbridge/image.py
.py
40602434d9425f15
7.45
7
from typing import Annotated import dagger from dagger import Doc, Name, function, object_type @object_type class Repository: """repository""" source: dagger.Directory melange: dagger.Melange @function async def container( self, ) -> dagger.Container: """Return container""" ...
GitGuardian/ggbridge
dagger/src/ggbridge/repository.py
.py
5a34a27614443880
7.45
7
# Imports import os import tempfile import time from multiprocessing import get_context from multiprocessing.context import SpawnProcess from stouputils.lock import LockFifo, RLockFifo def _safe_append(path: str, line: str) -> None: time.sleep(1) # Simulate some delay to increase chance of interleaving if locks fa...
Stoupy51/stouputils
examples/lock.py
.py
fd5c90fd71f31115
7.5
9
""" Regenerate the mechanical parts of the package layout: re-export lists and lazy import markers. Explicit re-exports are what makes PEP 810 lazy imports work, since a star import resolves every deferred name at once. Maintaining those lists by hand is the price, so this script derives them from the source instead: ...
Stoupy51/stouputils
scripts/sync_api.py
.py
c54e651719526263
7.5
9
""" Deprecated functions and classes. ::deprecated:: vX.Y.Z - Description of deprecation reason and alternative (if applicable) This module contains deprecated functions that have been replaced by new implementations These functions are retained for backward compatibility and will log deprecation warnings when used. "...
Stoupy51/stouputils
stouputils/_deprecated.py
.py
1652b8c30517bf12
7.5
9
# Lazy imports (PEP 810), ignored before Python 3.15 from ..lazy import ALWAYS_LAZY __lazy_modules__ = ALWAYS_LAZY # Imports from typing import TYPE_CHECKING from ..config import StouputilsConfig as Cfg from ..decorators.timing import measure_time from ..io.path import clean_path, relative_path from ..print.message...
Stoupy51/stouputils
stouputils/all_doctests/launch.py
.py
993cade4c9677d05
8
9
""" Consistency check for packages that re-export their submodules explicitly. Explicit re-exports are what makes PEP 810 lazy imports possible, since a star import resolves every deferred name at once. The cost is that a new public function is easy to forget in the parent package, so this module compares each submodu...
Stoupy51/stouputils
stouputils/all_doctests/reexports.py
.py
6624be9f3e42ddfc
8
9
""" This module is used to run all the doctests for all the modules in a given directory. - :py:func:`launch_tests` - Main function to launch tests for all modules in the given directory. - :py:func:`test_module_with_progress` - Test a module with testmod and measure the time taken with progress printing. .. image:: ...
Stoupy51/stouputils
stouputils/all_doctests/utils.py
.py
6e687906c63f7513
7
9
""" Common utilities shared by documentation generators (Sphinx, Zensical, etc.). This module contains functions and helpers that are used by multiple documentation backends, avoiding code duplication. """ # Lazy imports (PEP 810), ignored before Python 3.15 from ...lazy import ALWAYS_LAZY __lazy_modules__ = ALWAYS_L...
Stoupy51/stouputils
stouputils/applications/automatic_docs/common.py
.py
96785f6b489d5e5a
7.5
9
""" Docstring normalization applied before Sphinx parses the output of autodoc. reStructuredText only recognizes a doctest block when it starts a new block, which means a blank line must separate it from the prose introducing it. A docstring written without that blank line gets folded into the preceding paragraph, so ...
Stoupy51/stouputils
stouputils/applications/automatic_docs/docstring.py
.py
bbbc21b1b1efe1fe
7.5
9
""" Orchestration of a documentation build: lay out the folders, write the generated files, then run Sphinx. ``sphinx_docs`` is the only entry point most projects ever call. Every step it performs is a parameter, so a project needing a different landing page or a different build command replaces that one callable inst...
Stoupy51/stouputils
stouputils/applications/automatic_docs/sphinx/builder.py
.py
6a8eb8e288d0cb68
7.5
9
""" Generation of the ``docs/source/conf.py`` file Sphinx reads. The file is produced as text rather than imported from a template, because a fair part of it is decided by the caller's arguments: which forge hosts the sources, which theme renders them, and which pygments styles colour them. """ # Lazy imports (PEP 810...
Stoupy51/stouputils
stouputils/applications/automatic_docs/sphinx/conf_file.py
.py
3c51cd09a14842fe
7.5
9
""" Code forge URL conventions, used to link a documented object back to its source. Every forge agrees that a URL needs a repository, a branch and a path, and no two of them agree on the order. This module holds that knowledge in one table so the rest of the generator never has to care. """ # Lazy imports (PEP 810), ...
Stoupy51/stouputils
stouputils/applications/automatic_docs/sphinx/forges.py
.py
d9c9da3aa7bbad27
7.5
9
""" Editor-grade syntax highlighting for the Python code blocks of the generated documentation. Two pieces are needed, and neither works without the other: :mod:`.styles` supplies the VS Code palettes, and :mod:`.semantics` supplies the token distinctions those palettes expect but that Pygments' Python lexer does not ...
Stoupy51/stouputils
stouputils/applications/automatic_docs/sphinx/highlighting/__init__.py
.py
ed4952834cd9b6fb
7.5
9
""" Recovery of the token distinctions Pygments' Python lexer does not make. An editor colours ``task: str = "all"`` in three different ways because its grammar knows that ``task`` is a variable, ``str`` a type and ``"all"`` a string. Pygments only knows the third: it tags an identifier as ``Name.Function`` or ``Name....
Stoupy51/stouputils
stouputils/applications/automatic_docs/sphinx/highlighting/semantics.py
.py
c7fa7ed3b1aa3253
7.5
9
""" Theme, syntax highlighting and stylesheet concerns of the generated documentation. Pygments' Python lexer is coarse: it only tags an identifier as ``Name.Function`` or ``Name.Class`` when a literal ``def`` or ``class`` introduces it, and emits a bare ``Name`` for every call, attribute, argument and variable. A pal...
Stoupy51/stouputils
stouputils/applications/automatic_docs/sphinx/theming.py
.py
50a82a6fe21751dc
7.5
9
""" Zensical documentation generation utilities. This module provides a comprehensive set of utilities for automatically generating and managing documentation for Python projects using **Zensical** (a modern static site generator based on MkDocs Material) and **mkdocstrings** for API reference generation from docstrin...
Stoupy51/stouputils
stouputils/applications/automatic_docs/zensical.py
.py
bee0d1411a6cdc33
7.5
9
# Lazy imports (PEP 810), ignored before Python 3.15 from ..lazy import ALWAYS_LAZY __lazy_modules__ = ALWAYS_LAZY # Imports import fnmatch import os from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo from ..decorators import LogLevels, handle_error from ..io.path import clean_path, super_copy # Function that mak...
Stoupy51/stouputils
stouputils/archive/creation.py
.py
25aa52ae4d8f06ee
7.5
9
# Lazy imports (PEP 810), ignored before Python 3.15 from ...lazy import ALWAYS_LAZY __lazy_modules__ = ALWAYS_LAZY # Imports import contextlib import os from dataclasses import dataclass, field from typing import ClassVar from zipfile import ZIP_DEFLATED, ZipFile from ...decorators.error_handling import handle_err...
Stoupy51/stouputils
stouputils/archive/repair/repair.py
.py
08ec1445749643af
7.5
9
""" Byte level scanning of a zip archive whose structure cannot be trusted. The standard library refuses to open a damaged archive, so every offset here is treated as a hint: signatures are searched for, headers are bounds checked, and anything unreadable is reported as None. """ # Lazy imports (PEP 810), ignored befo...
Stoupy51/stouputils
stouputils/archive/repair/scanner.py
.py
29862e256aace6e5
7.5
9
#!/usr/bin/env python3 # Copyright 2025 Canonical Ltd. # See LICENSE file for licensing details. """Aggregate results from test matrix into a tabular form.""" import json import sys import pandas as pd FOOTNOTES = """ Legend: ✅: All tests passed for this dimension and this tox environment ⚠️: Some tests failed wh...
canonical/spark-k8s-bundle
.github/scripts/aggregate_results.py
.py
831e2bff8107eed1
7.42
6
#! /usr/bin/env python import os import shutil import subprocess import tempfile import sys import logging import argparse # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) SPHINX_DIR = os.path.join(os.getcwd(), ...
canonical/spark-k8s-bundle
docs/.sphinx/get_vale_conf.py
.py
93e608f47cce3164
7.42
6
#!/usr/bin/env python3 # Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. """Azure storage module.""" import os from dataclasses import dataclass from itertools import islice from azure.storage.blob import BlobServiceClient from spark_test.core import ObjectStorageUnit @dataclass class Crede...
canonical/spark-k8s-bundle
python/spark_test/core/azure_storage.py
.py
f1350c632e213f00
7.92
6
#!/usr/bin/env python3 # Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. """The base classes for bundle backend.""" import enum import subprocess from abc import abstractmethod from pathlib import Path from spark8t.utils import WithLogging class BundleBackendEnum(str, enum.Enum): """The...
canonical/spark-k8s-bundle
python/spark_test/core/bundle/__init__.py
.py
39c489bd1cd5ab3c
7.92
6
#!/usr/bin/env python3 # Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. """Terraform backend to apply the bundle.""" import json import shutil import tempfile from pathlib import Path from . import BundleBackend, BundleBackendEnum class TerraformBackend(BundleBackend): """Terraform bun...
canonical/spark-k8s-bundle
python/spark_test/core/bundle/terraform.py
.py
d5fbd136ccbfd010
7.92
6
# Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. """Kyuubi module.""" import tempfile from contextlib import closing, contextmanager from pathlib import Path from typing import Generator, Type, TypeAlias from impala.dbapi import connect from impala.hiveserver2 import HiveServer2Connection as ...
canonical/spark-k8s-bundle
python/spark_test/core/kyuubi.py
.py
dc8bffb4d59232ca
7.92
6
# Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. """Pod module.""" import json import subprocess from functools import cached_property from pathlib import Path from typing import Dict, Iterator, List, cast from lightkube import Client, KubeConfig from lightkube.resources import core_v1 from ...
canonical/spark-k8s-bundle
python/spark_test/core/pod.py
.py
5eac88d96d795d1c
7.92
6
#!/usr/bin/env python3 # Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. """S3 module.""" from __future__ import annotations import logging import os from dataclasses import dataclass from typing import TYPE_CHECKING, Any from boto3.session import Session from botocore.client import Config fr...
canonical/spark-k8s-bundle
python/spark_test/core/s3.py
.py
25af0b6d6d44b493
7.92
6
#!/usr/bin/env python3 # Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. """Azure storage fixtures.""" import os import uuid import pytest from spark_test.core.azure_storage import Container, Credentials @pytest.fixture(scope="session") def azure_credentials(): """Azure storage credenti...
canonical/spark-k8s-bundle
python/spark_test/fixtures/azure_storage.py
.py
65b15d40d0af1792
7.92
6
#!/usr/bin/env python3 # Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. """K8s fixtures.""" import os import time from pathlib import Path from typing import Iterable import pytest from lightkube import KubeConfig from lightkube.resources.core_v1 import Namespace from spark8t.domain import De...
canonical/spark-k8s-bundle
python/spark_test/fixtures/k8s.py
.py
90799ee62d0e52a1
7.92
6
#!/usr/bin/env python3 # Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. """Pod fixtures.""" import pytest from spark_test.core.pod import Pod from spark_test.fixtures.k8s import kubeconfig, namespace # noqa from spark_test.fixtures.service_account import service_account # noqa @pytest.fix...
canonical/spark-k8s-bundle
python/spark_test/fixtures/pod.py
.py
d61876db6c960663
7.92
6
#!/usr/bin/env python3 # Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. """S3 fixtures.""" import os import subprocess import uuid import pytest from spark_test import BINS, PKG_DIR from spark_test.core.s3 import Bucket, Credentials @pytest.fixture(scope="session") def credentials(): "...
canonical/spark-k8s-bundle
python/spark_test/fixtures/s3.py
.py
8ddbb9d28e901315
7.92
6
# Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. """Service account fixtures.""" import uuid import pytest from spark8t.domain import ServiceAccount from spark8t.registry.k8s import K8sServiceAccountRegistry from spark8t.utils import PropertyFile from spark_test.fixtures.azure_storage import...
canonical/spark-k8s-bundle
python/spark_test/fixtures/service_account.py
.py
6dda0bee2d6787f9
7.92
6
import shutil import pytest def pytest_addoption(parser): """Add CLI options to pytest.""" parser.addoption( "--bench-sf", choices=[ "sf1", "sf10", "sf30", "sf100", "sf300", "sf1000", "sf3000", "sf...
canonical/spark-k8s-bundle
python/tests/integration/bench/conftest.py
.py
9a26e497067cecb7
7.92
6
#!/usr/bin/env python3 # Copyright 2025 Canonical Ltd. # See LICENSE file for licensing details. import logging import time from collections import defaultdict from datetime import date from subprocess import check_output from typing import cast import jubilant import polars as pl import pytest from great_tables impor...
canonical/spark-k8s-bundle
python/tests/integration/bench/test_benchmark_kyuubi.py
.py
90f09f2df97c4f8b
7.92
6
# Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. from __future__ import annotations import ast import json import logging import re import shutil import subprocess import urllib.parse from contextlib import contextmanager from pathlib import Path from typing import cast import httpx import ju...
canonical/spark-k8s-bundle
python/tests/integration/helpers.py
.py
fcf9b4cbf4dc2b9f
7.92
6
#!/usr/bin/env python3 # Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. import logging import jubilant import pytest logger = logging.getLogger(__name__) @pytest.mark.skip_if_deployed def test_deploy_bundle(spark_bundle: list[str]) -> None: """Deploy bundle.""" deployed_applicatio...
canonical/spark-k8s-bundle
python/tests/integration/test_bundle.py
.py
00b59ad1e360cca9
7.92
6
#!/usr/bin/env python3 # Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. from __future__ import annotations import logging from typing import cast import jubilant import psycopg2 import pytest from tenacity import Retrying, stop_after_attempt, wait_fixed from spark_test.core.kyuubi import Ky...
canonical/spark-k8s-bundle
python/tests/integration/test_kyuubi.py
.py
79c622948f96216c
7.92
6
import logging import re import subprocess from pathlib import Path from typing import cast import boto3.session import httpx import jubilant import pytest from azure.storage.blob import BlobServiceClient from botocore.client import Config from tenacity import Retrying, stop_after_attempt, wait_fixed from spark_test....
canonical/spark-k8s-bundle
python/tests/integration/test_spark_job.py
.py
a54c7936bd51e9a1
7.92
6
"""Integration tests types module.""" from typing import ContextManager, Protocol, TypedDict class PortForwarder(Protocol): """Type stub for the port_forward fixture.""" def __call__( self, *, pod: str, port: int, namespace: str, on_port: int | None = None ) -> ContextManager: """Create ...
canonical/spark-k8s-bundle
python/tests/integration/types.py
.py
2af1cbf639e4be02
7.42
6
#!/usr/bin/env python3 # Copyright 2026 Canonical Ltd. # See LICENSE file for licensing details. """Extract shell code blocks from MyST Markdown tutorial files. Usage ----- # Auto-discover: process all .md files with spread metadata in a directory. python3 tests/tutorial/extract_commands.py docs/tutorial/ tes...
canonical/spark-k8s-bundle
python/tests/tutorial/extract_commands.py
.py
1e2afcf2c1cccd46
7.92
6
"""Audio File Manager which keeps an audio file open until a request in another file is made. This workflow avoids closing/opening a same file repeatedly. """ from __future__ import annotations from pathlib import Path from typing import TYPE_CHECKING from osekit.audio_backend.mseed_backend import MSeedBackend from...
Project-OSmOSE/OSEkit
src/osekit/audio_backend/audio_file_manager.py
.py
46a456d0a0d20d55
7.57
13
from os import PathLike import numpy as np def _require_obspy() -> None: try: import obspy # noqa: PLC0415, F401 except ImportError as e: msg = "MSEED support requires the optional dependency 'obspy' " "Install with: ``pip install osekit[mseed]``. " "If you're on windows and ...
Project-OSmOSE/OSEkit
src/osekit/audio_backend/mseed_backend.py
.py
7336acb2966e825e
7.57
13
from os import PathLike import numpy as np import soundfile as sf class SoundFileBackend: """Backend for reading conventional audio files (WAV, FLAC, MP3...).""" def __init__(self) -> None: """Instantiate a SoundFileBackend.""" self._file: sf.SoundFile | None = None def close(self) -> N...
Project-OSmOSE/OSEkit
src/osekit/audio_backend/soundfile_backend.py
.py
2581508ba53d6d58
7.57
13
"""``AudioDataset`` is a collection of ``AudioData`` objects. ``AudioDataset`` is a collection of ``AudioData``, with methods that simplify repeated operations on the audio data. """ from __future__ import annotations import logging from typing import TYPE_CHECKING, Literal, Self from osekit.core.audio_data import ...
Project-OSmOSE/OSEkit
src/osekit/core/audio_dataset.py
.py
3238a1d7c4e1e42f
7.57
13
"""Audio file associated with timestamps.""" from __future__ import annotations import typing from typing import TYPE_CHECKING from osekit.config import TIMESTAMP_FORMATS_EXPORTED_FILES from osekit.utils.timestamp import strptime_from_text if TYPE_CHECKING: from os import PathLike from pathlib import Path ...
Project-OSmOSE/OSEkit
src/osekit/core/audio_file.py
.py
d563ab262131ebe7
7.57
13
"""``AudioItem`` corresponding to a portion of an ``AudioFile`` object.""" from __future__ import annotations from collections.abc import Generator from typing import TYPE_CHECKING import numpy as np from osekit.core.audio_file import AudioFile from osekit.core.base_item import BaseItem if TYPE_CHECKING: from ...
Project-OSmOSE/OSEkit
src/osekit/core/audio_item.py
.py
f7838acf54d08b57
7.57
13
"""``BaseData``: Base class for the Data objects. Data corresponds to data scattered through different Files. The data is accessed via an Item object per File. """ from __future__ import annotations import itertools from abc import ABC, abstractmethod from pathlib import Path from typing import Self, TypeVar import...
Project-OSmOSE/OSEkit
src/osekit/core/base_data.py
.py
3cfb00900806a42a
7.57
13
"""``BaseFile``: Base class for the File objects. A File object associates file-written data to timestamps. """ from __future__ import annotations import typing from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Self from osekit.config import ( TIMESTAMP_FORMAT_EXPORTED_FILES_LOCALIZED, T...
Project-OSmOSE/OSEkit
src/osekit/core/base_file.py
.py
4b6000a313153592
7.57
13
"""``BaseItem``: Base class for the Item objects. Items correspond to a portion of a File object. """ from __future__ import annotations from abc import ABC from typing import TYPE_CHECKING, TypeVar import numpy as np from osekit.core.base_file import BaseFile from osekit.core.event import Event if TYPE_CHECKING:...
Project-OSmOSE/OSEkit
src/osekit/core/base_item.py
.py
99229158798f3385
7.57
13
"""The Detection class represents a detection made on APLOSE.""" import math from dataclasses import dataclass from pathlib import Path from typing import Any, Literal, Self import pandas as pd from matplotlib.patches import Rectangle from pandas import Timestamp from osekit.core.event import Event from osekit.utils...
Project-OSmOSE/OSEkit
src/osekit/core/detection.py
.py
52c557493af007da
7.57
13
"""Event class.""" from __future__ import annotations import bisect import copy from dataclasses import dataclass, field from typing import TYPE_CHECKING, TypeVar from osekit.utils.timestamp import localize_timestamp if TYPE_CHECKING: from pandas import Timedelta, Timestamp @dataclass class Event: """Even...
Project-OSmOSE/OSEkit
src/osekit/core/event.py
.py
c2a31dfb4080522b
7.57
13
"""Custom frequency scales for plotting spectrograms. The custom scale is formed from a list of ``ScaleParts``, which assign a frequency range to a range on the scale. Provided ``ScaleParts`` should cover the whole scale (from 0% to 100%). Such Scale can then be passed to the ``SpectroData.plot()`` method for the spe...
Project-OSmOSE/OSEkit
src/osekit/core/frequency_scale.py
.py
e8ae2c4821add473
7.57
13
"""The instrument class represent the audio acquisition chain. It embeds the technical properties of the hydrophone, the gain applied to the measured signal etc. """ from __future__ import annotations import numpy as np class Instrument: """Represent the audio acquisition chain. It embeds the technical pr...
Project-OSmOSE/OSEkit
src/osekit/core/instrument.py
.py
1f7feb910976d43b
7.57
13
"""Functions used to serialize the API objects to json files.""" import json import os from pathlib import Path, PurePosixPath, PureWindowsPath # noqa: F401 from typing import Literal from osekit.utils.path import is_absolute def absolute_to_relative( target_path: os.PathLike | str, root_path: os.PathLike ...
Project-OSmOSE/OSEkit
src/osekit/core/json_serializer.py
.py
f66c1053af08e6b8
7.57
13
"""LTASData is a special form of SpectroData. The Sx values from a ``LTASData`` object are computed recursively. LTAS should be preferred in cases where the audio is really long. In that case, the corresponding number of time bins (``scipy.ShortTimeFTT.p_nums``) is too long for the whole Sx spectrum to be computed onc...
Project-OSmOSE/OSEkit
src/osekit/core/ltas_data.py
.py
af0abf9c6af5fc40
7.57
13
"""``LTASDataset`` is a collection of ``LTASData`` objects. ``LTASDataset`` is a collection of ``LTASData``, with methods that simplify repeated operations on the ``LTASData``. """ from __future__ import annotations from pathlib import Path from typing import TYPE_CHECKING from scipy.signal import ShortTimeFFT fro...
Project-OSmOSE/OSEkit
src/osekit/core/ltas_dataset.py
.py
c2af954acadc16ae
7.57
13
"""Spectro file associated with timestamps. Spectro files are ``npz`` files with ``Time`` and ``Sxx`` arrays. Metadata (``time_resolution``) are stored as separate arrays. """ from __future__ import annotations import typing from typing import TYPE_CHECKING import numpy as np from pandas import Timestamp from scipy...
Project-OSmOSE/OSEkit
src/osekit/core/spectro_file.py
.py
ce9cf63590fae6d6
8.07
13
"""``SpectroItem`` corresponding to a portion of a ``SpectroFile`` object.""" from __future__ import annotations from typing import TYPE_CHECKING import numpy as np from osekit.core.base_item import BaseItem from osekit.core.spectro_file import SpectroFile if TYPE_CHECKING: from pandas import Timedelta, Timest...
Project-OSmOSE/OSEkit
src/osekit/core/spectro_item.py
.py
f4a3b54629d7edf3
8.07
13
"""Logging context used by util functions, settable using a context manager. The OSmOSE package instantiates a LoggingContext on initialize in the config module. Utils functions log records to this ``LoggingContext.logger`` logger. The global logger can be replaced with a context manager: >>> from osekit.config impor...
Project-OSmOSE/OSEkit
src/osekit/logging_context.py
.py
fb11f2e2432a6329
7.57
13
from __future__ import annotations from enum import Flag, auto from typing import TYPE_CHECKING, Literal from osekit.utils.audio import Butterworth, Normalization if TYPE_CHECKING: from pandas import Timedelta, Timestamp from scipy.signal import ShortTimeFFT from osekit.core.frequency_scale import Scale...
Project-OSmOSE/OSEkit
src/osekit/public/transform.py
.py
802b32aefe56bed0
7.57
13
from __future__ import annotations import dataclasses import enum from collections.abc import Iterable from typing import Literal, Self import numpy as np import soxr from pandas import Timedelta from scipy import signal from osekit.config import ( resample_quality_settings, ) def generate_sample_audio( nb...
Project-OSmOSE/OSEkit
src/osekit/utils/audio.py
.py
dcdf3d2b7efdc1c8
7.57
13
"""The job module provides classes that run transforms on a remote server. If a ``JobBuilder`` is attached to a Public API ``Project``, the transforms will run through jobs, with writting/submitting of ``pbs`` files. """ from __future__ import annotations import subprocess from dataclasses import dataclass from enu...
Project-OSmOSE/OSEkit
src/osekit/utils/job.py
.py
045950e9cdc24f71
7.57
13
# Copyright The OpenTelemetry Authors # SPDX-License-Identifier: Apache-2.0 import logging import os import sys import traceback import _pytest._code import _pytest.skipping import pytest from opentelemetry import trace from opentelemetry.sdk.resources import SERVICE_NAME, Resource from opentelemetry.sdk.trace import...
kuisathaverat/pytest_otel
src/pytest_otel/__init__.py
.py
ab23fbd873cebed8
7.92
6
import pytest import json import time import os import socket import subprocess SPAN_KIND_INTERNAL = 1 SPAN_KIND_SERVER = 2 STATUS_CODE_OK = 1 STATUS_CODE_ERROR = 2 def is_portListening(host, port): """Check a port in a host is liostening""" a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) l...
kuisathaverat/pytest_otel
tests/it/utils/__init__.py
.py
e382465e95f9f3cd
7.92
6
from pathlib import Path from mex.common.assets.base import BaseAssetsConnector from mex.common.settings import BaseSettings class FilesystemAssetsConnector(BaseAssetsConnector): """Filesystem-based implementation of assets connector.""" def __init__(self) -> None: """Create a new connector instance...
robert-koch-institut/mex-common
mex/common/assets/filesystem.py
.py
7f82c483f0654e1f
7.54
11
from typing import TYPE_CHECKING, Final from mex.common.types import AssetsConnectorType if TYPE_CHECKING: from mex.common.assets.base import BaseAssetsConnector _CONNECTOR_REGISTRY: Final[dict[AssetsConnectorType, type["BaseAssetsConnector"]]] = {} def register_assets_connector( key: AssetsConnectorType, ...
robert-koch-institut/mex-common
mex/common/assets/registry.py
.py
fa3513362826fe90
7.54
11
import sys import warnings from bdb import BdbQuit from collections.abc import Callable from functools import partial from traceback import format_exc import click from click import Command, Option from click.exceptions import Abort, Exit from mex.common.connector import CONNECTOR_STORE from mex.common.logging import...
robert-koch-institut/mex-common
mex/common/cli.py
.py
ecd0e18e9f413a64
7.54
11
from abc import ABCMeta, abstractmethod from contextlib import ExitStack, closing from typing import Self, cast, final from mex.common.context import SingletonStore from mex.common.transform import dromedary_to_snake class _ConnectorStore(SingletonStore["BaseConnector"]): """Thin wrapper for storing one singleto...
robert-koch-institut/mex-common
mex/common/connector/base.py
.py
6f64a48eab9f8f3f
7.54
11
import json import time from abc import abstractmethod from collections.abc import Mapping from typing import Any, Literal, cast import backoff import requests from requests import RequestException, Response, codes from requests.exceptions import ( ConnectTimeout, ProxyError, ReadTimeout, SSLError, ) ...
robert-koch-institut/mex-common
mex/common/connector/http.py
.py
e6eb3b6234e23caa
7.54
11
from collections.abc import Callable from mex.common.exceptions import TimedRequestException def bounded_backoff( min_time: float, max_time: float ) -> Callable[[TimedRequestException], int | float]: """Get a function to calculate a bounded backoff time. Args: min_time: Minimum backoff time in s...
robert-koch-institut/mex-common
mex/common/connector/utils.py
.py
4704f3627d5ca1a5
7.54
11
from collections.abc import Iterator from typing import Generic, TypeVar _SingletonT = TypeVar("_SingletonT") class SingletonStore(Generic[_SingletonT]): """Thin wrapper for storing one singleton instance per class. Instances are kept in a plain dict, so a store is shared by all threads that access it a...
robert-koch-institut/mex-common
mex/common/context.py
.py
34509914f49d4fe7
7.54
11
import time from typing import Any, Self from requests.exceptions import RequestException class MExError(Exception): """Base class for generic exceptions.""" def __str__(self) -> str: """Format this exception as a string for logging.""" args = ", ".join(str(a) for a in self.args) or "N/A" ...
robert-koch-institut/mex-common
mex/common/exceptions.py
.py
3a251a8e3c431c4e
7.54
11
from functools import lru_cache from mex.common.backend_api.connector import BackendApiConnector from mex.common.identity.base import BaseProvider from mex.common.identity.models import Identity from mex.common.types import Identifier, MergedPrimarySourceIdentifier IDENTITY_CACHE_SIZE = 5000 class BackendApiIdentit...
robert-koch-institut/mex-common
mex/common/identity/backend_api.py
.py
7c7352e550acec6a
7.54
11
from abc import abstractmethod from mex.common.connector import BaseConnector from mex.common.identity.models import Identity from mex.common.types import AnyMergedIdentifier, MergedPrimarySourceIdentifier class BaseProvider(BaseConnector): """Base class to define the interface of identity providers.""" @ab...
robert-koch-institut/mex-common
mex/common/identity/base.py
.py
e1486b21f29bd03d
7.54
11
import hashlib from mex.common.identity.base import BaseProvider from mex.common.identity.models import Identity from mex.common.models import ( MEX_PRIMARY_SOURCE_IDENTIFIER, MEX_PRIMARY_SOURCE_IDENTIFIER_IN_PRIMARY_SOURCE, MEX_PRIMARY_SOURCE_STABLE_TARGET_ID, ) from mex.common.types import ( AnyMerge...
robert-koch-institut/mex-common
mex/common/identity/memory.py
.py
609c940a577a3a52
7.54
11
from typing import TYPE_CHECKING, Final from mex.common.types import IdentityProvider if TYPE_CHECKING: from mex.common.identity.base import BaseProvider _PROVIDER_REGISTRY: Final[dict[IdentityProvider, type["BaseProvider"]]] = {} def register_provider( key: IdentityProvider, provider_cls: type["BaseProvid...
robert-koch-institut/mex-common
mex/common/identity/registry.py
.py
5f923728d78c6a5f
7.54
11
import re import ssl from functools import lru_cache from typing import Any, cast from urllib.parse import urlsplit import backoff from ldap3 import Connection, Server, Tls from ldap3.core.exceptions import LDAPExceptionError, LDAPSocketSendError from mex.common.connector import BaseConnector from mex.common.exceptio...
robert-koch-institut/mex-common
mex/common/ldap/connector.py
.py
c78060ee4aa19396
7.54
11
from collections import defaultdict from collections.abc import Iterable from mex.common.identity import get_provider from mex.common.ldap.models import LDAPPerson, LDAPPersonWithQuery from mex.common.types import MergedPersonIdentifier, MergedPrimarySourceIdentifier def get_merged_ids_by_employee_ids( persons: ...
robert-koch-institut/mex-common
mex/common/ldap/extract.py
.py
384157eb8db4f320
7.54
11
from typing import Any, Final, Literal, get_args from pydantic import UUID4, TypeAdapter from mex.common.models import BaseModel class LDAPActor(BaseModel): """Model class for generic LDAP accounts.""" objectGUID: UUID4 sAMAccountName: str | None = None mail: list[str] = [] class LDAPPerson(LDAPA...
robert-koch-institut/mex-common
mex/common/ldap/models.py
.py
0afa682d11b40042
7.54
11
import re from collections.abc import Iterable from dataclasses import dataclass from functools import lru_cache from mex.common.ldap.models import ( AnyLDAPActor, LDAPFunctionalAccount, LDAPPerson, LDAPPersonWithQuery, ) from mex.common.logging import logger from mex.common.models import ( Extract...
robert-koch-institut/mex-common
mex/common/ldap/transform.py
.py
ccc59aa87b37f5cf
7.54
11