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 |
|---|---|---|---|---|---|---|
"""Custom assertion helpers for test consistency.
This module provides standardized assertion functions to ensure
consistent validation across all test modules.
"""
import numpy as np
def assert_valid_threshold(
threshold: float | np.ndarray,
n_classes: int | None = None,
allow_infinite_range: bool = Tr... | finite-sample/optimal-classification-cutoffs | tests/fixtures/assertions.py | .py | 8bfc4950af2e9627 | 8.04 | 11 |
"""Common test data generation utilities.
This module provides standardized data generation functions for consistent
testing across all test modules.
"""
import numpy as np
def generate_binary_data(
n_samples: int = 100,
imbalance_ratio: float = 0.5,
noise: float = 0.1,
random_state: int | None = No... | finite-sample/optimal-classification-cutoffs | tests/fixtures/data_generators.py | .py | 3a6024d50a532485 | 7.04 | 11 |
"""Reusable Hypothesis strategies for comprehensive threshold optimization testing.
This module provides controlled data generation strategies that enable systematic
testing of mathematical properties and edge cases in the optimization algorithms.
"""
from __future__ import annotations
import numpy as np
from hypoth... | finite-sample/optimal-classification-cutoffs | tests/fixtures/hypothesis_strategies.py | .py | 9539d5afad9bea37 | 7.04 | 11 |
"""Test fixtures with realistic datasets for optimal cutoff testing.
This module provides standardized, realistic datasets for testing threshold optimization
algorithms. All datasets use meaningful sample sizes (100+ samples) and realistic
distributions that mirror real-world classification problems.
"""
from typing ... | finite-sample/optimal-classification-cutoffs | tests/fixtures/realistic_datasets.py | .py | a8e4fa5bd13e93c8 | 7.04 | 11 |
"""Integration tests for binary classification workflows.
This module tests end-to-end binary classification scenarios, including
sample weights, comparison operators, and method interactions.
"""
import numpy as np
from optimal_cutoffs import optimize_thresholds
from optimal_cutoffs.cv import cross_validate
from op... | finite-sample/optimal-classification-cutoffs | tests/integration/test_binary_classification.py | .py | 7d317e32a093d699 | 7.04 | 11 |
"""prometheus_api.
This library implements endpoint wrappers for the prometheus-api interface. The prometheus-api interface is used to
transfer information about an instance of Prometheus, such as how to access and uniquely identify it. Typically, this is
useful for charms that operate a Prometheus instance to give ... | canonical/prometheus-k8s-operator | lib/charms/mimir_coordinator_k8s/v0/prometheus_api.py | .py | 734f0630f80561fd | 7.66 | 20 |
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
"""Helper for interacting with Prometheus throughout the charm's lifecycle."""
import logging
from typing import Union
import requests
from requests.exceptions import ConnectionError, ConnectTimeout, ReadTimeout
logger = logging.getLogger(__n... | canonical/prometheus-k8s-operator | src/prometheus_client.py | .py | 89c2b77b1cf19d79 | 7.66 | 20 |
#!/usr/bin/env python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
import functools
import logging
import os
import shutil
from collections import defaultdict
from datetime import datetime
from pathlib import Path
import jubilant
import pytest
logger = logging.getLogger(__name__)
clas... | canonical/prometheus-k8s-operator | tests/integration/conftest.py | .py | 516f7db00bd38c4f | 8.16 | 20 |
#!/usr/bin/env python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
import grp
import json
import logging
import subprocess
from pathlib import Path
from typing import List
import requests
import yaml
from juju.application import Application
from juju.unit import Unit
from lightkube impor... | canonical/prometheus-k8s-operator | tests/integration/helpers.py | .py | 13c068cec674738a | 8.16 | 20 |
# Copyright 2022 Canonical Ltd.
# See LICENSE file for licensing details.
"""## Overview.
This document explains how to use the `JujuTopology` class to
create and consume topology information from Juju in a consistent manner.
The goal of the Juju topology is to uniquely identify a piece
of software running across any... | canonical/prometheus-k8s-operator | tests/integration/prometheus-tester/lib/charms/observability_libs/v0/juju_topology.py | .py | 374b2bac3def408e | 8.16 | 20 |
#!/usr/bin/env python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
"""A Charm to functionally test the Prometheus Operator."""
import json
import logging
from pathlib import Path
from charms.prometheus_k8s.v0.prometheus_scrape import MetricsEndpointProvider
from ops.charm import CharmBa... | canonical/prometheus-k8s-operator | tests/integration/prometheus-tester/src/charm.py | .py | f3d797f16c048048 | 8.16 | 20 |
#!/usr/bin/env python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
import random
import time
from prometheus_client import Summary, start_http_server
# Metric that tracks time spent and number of requests made.
REQUEST_TIME = Summary("request_processing_seconds", "Time spent processing ... | canonical/prometheus-k8s-operator | tests/integration/prometheus-tester/src/metrics.py | .py | 45bf4dfa4b6a8c2e | 8.16 | 20 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
import logging
from pathlib import Path
import jubilant
import pytest
import yaml
from helpers import oci_image, push_to_otelcol, query_exemplars
# from minio import Minio
logger = logging.getLogger(__name__)
METADATA =... | canonical/prometheus-k8s-operator | tests/integration/test_exemplars.py | .py | 48fc69092bc52698 | 7.16 | 20 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Integration tests for the logging (log forwarding) relation."""
import logging
from pathlib import Path
import jubilant
import pytest
import requests
import yaml
from helpers import oci_image
from tenacity import retr... | canonical/prometheus-k8s-operator | tests/integration/test_logging.py | .py | fa7e80640c4063e8 | 8.16 | 20 |
"""Feature: Prometheus can form TLS connections with HTTPS servers."""
import json
import logging
import time
import jubilant
from helpers import oci_image
from requests import request
from tenacity import retry, stop_after_delay, wait_fixed
logger = logging.getLogger(__name__)
PROMETHEUS_RESOURCES = {"prometheus-... | canonical/prometheus-k8s-operator | tests/integration/test_receive_ca_cert.py | .py | 5c75605af06bd9a8 | 8.16 | 20 |
#!/usr/bin/env python3
# Copyright 2022 Canonical Ltd.
# See LICENSE file for licensing details.
"""This test module tests prometheus resource limits on startup and after config-changed."""
import json
import logging
import subprocess
from pathlib import Path
import jubilant
import pytest
import requests
import yaml... | canonical/prometheus-k8s-operator | tests/integration/test_resource_limits.py | .py | 99912f1efb273b25 | 8.16 | 20 |
#!/usr/bin/env python3
# Copyright 2022 Canonical Ltd.
# See LICENSE file for licensing details.
import asyncio
import logging
import pytest
import yaml
from cosl.rules import generic_alert_groups
from helpers import (
check_prometheus_is_ready,
get_prometheus_rules,
get_rules_for,
get_workload_file,
... | canonical/prometheus-k8s-operator | tests/integration/test_upgrade_charm.py | .py | 7fffb5d07ff17e46 | 7.16 | 20 |
import json
import logging
from charms.prometheus_k8s.v1.prometheus_remote_write import (
PrometheusRemoteWriteConsumer,
)
from cosl.rules import HOST_METRICS_MISSING_RULE_NAME
from helpers import (
UNITTEST_DIR,
patch_cos_tool_path,
)
from ops.charm import CharmBase
from scenario import Context, PeerRelat... | canonical/prometheus-k8s-operator | tests/unit/test_absent_alert_duplicated_for_remote_writer.py | .py | 1189238c43b0b7e0 | 7.16 | 20 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
import dataclasses
import json
import yaml
from ops.model import ActiveStatus, BlockedStatus
from scenario import Relation, State
from charm import to_status
# To test that valid rules are written to disk and invalid rules are filtered out,
... | canonical/prometheus-k8s-operator | tests/unit/test_alert_rule_filtering.py | .py | 7c9ccd876e707b46 | 7.16 | 20 |
#!/usr/bin/env python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
import datetime
import logging
import unittest
from unittest.mock import Mock, patch
import ops
from helpers import k8s_resource_multipatch, prom_multipatch
from ops.model import ActiveStatus, BlockedStatus
from ops.pebbl... | canonical/prometheus-k8s-operator | tests/unit/test_charm_status.py | .py | e266b434d37cc4ec | 8.16 | 20 |
import pytest
from scenario import Container, Context, Exec, State
from charm import PROMETHEUS_CONFIG
def test_default_config_doesnt_enable_exemplars(context: Context):
# WHEN any event happens on prometheus with a default config
container = Container(
"prometheus",
can_connect=True,
... | canonical/prometheus-k8s-operator | tests/unit/test_exemplars.py | .py | 50cc1e1eb5405858 | 7.16 | 20 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import base64
import http.cookiejar
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
jenkins_host_name = sys.argv[1]
jenkins_port = sys.argv[2]
JENKINS_SERVER_URL ... | Juniper/nita-webapp | build-and-test-webapp/add_jenkins_job.py | .py | 85b88c1543c3b42e | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Configure Jenkins global settings required for NITA operation.
Usage: python configure_jenkins.py <host> <port>
Sets the Jenkins URL so that jenkins-cli.jar can authenticate and create jobs.
Without the Je... | Juniper/nita-webapp | build-and-test-webapp/configure_jenkins.py | .py | d9fd45c7f775303e | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from ngcn.models import (
Action,
ActionCategory,
ActionHistory,
CampusNetwork,
CampusTyp... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/admin.py | .py | ea5703ec9b7cdafa | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Custom DRF authentication for NITA.
DRF's SessionAuthentication.enforce_csrf() hard-codes CsrfViewMiddleware for
its internal CSRF check, bypassing the project's LabCsrfMiddleware (which
accepts any Origin/... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/api/authentication.py | .py | 274a39edefeb7348 | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Role-based DRF permission classes for the NITA Webapp API.
Access control is driven by the ``role`` field on the custom user model
(``ngcn.User``): one of ``user``, ``power_user`` or ``admin``. Django's
``i... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/api/permissions.py | .py | 7259bdb35be498eb | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""drf-spectacular post-processing hooks for the generated OpenAPI schema."""
# Upper bound on the number of entries the lifecycle-runs list can return:
# ``LifecycleRunViewSet._MAX_BUILDS`` (50) inspected per... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/api/schema_hooks.py | .py | 146137bf954e74bc | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""DRF ModelSerializer classes for the NITA Webapp REST API.
Each model in ``ngcn.models`` has a corresponding serializer here. Where
useful, read-only computed / nested fields are added so that API consumers... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/api/serializers.py | .py | 12d4538f15c77b89 | 7.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import logging
import os
from django.apps import AppConfig
logger = logging.getLogger(__name__)
def bootstrap_admin_from_env():
"""Create an admin user from ``NITA_BOOTSTRAP_ADMIN_*`` env vars.
Fir... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/apps.py | .py | 516173844c347b40 | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Jenkins server configuration and connection helpers.
Holds the Jenkins connection constants (read from ``server_details.ini`` and the
environment) and the factory for a ``jenkins.Jenkins`` client. Extracted... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/jenkins_config.py | .py | 4fbe0e007cd3b0ae | 7.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Shared helpers for invoking Jenkins jobs and streaming their console output.
This module centralises the authenticated (CSRF-crumbed) Jenkins build
invocation and the Server-Sent-Events console stream gener... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/jenkins_jobs.py | .py | 501223219e7f31a2 | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Django management command: create (or update) the initial admin user.
Usage
-----
manage.py create_admin --username admin --email admin@example.com --password secret
Behaviour
---------
* Creates a use... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/management/commands/create_admin.py | .py | 34d49d25cefb3250 | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Drop the Role, Resource, and their CampusType M2M join tables.
These tables were never populated — the code that would parse roles and
resources from project.yaml was commented out before the feature shippe... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/migrations/0001_remove_roles_resources.py | .py | 1d5cca7f4c318b69 | 7.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Drop the CampusNetwork.dynamic_ansible_workspace column.
The dynamic Ansible workspace is now the permanent, only behaviour: the
build directory is always set to ``/var/tmp/build/<type>-<network>`` at
trigg... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/migrations/0002_remove_dynamic_ansible_workspace.py | .py | 34d44b9801dece68 | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Add the LifecycleRun table for network lifecycle job history."""
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("ngcn", "0002_remove_dynamic... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/migrations/0003_lifecyclerun.py | .py | b4213934bc33ee48 | 7.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Add ownership/curation fields.
* ``CampusNetwork.owner`` (PROTECT) and ``CampusNetwork.team`` (SET_NULL)
* ``CampusType.created_by`` (SET_NULL)
A data migration assigns any pre-existing (orphaned) networks... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/migrations/0006_network_ownership.py | .py | 0b309ff7bfee39a2 | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext as _
# Create your models here.
class User(Abstr... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/models.py | .py | 2498db9bbc59081f | 7.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
import logging
from ngcn.statusupdater import StatusUpdater
logger = logging.getLogger(__name__)... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/servicestartupmiddleware.py | .py | 34b23259ed380b7a | 7.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Workbook / spreadsheet business logic shared by the API layer.
Contains the workbook parsing, generation and persistence helpers plus the
``GridDataManager`` that were previously defined in the legacy ``ngc... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn/workbook.py | .py | 897447f6844e9b76 | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Custom CSRF middleware for NITA.
NITA is a private lab tool that may be accessed through arbitrary hosts,
IP addresses, or port-forwarding tunnels (e.g. VS Code remote, kubectl
port-forward, or SSH tunnels)... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn_workbench/csrf.py | .py | ba5bf51deb0737fa | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import os
from django.conf import settings
from django.contrib import admin
from django.http import HttpResponse
from django.urls import include, path, re_path
from drf_spectacular.views import SpectacularAPIV... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/ngcn_workbench/urls.py | .py | 4f029206a52ae0ce | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""pytest fixtures shared across the entire NITA Webapp test suite."""
import pytest
from django.contrib.auth import get_user_model
from ngcn.models import (
Action,
ActionCategory,
ActionProperty,... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/tests/conftest.py | .py | 332c3defaaff7104 | 8.07 | 13 |
# Copyright (c) Hewlett Packard Enterprise, 2026. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Migration-integrity tests.
The main test suite runs with ``MIGRATION_MODULES = {"ngcn": None}`` (see
``ngcn_workbench.test_settings``), which builds the schema directly from the
models and therefore never e... | Juniper/nita-webapp | build-and-test-webapp/nita-webapp/ngcn_workbench/tests/test_migrations.py | .py | 2e1844babfd1dc1e | 8.07 | 13 |
#!/usr/bin/env python
"""Command-line interface for gitlab-backup."""
import collections
import logging
import os
import sys
import tempfile
from gitlab_backup.gitlab_backup import (
backup_repository,
check_git_install,
check_git_lfs_install,
get_client,
logger,
mkdir_p,
parse_args,
s... | josegonzalez/python-gitlab-backup | gitlab_backup/cli.py | .py | 44ec1f37a21d3b65 | 7.62 | 16 |
"""Shared pytest fixtures for gitlab-backup tests."""
import pytest
from gitlab_backup.gitlab_backup import parse_args
@pytest.fixture
def create_args():
"""Factory fixture that creates args with real CLI defaults.
Uses the actual argument parser so new CLI args are automatically
available with their d... | josegonzalez/python-gitlab-backup | tests/conftest.py | .py | c1d1a6965ac8b272 | 8.12 | 16 |
"""Tests for logging_subprocess pipe handling."""
import logging
import subprocess
import sys
import threading
import pytest
from gitlab_backup import gitlab_backup
def _raise_file_not_found(*_args, **_kwargs):
raise FileNotFoundError(2, "No such file or directory", "git")
class TestLoggingSubprocess:
""... | josegonzalez/python-gitlab-backup | tests/test_logging_subprocess.py | .py | befbee7f2750e8d6 | 7.12 | 16 |
from typing import Any
from .async_connection import AsyncConnection # noqa: F401 re-export
from .connection import Addr
from .errors import CasMismatchError, MemcacheError
from .experiment._core import WireOp, settle
from .experiment.async_client import AsyncMemcache as _ScenarioAsyncMemcache
from .experiment.meta_a... | aisk/python-memcache | memcache/async_memcache.py | .py | 0899b7d2b50d4322 | 7.52 | 10 |
import socket
from typing import TypeAlias
from .errors import MemcacheError, PipelineError
from .meta_command import MetaCommand, MetaResult, ResponseReader
NEWLINE = b"\r\n"
RECV_SIZE = 65536
Addr: TypeAlias = tuple[str, int]
MAX_PIPELINE_CHUNK_BYTES = 512 * 1024
"""How many request bytes may be in flight before... | aisk/python-memcache | memcache/connection.py | .py | 38a5823e6b9a3ca1 | 7.52 | 10 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from .meta_command import MetaResult
class MemcacheError(Exception):
pass
class SerializeError(MemcacheError):
pass
class CasMismatchError(MemcacheError):
"""The item changed since it was read; re-read and... | aisk/python-memcache | memcache/errors.py | .py | 6c223d91f8f0691b | 7.52 | 10 |
"""Typed 1:1 mapping of the memcached meta protocol.
This module builds wire commands (mg/ms/md/ma/me) from named arguments and
parses wire responses into :class:`MetaCommandResult`. Every keyword argument
corresponds to exactly one protocol flag. This layer performs no
serialization and no semantic interpretation of ... | aisk/python-memcache | memcache/experiment/meta_api.py | .py | dd1839d0ee24e644 | 7.52 | 10 |
from typing import Any
from .connection import Addr, Connection # noqa: F401 re-export for backward compat
from .errors import CasMismatchError, MemcacheError
from .experiment._core import WireOp, settle
from .experiment.client import Memcache as _ScenarioMemcache
from .experiment.meta_api import MetaCommandResult, b... | aisk/python-memcache | memcache/memcache.py | .py | 2336a073a2101a13 | 7.52 | 10 |
import base64
from dataclasses import dataclass
from .errors import MemcacheError
# memcached limits the key token *on the wire* to 250 bytes and the legacy
# text key may not contain whitespace or control characters. Keys that violate
# the latter are sent base64-encoded with the meta ``b`` flag; since the server
# ... | aisk/python-memcache | memcache/meta_command.py | .py | aa7d9c657d2ce8cd | 7.52 | 10 |
import bz2
import gzip
import json
import lzma
import pickle
import sys
import zlib
from typing import Any, Protocol
from collections.abc import Callable
from .errors import SerializeError
FLAG_BYTES = 0
FLAG_PICKLE = 1 << 0
FLAG_INT = 1 << 1
FLAG_COMPRESSED = 1 << 3
FLAG_STR = 1 << 4
FLAG_JSON = 1 << 5
class Seria... | aisk/python-memcache | memcache/serialize.py | .py | 7bcfe1d4e0b17b0b | 7.52 | 10 |
import pytest
import trio
import memcache
@pytest.fixture()
def client():
return memcache.AsyncMemcache(("localhost", 11211))
@pytest.mark.trio
async def test_trio_connection(client):
"""Test basic trio connection functionality."""
# Test basic set/get operations
await client.set("trio_test", "tri... | aisk/python-memcache | tests/test_trio_client.py | .py | 3ef520823fa4f58e | 7.02 | 10 |
"""igvm - Color output helpers
Copyright (c) 2026 InnoGames GmbH
Replacement for fabric.colors which is not available in fabric 3.x.
"""
def _wrap(code: int, text: str, bold: bool = False) -> str:
if bold:
return f'\033[1;{code}m{text}\033[0m'
return f'\033[{code}m{text}\033[0m'
def green(text: st... | innogames/igvm | igvm/colors.py | .py | 5f4971bc731f5064 | 7.59 | 14 |
"""igvm - DRBD Transport Internals
Copyright (c) 2018 InnoGames GmbH
"""
from contextlib import contextmanager
from igvm.exceptions import RemoteCommandError
from igvm.settings import DEFAULT_VG_NAME
from io import BytesIO
from logging import getLogger
from time import sleep
from tqdm import tqdm
from typing import T... | innogames/igvm | igvm/drbd.py | .py | e92c799909ed7a6e | 7.59 | 14 |
"""igvm - Host Model
Copyright (c) 2018 InnoGames GmbH
"""
import logging
import shlex
import socket
from datetime import datetime, timezone
from io import BytesIO
from uuid import uuid4
import paramiko.ssh_exception
from igvm.exceptions import RemoteCommandError, InvalidStateError
from igvm.fabric_compat import (
... | innogames/igvm | igvm/host.py | .py | 7cf81bc40c13c41e | 7.59 | 14 |
"""igvm - Hypervisor Selection Preferences
This module contains preference classes to select Hypervisors. Preferences
return either a score of range 0.0 - 1.0 inclusive, or a boolean value, which
is only there for convenience and converts to float.
A higher score means that a Hypervisor should be favored, while a low ... | innogames/igvm | igvm/hypervisor_preferences.py | .py | e54a0c839d0137bd | 7.59 | 14 |
"""igvm - KVM Utilities
Copyright (c) 2018 InnoGames GmbH
"""
import logging
import re
import time
from uuid import uuid4
from xml.dom import minidom
from xml.etree import ElementTree
from jinja2 import Environment, PackageLoader
from libvirt import (
VIR_DOMAIN_VCPU_MAXIMUM,
VIR_DOMAIN_AFFECT_LIVE,
VIR_... | innogames/igvm | igvm/kvm.py | .py | 12227efbbbf0e551 | 7.59 | 14 |
"""igvm - Puppet interaction class
Copyright (c) 2020 InnoGames GmbH
"""
import random
import socket
from logging import getLogger
from time import sleep
import paramiko.ssh_exception
from adminapi.dataset import Query, DatasetObject
from igvm.exceptions import ConfigError
from igvm.fabric_compat import Connection... | innogames/igvm | igvm/puppet.py | .py | 64f8a9e2f563c54d | 7.59 | 14 |
"""igvm - Transaction System
Copyright (c) 2018 InnoGames GmbH
"""
import logging
log = logging.getLogger(__name__)
class Transaction(object):
"""Context manager of an igvm action with rollback support
Each successful step register a callback to undo its changes.
If the transaction fails, all register... | innogames/igvm | igvm/transaction.py | .py | b707c1da3314f958 | 7.59 | 14 |
"""igvm - Utilities
Copyright (c) 2018 InnoGames GmbH
"""
from __future__ import division
import ipaddress
import logging
import socket
import time
from concurrent import futures
from os import path
from paramiko import SSHConfig
from igvm.exceptions import TimeoutError
_SIZE_FACTORS = {
'T': 1024 ** 4,
... | innogames/igvm | igvm/utils.py | .py | 2e2f9a22fc0ccf46 | 7.59 | 14 |
"""Integration to access ebusd daemon (service for communication with e.g. eBUS heating systems)."""
"""ebusd: https://github.com/john30/ebusd"""
import logging
import threading
from typing import Final
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_... | Berlenz/Home-Assistant-eBUS | custom_components/ebus/__init__.py | .py | e6687d35d4f93464 | 7.48 | 8 |
"""Config flow for the eBUS integration."""
from __future__ import annotations
import logging
import re
import socket
import voluptuous as vol
import yaml
from homeassistant import config_entries
from homeassistant.const import CONF_PORT
from homeassistant.core import callback
from homeassistant.helpers.selector im... | Berlenz/Home-Assistant-eBUS | custom_components/ebus/config_flow.py | .py | 70c247f5dc0cc3b8 | 7.48 | 8 |
"""Support for eBUS sensors."""
import logging
import re
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.components.sensor import (
DEVICE_CLASSES_SCHEMA,
STATE_CLASSES_SCHEMA,
CONF_STATE_CLASS,
PLATFORM_SCHEMA,
RestoreSensor,
)
from homeassistant.c... | Berlenz/Home-Assistant-eBUS | custom_components/ebus/sensor.py | .py | 48550a2cc9f69412 | 7.48 | 8 |
import datetime
from decimal import Decimal
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.urls import reverse, reve... | PetrDlouhy/django-plans-payments | plans_payments/views.py | .py | 21f3a80da4bf9fe5 | 7.59 | 14 |
from datetime import timedelta
from unittest import mock
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from model_bakery import baker
from payments import PaymentStatus, RedirectNeeded
from plans_payments.models import Payment
from plans_payments... | PetrDlouhy/django-plans-payments | tests/test_views.py | .py | e52c48b8365f4dfe | 7.09 | 14 |
# -*- coding: utf-8 -*-
__author__ = "Konstantin Klementiev"
__date__ = "19 Dec 2024"
# !!! SEE CODERULES.TXT !!!
import os
import itertools
from .logger import syslogger
MAX_HEADER_LINES = 256
MIME_TYPE_DATA = 'parseq-data-model-items'
MIME_TYPE_TEXT = 'text/uri-list'
MIME_TYPE_HDF5 = 'parseq-hdf5-model-items'
(DAT... | kklmn/ParSeq | parseq/core/commons.py | .py | 54d0e5e30817fbe6 | 7.48 | 8 |
# -*- coding: utf-8 -*-
u"""
Data nodes
----------
Data nodes are intermediate stops along the data pipeline. Their main purposes
are to visualize data, display transformation status, select parameters of data
transformations, possibly stop or split data propagation or combine with other
data. Each data node defines a... | kklmn/ParSeq | parseq/core/nodes.py | .py | 59999d4597890882 | 7.48 | 8 |
# -*- coding: utf-8 -*-
__author__ = "Konstantin Klementiev"
__date__ = "16 Feb 2019"
# !!! SEE CODERULES.TXT !!!
import os
import numpy as np
from silx.gui import qt
from silx.gui import plot as splot
from silx.gui.plot.actions.control import ZoomBackAction, CrosshairAction
try:
from silx.gui.plot.tools.menus im... | kklmn/ParSeq | parseq/gui/plot.py | .py | 723c391a5b2a7857 | 7.48 | 8 |
# -*- coding: utf-8 -*-
__author__ = "Konstantin Klementiev"
__date__ = "17 Nov 2018"
# !!! SEE CODERULES.TXT !!!
import reprlib
from ..core import singletons as csi
from ..core import spectra as csp
from ..core import commons as cco
class FloatRepr(reprlib.Repr):
def repr_float(self, value, level):
ret... | kklmn/ParSeq | parseq/gui/undoredo.py | .py | 7e8e425eca9ded75 | 7.48 | 8 |
"""
Sample module for demonstrating autodoc functionality.
This module provides a simple database connection class and utility functions
for demonstrating how API documentation is generated with sphinx.ext.autodoc.
"""
class DatabaseConnection:
"""
Manages connections to a database.
This class provides ... | scylladb/sphinx-scylladb-theme | docs/source/examples/_sample_module.py | .py | 26f5a2ac7b7a64de | 7.57 | 13 |
# -*- coding: utf-8 -*-
import argparse
import contextlib
import itertools
import json
import logging
import multiprocessing
import os
import pathlib
import re
import shlex
import shutil
import string
import subprocess
import sys
import tempfile
import sphinx as _sphinx
from sphinx import config as sphinx_config
from ... | scylladb/sphinx-scylladb-theme | extensions/sphinx-multiversion/sphinx_multiversion/main.py | .py | 6a027d6503d740dc | 7.57 | 13 |
from os import getenv, path
import sphinx_collapse
import sphinx_copybutton
import sphinx_substitution_extensions
from notfound import extension as not_found
from sphinx_tabs import tabs
from sphinxcontrib import mermaid
from sphinx_scylladb_theme._version import version
from sphinx_scylladb_theme.extensions import (... | scylladb/sphinx-scylladb-theme | sphinx_scylladb_theme/__init__.py | .py | 925872890b61b055 | 7.57 | 13 |
"""
Sphinx directive for HTML alert components with target option.
"""
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from .utils import generate_template, resolve_link
class Alert(Directive):
has_content = True
option_spec = {
"link": directives.unchanged_required... | scylladb/sphinx-scylladb-theme | sphinx_scylladb_theme/extensions/alerts.py | .py | be4d3cad678b81eb | 7.57 | 13 |
"""
Sphinx directive for HTML Grid Components.
"""
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from .utils import generate_template
class Grid(Directive):
has_content = True
option_spec = {
"class": directives.unchanged,
"type": directives.unchanged, # ... | scylladb/sphinx-scylladb-theme | sphinx_scylladb_theme/extensions/grid.py | .py | b084eeca7a7ae6ae | 7.57 | 13 |
"""
Extension for Sphinx that generates a navigation tree with dropdowns
from Sphinx's toctree function's output.
Adapted from https://github.com/pradyunsg/furo
(Copyright (c) 2020 Pradyun Gedam, MIT License)
for sphinx-scylladb-theme.
"""
import functools
from bs4 import BeautifulSoup
@functools.lru_cache(maxsiz... | scylladb/sphinx-scylladb-theme | sphinx_scylladb_theme/extensions/navigation.py | .py | 4c9a1e8b189213a4 | 7.57 | 13 |
"""
Sphinx directive for HTML Panel Box Components.
"""
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from .utils import generate_template
class PanelBox(Directive):
has_content = True
option_spec = {
"title": directives.unchanged_required,
"class": direct... | scylladb/sphinx-scylladb-theme | sphinx_scylladb_theme/extensions/panel_box.py | .py | 9f2472b173d9af5e | 7.57 | 13 |
"""
Sphinx directive for HTML Topic Box Components.
"""
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from .utils import generate_template, is_url, resolve_link
class TopicBox(Directive):
has_content = True
option_spec = {
"title": directives.unchanged_required,
... | scylladb/sphinx-scylladb-theme | sphinx_scylladb_theme/extensions/topic_box.py | .py | 6f9ad80ed3794bfb | 7.57 | 13 |
import os
import shutil
from urllib.parse import urlparse
def generate_template(template, **vars):
"""
Replaces variables inside a template.
:param template: Text with variables between brackets {}.
:type src: str
"""
return template.format(**vars)
def copy(src, dest):
"""
Copies a... | scylladb/sphinx-scylladb-theme | sphinx_scylladb_theme/extensions/utils.py | .py | 469690ef483c7c9c | 7.57 | 13 |
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# L... | scylladb/sphinx-scylladb-theme | sphinx_scylladb_theme/lexers/cql.py | .py | 6faa1015d747abaa | 7.57 | 13 |
import requests
def multiversion_regex_builder(versions):
"""Generates a regex string from a list of versions.
Every documentation project `conf.py` file uses this function
to define the different documentation versions supported.
:param versions: A list of versions. Versions could be either branch ... | scylladb/sphinx-scylladb-theme | sphinx_scylladb_theme/utils.py | .py | dd7b80dab08802f3 | 7.57 | 13 |
from __future__ import annotations
import warnings
from abc import ABC, abstractmethod
from collections.abc import Sequence
from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable, Generic, Protocol, TypeVar
import numpy as np
from numpy.typing import ArrayLike
from scipy import stats
from scipy.... | OpheliaMiralles/pykelihood | pykelihood/distributions/base.py | .py | 151cae573d75ad78 | 7.56 | 12 |
from __future__ import annotations
import abc
import inspect
import operator
from collections.abc import Callable, Collection, Hashable, Iterator, Mapping, Sequence
from functools import wraps
from typing import Any, Generic, TypeVar
import numpy as np
import numpy.typing as npt
from typing_extensions import Self
fr... | OpheliaMiralles/pykelihood | pykelihood/effects.py | .py | 7b77471027ac3765 | 7.56 | 12 |
from __future__ import annotations
import warnings
from functools import cached_property
from itertools import count
from typing import Callable
import numpy as np
import pandas as pd
from scipy.optimize import brentq
from scipy.stats import chi2
from pykelihood.distributions import Distribution
from pykelihood.metr... | OpheliaMiralles/pykelihood | pykelihood/profiler.py | .py | f90d2b118b0c8310 | 7.56 | 12 |
from typing import Optional, TypeVar
T = TypeVar("T")
def ifnone(x: Optional[T], default: T) -> T:
"""
Return `default` if `x` is None, otherwise return `x`.
Parameters
----------
x : Optional[T]
The value to check.
default : T
The default value to return if `x` is None.
... | OpheliaMiralles/pykelihood | pykelihood/utils.py | .py | 0f117636e0637877 | 7.56 | 12 |
from functools import partial
import numpy as np
import pytest
from pytest import approx
from scipy.stats import norm
from pykelihood import kernels
from pykelihood.distributions import GEV, GPD, Normal
from pykelihood.metrics import (
Brier_score,
crps,
log_likelihood,
opposite_log_likelihood,
pp... | OpheliaMiralles/pykelihood | tests/test_metrics.py | .py | 407630843435d28e | 8.06 | 12 |
from abc import ABC, abstractmethod
BACKEND_REGISTRY: dict[str, type["Limiter"]] = {}
class LimiterException(Exception):
pass
class Limiter(ABC):
def __init_subclass__(cls, name: str | None = None, **kwargs) -> None:
super().__init_subclass__(**kwargs)
if name:
BACKEND_REGISTR... | tabotkevin/flask_limit | src/flask_limit/limiters/base.py | .py | 6c3c9badcaf2eaac | 7.5 | 9 |
from threading import RLock
from time import time
from .base import Limiter
class MemRateLimiter(Limiter, name="memory"):
"""Rate limiter backed by process-local memory.
This backend is thread-safe within a single Python process.
It is not shared between multiple processes or application instances.
... | tabotkevin/flask_limit | src/flask_limit/limiters/memory.py | .py | 116bf73e3e608d17 | 7.5 | 9 |
def get_fahrenheit():
'''
Hämtar antal fahrenheit från användaren
Returns:
float : Antal grader i fahrenheit
'''
while True:
try:
fahrenheit = float(input('Antal grader i fahrenheit: '))
return fahrenheit
except:
print("Du måste mata in si... | mau-webb/mau-webb.github.io | resurser/da354a-ht21/5-fil-och-felhantering/ex-solutions/Ö2.2.py | .py | 334ecf26d60de14b | 7.52 | 10 |
def main():
'''
Huvudfunktionen i programmet som hantera välkomnande av användaren,
inläsning av filmer från vår textfil "movies.text" samt menyn i programmet.
'''
# 1. Skriva ut en välkomstfras
welcome()
# 2. Läsa in alla filmer från en text-fil
movies = read_movies_from_file("movies.t... | mau-webb/mau-webb.github.io | resurser/da354a-ht21/5-fil-och-felhantering/ex-solutions/Ö3.py | .py | 0194ebeb5c4233af | 7.52 | 10 |
def calculate_grade(points):
'''
Funktionen beräknar och returnerar betyget baserat på poängsumman
'''
if points >= 90:
return "A"
elif points >= 80:
return "B"
elif points >= 70:
return "C"
elif points >= 60:
return "D"
elif points >= 50:
return "... | mau-webb/mau-webb.github.io | resurser/da354a-ht22/3-iteration-och-selektion/ex-solutions/Ö1.3.py | .py | 9de02854d2753872 | 7.52 | 10 |
def get_fahrenheit():
'''
Hämtar antal fahrenheit från användaren
Returns:
float : Antal grader i fahrenheit
'''
while True:
try:
fahrenheit = float(input('Antal grader i fahrenheit: '))
return fahrenheit
except:
print("Du måste mata in si... | mau-webb/mau-webb.github.io | resurser/da354a-ht22/5-fil-och-felhantering/ex-solutions/Ö2.2.py | .py | 051fd0ec045eeb15 | 7.52 | 10 |
def divide_numbers(numerator, denominator):
'''
Funktionen delar två tal och returnerar resultatet
'''
while True:
try:
result = numerator / denominator
return result
except ZeroDivisionError:
print("Du kan inte dela med noll. Försök igen.")
... | mau-webb/mau-webb.github.io | resurser/da354a-ht22/5-fil-och-felhantering/ex-solutions/Ö2.3.py | .py | 19a8570055745bc2 | 7.52 | 10 |
def add_numbers(num_1, num_2):
"""
Adderar två tal och returnerar resultatet.
Parametrar:
num_1 (str): Det första talet.
num_2 (str): Det andra talet.
Returnerar:
int: Resultatet av additionen om allt går bra.
None: Om inmatningen inte är giltig.
"""
try:
result = int(n... | mau-webb/mau-webb.github.io | resurser/da354a-ht22/5-fil-och-felhantering/ex-solutions/Ö2.4.py | .py | 0cc6426c0a9f0e16 | 7.52 | 10 |
def calculate_time(hours, minutes):
"""
Räknar ut rätt tid utifrån antal timmar och minuter.
Parametrar:
hours (str): Antal timmar.
minutes (str): Antal minuter.
Returnerar:
tuple: Ett tupel med antal timmar och minuter om allt går bra.
None: Om något går fel och tiden är försvunnen i ... | mau-webb/mau-webb.github.io | resurser/da354a-ht22/5-fil-och-felhantering/ex-solutions/Ö2.5.py | .py | d279d8e21a078f6c | 7.52 | 10 |
"""
# Careless responding walkthrough
This notebook-style script mirrors a typical analysis path:
1. Simulate attentive vs careless respondents
2. Screen with multiple indices
3. Inspect multi-index agreement
4. Form a composite ranking
Run with:
```bash
uv run python examples/careless_responding_walkthrough.py
```... | Cameron-Lyons/ier | examples/careless_responding_walkthrough.py | .py | 1e78d49f9830f8fb | 7.48 | 8 |
"""Shared validation for composite command-line serializers."""
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from collections.abc import Mapping
def validate_composite_components(
n_respondents: int,
component_scores: Mapping[str, np.ndarray]... | Cameron-Lyons/ier | src/ier/_cli_composite.py | .py | 743cad8bb8159b5c | 7.48 | 8 |
"""Shared helpers for percentile/threshold-based flagging."""
from typing import Literal
import numpy as np
def validate_percentile(percentile: float) -> float:
"""Return a finite percentile in ``[0, 100]`` or raise ``ValueError``."""
if isinstance(percentile, bool):
raise ValueError("percentile mus... | Cameron-Lyons/ier | src/ier/_flagging.py | .py | 70d9a7032411d865 | 7.48 | 8 |
"""Bounded reductions for predefined item pairs."""
import warnings
import numpy as np
from ier._row_statistics import row_mean, row_slices
def paired_mean_absolute_difference(
x: np.ndarray,
left_indices: np.ndarray,
right_indices: np.ndarray,
*,
right_reflection: float | None,
ignore_nan:... | Cameron-Lyons/ier | src/ier/_pair_statistics.py | .py | 22cdac021f633a6d | 7.48 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.