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 |
|---|---|---|---|---|---|---|
"""design_matrix: formula -> hierarch column layout.
Contract: the emitted DataFrame has one column per nesting-chain level in
formula order (plus a synthesized replicate index when innermost cells hold
more than one measurement), with the dependent variable last; the treatment's
position in the chain is its position ... | rishi-kulkarni/hierarch | tests/test_design.py | .py | d8c000dbb690d1d5 | 7.98 | 8 |
"""Exact tests equal brute-force enumeration.
With bootstraps=1 the p-value of hypothesis_test is a deterministic function of the
data: it must equal an itertools enumeration of the distinct (stratified) label
orderings scored with an independent transcription of each statistic, for every
`compare` and `alternative`. ... | rishi-kulkarni/hierarch | tests/test_exact_matches_brute_force.py | .py | d226cd23b4054cc5 | 7.98 | 8 |
import math
import unittest
from hierarch import internal_functions
from hierarch.power import DataSimulator
import scipy.stats as stats
import numpy as np
import pandas as pd
class TestNumbaUnique(unittest.TestCase):
def _check_unique(self, data, col, ret):
"""
Check that nb_unique returns the sa... | rishi-kulkarni/hierarch | tests/test_internal_functions.py | .py | d90ec1cc3942348c | 7.98 | 8 |
import subprocess
import sys
def get_diff():
"""
Gets the file diff between the current branch (your branch) and the
main working branch.
"""
subprocess.run(
["git", "fetch", "origin"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
output = [
f"./{... | nationalarchives/ds-wagtail | .github/scripts/check_migrations.py | .py | 11e591e8e2f93fa8 | 7.5 | 9 |
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication, TokenAuthentication
from app.api.models import APIToken
class DummyUser:
"""
A dummy user class to represent token-authenticated requests that are not associated with a specific user account.
This allows u... | nationalarchives/ds-wagtail | app/api/auth.py | .py | 2fc1aabc301e58de | 7.5 | 9 |
import binascii
import os
from django.db import models
class APIToken(models.Model):
"""
A custom API token to enable API tokens
to be generated for services to access the API.
"""
name = models.CharField(max_length=100, unique=True)
key = models.CharField(max_length=40, unique=True)
act... | nationalarchives/ds-wagtail | app/api/models.py | .py | 130d0fa4b433a6e0 | 7.5 | 9 |
from django.test import RequestFactory, TestCase
from rest_framework import exceptions
from app.api.auth import CustomTokenAuthentication, DummyUser
from app.api.models import APIToken
class CustomTokenAuthenticationTests(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.auth = Cus... | nationalarchives/ds-wagtail | app/api/tests/test_auth.py | .py | 293d511130ed7c48 | 7 | 9 |
from io import StringIO
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test import TestCase
from app.api.models import APIToken
class ManageAPITokenCommandCreateTests(TestCase):
def test_create_token_no_name(self):
"""Test creating a new ... | nationalarchives/ds-wagtail | app/api/tests/test_management_commands.py | .py | e2d0c438bc9d39aa | 7 | 9 |
from django.conf import settings
from django.urls import path
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from wagtail.api.v2.serializers import StreamField as StreamFieldSerializer
from wagtail.models import Site
from app.alerts.models import AlertSerializer
from ap... | nationalarchives/ds-wagtail | app/api/urls/globals.py | .py | c50faeca40c17aec | 7.5 | 9 |
import logging
from django.conf import settings
from django.db.models import Q
from django.http import Http404
from django.utils.crypto import constant_time_compare
from rest_framework import status
from rest_framework.response import Response
from wagtail.api.v2.filters import (
AncestorOfFilter,
ChildOfFilte... | nationalarchives/ds-wagtail | app/api/urls/pages.py | .py | 30ae63e9e0329d16 | 7.5 | 9 |
"""Async Typer support for the easyEnergy CLI.
Adaptation of the snippet/code from:
- https://github.com/tiangolo/typer/issues/88#issuecomment-1613013597
- https://github.com/argilla-io/argilla/blob/e77ca86c629a492019f230ac55ebde207b280xc9c/src/argilla/cli/typer_ext.py
"""
# Copyright 2021-present, the Recognai S.L.... | klaasnicolaas/python-easyenergy | src/easyenergy/cli/async_typer.py | .py | e83dd1c950872bae | 7.45 | 7 |
"""Constants for EasyEnergy API client."""
from __future__ import annotations
from enum import StrEnum
from typing import Final
from zoneinfo import ZoneInfo
API_HOST: Final = "price-graph.mijn.easyenergy.com"
API_PATH: Final = "/api/"
MARKET_TIMEZONE: Final = ZoneInfo("Europe/Amsterdam")
class VatOption(StrEnum):... | klaasnicolaas/python-easyenergy | src/easyenergy/const.py | .py | 38e48c5a0791e0c8 | 7.45 | 7 |
"""Asynchronous Python client for the easyEnergy API."""
from __future__ import annotations
import asyncio
import socket
from dataclasses import dataclass
from datetime import date, timedelta
from importlib import metadata
from typing import Any, Self
from aiohttp.client import ClientError, ClientSession
from aiohtt... | klaasnicolaas/python-easyenergy | src/easyenergy/easyenergy.py | .py | 668898d40263c5e8 | 7.45 | 7 |
"""Data models for the easyEnergy API."""
from __future__ import annotations
from abc import ABC
from bisect import bisect_left, bisect_right
from dataclasses import dataclass, field
from datetime import UTC, datetime
from functools import cached_property
from typing import TYPE_CHECKING, Any, Self
from mashumaro im... | klaasnicolaas/python-easyenergy | src/easyenergy/models.py | .py | 0d970c4cb6fe813e | 7.45 | 7 |
"""Fixture for the easyEnergy tests."""
from collections.abc import AsyncGenerator
import pytest
from aiohttp import ClientSession
from easyenergy import EasyEnergy
@pytest.fixture(name="stable_terminal")
def fixture_stable_terminal(monkeypatch: pytest.MonkeyPatch) -> None:
"""Force deterministic Rich renderin... | klaasnicolaas/python-easyenergy | tests/conftest.py | .py | 9f197e3ef4f3c6ae | 7.95 | 7 |
"""Asynchronous Python client for the Omnik Inverter."""
from __future__ import annotations
import asyncio
import json
from dataclasses import dataclass
from importlib import metadata
from typing import Any, Self
from aiohttp import BasicAuth, ClientError, ClientResponseError, ClientSession
from aiohttp.hdrs import ... | klaasnicolaas/python-omnikinverter | src/omnikinverter/omnikinverter.py | .py | 8ab45fef469a1d43 | 7.52 | 10 |
"""Data model and conversions for tcp-based communication with the Omnik Inverter."""
from __future__ import annotations
from ctypes import BigEndianStructure, c_char, c_ubyte, c_uint, c_ushort, sizeof
from typing import TYPE_CHECKING, Any, ClassVar
from .const import LOGGER
from .exceptions import OmnikInverterPack... | klaasnicolaas/python-omnikinverter | src/omnikinverter/tcp.py | .py | 8ee9026fda3c65f9 | 7.52 | 10 |
"""Testing functionality for the Omnik Inverter device."""
from pathlib import Path
def _fixture_path(filename: str) -> Path:
return Path(__file__).parent / "fixtures" / filename
def load_fixtures(filename: str) -> str:
"""Load a fixture."""
return _fixture_path(filename).read_text(encoding="utf-8")
... | klaasnicolaas/python-omnikinverter | tests/__init__.py | .py | 96f38ecd6a768d6d | 7.52 | 10 |
"""Test the models from TCP source."""
from __future__ import annotations
import struct
import time
from socket import SHUT_RDWR, SO_LINGER, SOL_SOCKET, socket
from threading import Thread
from typing import TYPE_CHECKING
import pytest
from omnikinverter import Device, Inverter, OmnikInverter, tcp
from omnikinverte... | klaasnicolaas/python-omnikinverter | tests/test_tcp_models.py | .py | 9eff1d9aeff69db1 | 7.02 | 10 |
"""Models for Autarco."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import date, datetime
from typing import Any
from mashumaro import DataClassDictMixin, field_options
from mashumaro.config import BaseConfig
from mashumaro.mixins.orjson import DataClassORJSONMixin
fro... | klaasnicolaas/python-autarco | src/autarco/models.py | .py | 07ecb7c314fb54b4 | 7.42 | 6 |
"""
Generated by qenerate plugin=pydantic_v1. DO NOT MODIFY MANUALLY!
"""
from collections.abc import Callable # noqa: F401 # pylint: disable=W0611
from datetime import datetime # noqa: F401 # pylint: disable=W0611
from enum import Enum # noqa: F401 # pylint: disable=W0611
from typing import ( # noqa: F401 # pylint... | app-sre/qenerate | demo/gql/fragments/fragment1.py | .py | f31a1024dc758cac | 7.59 | 14 |
"""
Generated by qenerate plugin=pydantic_v1. DO NOT MODIFY MANUALLY!
"""
from collections.abc import Callable # noqa: F401 # pylint: disable=W0611
from datetime import datetime # noqa: F401 # pylint: disable=W0611
from enum import Enum # noqa: F401 # pylint: disable=W0611
from typing import ( # noqa: F401 # pylint... | app-sre/qenerate | demo/gql/queries/example1.py | .py | 9e20ece560094ead | 7.59 | 14 |
"""
Generated by qenerate plugin=pydantic_v1. DO NOT MODIFY MANUALLY!
"""
from collections.abc import Callable # noqa: F401 # pylint: disable=W0611
from datetime import datetime # noqa: F401 # pylint: disable=W0611
from enum import Enum # noqa: F401 # pylint: disable=W0611
from typing import ( # noqa: F401 # pylint... | app-sre/qenerate | demo/gql/queries/example2.py | .py | 7c934f9ff4208909 | 7.59 | 14 |
import logging
import os
import yaml
import pprint
from yamlinclude import YamlIncludeConstructor
from .DottedDict import DottedDict
logger = logging.getLogger(__name__)
def thisFolder(part, home):
"""{this-folder} is the folder of the yaml that said it.
The same thing in every file - a config, a theme, a l... | n0bel/PiClock3 | PiClock3/Config.py | .py | 80aefe3e57935bff | 7.62 | 16 |
import logging
import string
logger = logging.getLogger(__name__)
class DottedDict(dict):
def __init__(self):
super().__init__(self)
self.__dict__ = self
# also allow x['some.deeper.path']
def __getitem__(self, key):
if '.' not in key:
return super().__getitem__(key)
... | n0bel/PiClock3 | PiClock3/DottedDict.py | .py | a8b0793743e3fa35 | 7.62 | 16 |
import time
from ..Plugin import Plugin
from ..Tiler import TileFetcher
# facts about the service, not settings
HOST = 'https://api.librewxr.net'
ATTRIBUTION = 'LibreWXR'
# Every frame is named after its own timestamp on a ten minute grid, so the
# frame list is arithmetic and needs no index. The current slot alway... | n0bel/PiClock3 | PiClock3/LibreWXR/LibreWXR.py | .py | 1d73bb3c6e2d79cc | 7.62 | 16 |
import logging
import os
import re
import sys
logger = logging.getLogger(__name__)
from PyQt5.QtCore import (QObject)
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QGraphicsDropShadowEffect
DASH = re.compile(r'%-([a-zA-Z])')
WINDOWS = sys.platform == 'win32'
class Plugin(QObject):
def __init__(se... | n0bel/PiClock3 | PiClock3/Plugin.py | .py | 6d9204653cf670b2 | 7.62 | 16 |
import datetime
import json
import logging
import time
from ..Plugin import Plugin
from ..Tiler import TileFetcher
from ..WebGet import WebGet
logger = logging.getLogger(__name__)
INDEX_REFRESH = 300
# facts about the service, not settings
INDEX = 'https://api.rainviewer.com/public/weather-maps.json'
ATTRIBUTION = ... | n0bel/PiClock3 | PiClock3/RainViewer/RainViewer.py | .py | 00aa6a60432d320b | 7.62 | 16 |
"""Derivations a weather source can do for itself.
A station reports temperature, dew point and wind and leaves the rest to the
reader. These are the sums that reader has to do, so a provider can hand
out numbers and a widget can go back to only formatting.
Everything here takes and returns numbers - Celsius, km/h, ... | n0bel/PiClock3 | PiClock3/Weather.py | .py | 6f0488ca0835de4a | 7.62 | 16 |
import logging.handlers
import traceback
import os
import sys
from PyQt5.QtWidgets import QMessageBox, QApplication
from PiClock3.Config import Config
from PiClock3.PiClock3 import PiClock3
sys.path.insert(0, os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'plugins'))
USAGE = """
python3 PyQtPiCl... | n0bel/PiClock3 | PyQtPiClock3.py | .py | 80d98ab5628f5cd8 | 7.62 | 16 |
#!/usr/bin/env python3
# Copyright 2023 Canonical Ltd.
# See LICENSE file for licensing details.
"""Interface library for sharing hydra endpoints.
This library provides a Python API for both requesting and providing public and admin endpoints.
## Getting Started
To get started using the library, you need to fetch the... | canonical/hydra-operator | lib/charms/hydra/v0/hydra_endpoints.py | .py | e24b369b121ac586 | 7.48 | 8 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Interface library for configuring the hydra token hook.
The provider side is responsible for providing the configuration that hydra
will use to call this hook.
The requirer side (hydra) takes the configuration provided and updates its
confi... | canonical/hydra-operator | lib/charms/hydra/v0/hydra_token_hook.py | .py | ba50b4d5c142c217 | 7.48 | 8 |
#!/usr/bin/env python3
# Copyright 2023 Canonical Ltd.
# See LICENSE file for licensing details.
"""Interface library for sharing Identity Platform Login UI application's endpoints with other charms.
This library provides a Python API for both requesting and providing a public endpoints.
## Getting Started
To get star... | canonical/hydra-operator | lib/charms/identity_platform_login_ui_operator/v0/login_ui_endpoints.py | .py | 5701a832311b0c8b | 7.48 | 8 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
from collections import ChainMap
from typing import Any, Mapping, Optional, Protocol, TypeAlias
from jinja2 import Template
from ops import ConfigData, Container, Model, SecretNotFoundError
from ops.pebble import PathError
from typing_extension... | canonical/hydra-operator | src/configs.py | .py | a78d3258796da2d2 | 7.48 | 8 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Reconciliation between the `oauth` integrations and the OAuth2 clients in Hydra."""
import hashlib
import json
import logging
from typing import Any
from charms.hydra.v0.oauth import DataValidationError, OAuthProvider
from ops.model import ... | canonical/hydra-operator | src/oauth.py | .py | cc0f0702f8715a21 | 7.48 | 8 |
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
from datetime import datetime, timezone
from typing import Optional, ValuesView
from ops import Model, SecretNotFoundError
from configs import ServiceConfigs
from constants import (
COOKIE_SECRET,
COOKIE_SECRET_KEY,
COOKIE_SECRET_L... | canonical/hydra-operator | src/secret.py | .py | b99ce8045e447188 | 7.48 | 8 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
import logging
from collections import ChainMap
from typing import Optional
from ops.model import Container, ModelError, Unit
from ops.pebble import CheckStatus, Layer, LayerDict, ServiceInfo
from cli import CommandLine
from configs import Con... | canonical/hydra-operator | src/services.py | .py | ed2cb18aecde8c76 | 7.48 | 8 |
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
from typing import TYPE_CHECKING, Callable, TypeVar
from ops.charm import CharmBase
from constants import (
DATABASE_INTEGRATION_NAME,
INTERNAL_ROUTE_INTEGRATION_NAME,
LOGIN_UI_INTEGRATION_NAME,
PEER_INTEGRATION_NAME,
PUBLI... | canonical/hydra-operator | src/utils.py | .py | c3b57eba5dd71197 | 7.48 | 8 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
import platform
from contextlib import contextmanager
from typing import Callable, Iterator
import jubilant
import yaml
from integration.constants import HYDRA_APP
from tenacity import retry, stop_after_attempt, wait_exponential
StatusPredicat... | canonical/hydra-operator | tests/integration/utils.py | .py | 7d0cecab91d0e2e7 | 7.98 | 8 |
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
from unittest.mock import MagicMock
import pytest
from ops import Container
from ops.pebble import ExecError
from cli import CommandLine, parse_kv_string
from exceptions import ClientDoesNotExistError, MigrationError
@pytest.mark.parametrize... | canonical/hydra-operator | tests/unit/test_cli.py | .py | b232ce79273eb6ea | 7.98 | 8 |
import logging
import subprocess
from pathlib import Path
import typer
from rich.prompt import Prompt
from ..config import config, user_config_file
from ..models import DEFAULT_PROFILE, Env
from ..utils import console
app = typer.Typer()
log = logging.getLogger(__name__)
@app.command()
def init() -> None:
"""D... | app-sre/qontract-development-cli | qontract_development_cli/commands/config.py | .py | cff3aab89ec01910 | 7.45 | 7 |
import logging
import subprocess
from typing import Annotated
import typer
from rich.prompt import Confirm
from ..completions import complete_env
from ..config import config
from ..models import Env
from ..utils import console
app = typer.Typer()
log = logging.getLogger(__name__)
@app.command()
def edit(
env_n... | app-sre/qontract-development-cli | qontract_development_cli/commands/env.py | .py | 94af960a31503900 | 7.45 | 7 |
"""Script for regenerating examples and docs."""
from __future__ import annotations
import argparse
from collections.abc import Sequence
from contextlib import ExitStack
from pathlib import Path
from typeshed_stats.gather import (
PackageInfo,
gather_stats_on_multiple_packages,
tmpdir_typeshed,
)
from ty... | AlexWaygood/typeshed-stats | scripts/regenerate.py | .py | cd566d74b810c455 | 7.59 | 14 |
"""Convenience script to run all checks locally."""
import argparse
import subprocess
import sys
from pathlib import Path
from typing import Literal, overload
FILES_TO_CHECK = ("src", "tests", "scripts", "website_macros.py")
@overload
def run_checks(
*,
regenerate_examples: Literal[True],
typeshed_dir: ... | AlexWaygood/typeshed-stats | scripts/runtests.py | .py | 1198c8284bc9b80e | 8.09 | 14 |
"""Tools for serializing and deserializing [`PackageInfo`][typeshed_stats.gather.PackageInfo] and [`FileInfo`][typeshed_stats.gather.FileInfo] objects."""
import typing
from collections.abc import Sequence
from functools import cache
from operator import attrgetter
from pathlib import Path
from typing import Any
impo... | AlexWaygood/typeshed-stats | src/typeshed_stats/serialize.py | .py | b383312ee3f46799 | 7.59 | 14 |
# pyright: reportUnusedFunction=false
"""Macros and variables for the mkdocs-macros plugin."""
import builtins
import csv
import datetime as dt
import shutil
import subprocess
import types
from abc import abstractmethod
from collections.abc import Callable
from enum import Enum
from pathlib import Path
from typing imp... | AlexWaygood/typeshed-stats | website_macros.py | .py | e385bd1bb84cdbfb | 7.59 | 14 |
import logging
import os
import time
import cachetools
from fastapi import Request
from model import Detector
from app.core.groundlight_client import groundlight_client
from app.escalation_queue.queue_writer import QueueWriter
from app.profiling.context import trace_span
from .database import DatabaseManager
from .e... | groundlight/edge-endpoint | app/core/app_state.py | .py | 044de2f226470f25 | 7.52 | 10 |
import logging
from logging.handlers import RotatingFileHandler
from typing import Any, Dict, Sequence
from sqlalchemy import create_engine, select
from sqlalchemy.engine.base import Engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import sessionmaker
from app.core.file_paths import DATABASE_FILEP... | groundlight/edge-endpoint | app/core/database.py | .py | ca1f558fab0e5f98 | 7.52 | 10 |
"""Simple device ID management.
We need a way to identify the device, and we need to be able to generate a new one if needed.
The device ID is stored in a JSON file, normally at /opt/groundlight/device/id.json
When we generate it, it has a few fields:
- uuid: The unique device ID
- friendly_name: A friendly name for th... | groundlight/edge-endpoint | app/core/deviceid.py | .py | d8502ad530732356 | 7.52 | 10 |
import logging
import os
import yaml
from groundlight.edge import EdgeEndpointConfig, InferenceConfig
from app.profiling.context import trace_span
from .database import DatabaseManager
from .file_paths import ACTIVE_EDGE_CONFIG_PATH
from .naming import get_edge_inference_model_name
logger = logging.getLogger(__name... | groundlight/edge-endpoint | app/core/edge_config_manager.py | .py | 5244613fc7b5fdaf | 7.52 | 10 |
"""Authorize inbound SDK requests against this Edge Endpoint's Groundlight group."""
import hashlib
from functools import lru_cache
from fastapi import HTTPException, Request
from groundlight import ApiTokenError, Groundlight, GroundlightClientError
from groundlight_openapi_client.exceptions import ApiException
from ... | groundlight/edge-endpoint | app/core/edge_endpoint_auth.py | .py | f398b17e0e5956ac | 7.52 | 10 |
import logging
from collections import deque
logger = logging.getLogger(__name__)
class SpeedMonitor:
"""Keeps track of how fast inference has been on each model, in a recency window"""
def __init__(self, window_size: int = 20):
self.models = {}
self.window_size = window_size
def update... | groundlight/edge-endpoint | app/core/speedmon.py | .py | 9bae0e3e93c1340b | 7.52 | 10 |
import json
import logging
import time
import uuid
from datetime import datetime, timezone
from io import BytesIO
from typing import Any, Callable
import cachetools
import ksuid
from fastapi import HTTPException
from model import (
ROI,
BinaryClassificationResult,
BoundingBoxLabelEnum,
BoundingBoxResul... | groundlight/edge-endpoint | app/core/utils.py | .py | 01cac74c370647cc | 7.52 | 10 |
import json
import logging
import traceback
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
import ksuid
from app.escalation_queue.constants import DEFAULT_QUEUE_BASE_DIR
logger = logging.getLogger(__name__)
FAILED_ESCALATIONS_DIR = Path(DEFAULT_QUEUE_BASE_DIR) / "... | groundlight/edge-endpoint | app/escalation_queue/failed_escalations.py | .py | cfd06e1ac4eee826 | 7.52 | 10 |
import json
import logging
import os
import time
from datetime import datetime, timedelta
from pathlib import Path
from fastapi import HTTPException, status
from groundlight import GroundlightClientError, ImageQuery
from urllib3.exceptions import MaxRetryError, ReadTimeoutError
from app.core.groundlight_client import... | groundlight/edge-endpoint | app/escalation_queue/manage_reader.py | .py | c84a704761555b47 | 7.52 | 10 |
from typing import Any
from pydantic import BaseModel
class SubmitImageQueryParams(BaseModel):
"""The parameters of submitting an image query that need to be written to the escalation queue."""
patience_time: float | None
confidence_threshold: float | None
human_review: str | None
metadata: dict... | groundlight/edge-endpoint | app/escalation_queue/models.py | .py | eae3adf49cc125d2 | 7.52 | 10 |
import logging
import os
import re
import time
from itertools import islice
from pathlib import Path
from typing import Generator
from app.escalation_queue.constants import (
DEFAULT_QUEUE_BASE_DIR,
READING_DIR_SUFFIX,
TRACKING_FILE_NAME_PREFIX,
WRITING_DIR_SUFFIX,
)
logger = logging.getLogger(__name_... | groundlight/edge-endpoint | app/escalation_queue/queue_reader.py | .py | 4bbcdbbd9230c922 | 7.52 | 10 |
import logging
from groundlight import Groundlight
from model import ImageQuery
from app.core.utils import get_formatted_timestamp_str, safe_call_sdk
from app.escalation_queue.models import EscalationInfo, SubmitImageQueryParams
from app.escalation_queue.queue_writer import QueueWriter
from app.profiling.context impo... | groundlight/edge-endpoint | app/escalation_queue/queue_utils.py | .py | 3db5fdd066d9b344 | 7.52 | 10 |
import json
import logging
import os
from pathlib import Path
import ksuid
from app.core.utils import get_formatted_timestamp_str
from app.escalation_queue.constants import (
DEFAULT_QUEUE_BASE_DIR,
IMAGE_DIR_SUFFIX,
MAX_QUEUE_FILE_LINES,
WRITING_DIR_SUFFIX,
)
from app.escalation_queue.models import E... | groundlight/edge-endpoint | app/escalation_queue/queue_writer.py | .py | 0672639b3e29c214 | 7.52 | 10 |
import logging
import os
from pathlib import Path
from app.escalation_queue.constants import DEFAULT_REQUEST_CACHE_DIR, DEFAULT_REQUEST_CACHE_MAX_ENTRIES
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
logging.basicConfig(
level=LOG_LEVEL, format="%(asctime)s.%(msecs)03d %(levelname)s %(message)s", datefm... | groundlight/edge-endpoint | app/escalation_queue/request_cache.py | .py | d186a1b229e0c3a6 | 7.52 | 10 |
"""Uses the filesystem to track various metrics about image-query activity. Tracks iqs, escalations,
audits, below_threshold_iqs, and confidence histograms for each detector, as well as iqs submitted to the
edge-endpoint as a whole.
Filesystem structure:
/opt/groundlight/device/edge-metrics/
detectors/
<de... | groundlight/edge-endpoint | app/metrics/iq_activity.py | .py | 63dc2bbb8fc35dcf | 7.52 | 10 |
"""Report metrics to the cloud API.
Is called by the main edge-endpoint web server.
Can also be run directly as a script.
"""
import json
import logging
import os
from datetime import datetime, timedelta
from typing import Any, Callable
from app.core import deviceid
from app.core.groundlight_client import groundlight... | groundlight/edge-endpoint | app/metrics/metric_reporting.py | .py | c6ffd2e35f69d241 | 7.52 | 10 |
import json
import logging
import os
from datetime import datetime, timedelta, timezone
import psutil
import tzlocal
import yaml
from groundlight.edge import InferenceConfig
from kubernetes import client, config
from app.core.edge_config_manager import EdgeConfigManager
from app.core.edge_inference import get_current... | groundlight/edge-endpoint | app/metrics/system_metrics.py | .py | d017e6d8e92b6c9f | 7.52 | 10 |
import logging
import os
import time
from app.core.database import DatabaseManager
from app.core.edge_config_manager import EdgeConfigManager
from app.core.edge_inference import EdgeInferenceManager, delete_old_model_versions
from app.core.kubernetes_management import InferenceDeploymentManager
from app.core.naming im... | groundlight/edge-endpoint | app/model_updater/update_models.py | .py | 3ce4e4240ca2d184 | 7.52 | 10 |
import os
from app.profiling.context import get_current_span, get_current_tracer, trace_span
PROFILING_ENABLED: bool = os.environ.get("ENABLE_PROFILING", "false").lower() == "true"
_manager = None
def get_profiling_manager():
"""Returns the ProfilingManager singleton. Only call when PROFILING_ENABLED is True."... | groundlight/edge-endpoint | app/profiling/__init__.py | .py | 989a437e4dcebea8 | 7.52 | 10 |
import asyncio
import contextvars
from functools import wraps
_current_tracer = contextvars.ContextVar("_current_tracer", default=None)
_current_span = contextvars.ContextVar("_current_span", default=None)
def get_current_tracer():
"""Returns the active RequestTracer for the current context, or None."""
retu... | groundlight/edge-endpoint | app/profiling/context.py | .py | f20b30fe85d524a1 | 7.52 | 10 |
"""Load and aggregate profiling trace data from JSONL files on disk.
This module is used by the Marimo dashboard notebook and can also be used
independently for CLI analysis or testing.
"""
import json
import logging
import statistics
import time
from datetime import datetime, timedelta, timezone
from pathlib import ... | groundlight/edge-endpoint | app/profiling/data_loader.py | .py | b98989de32dbcc7a | 7.52 | 10 |
"""Runtime instrumentation that closes profiling gaps the @trace_span decorator can't reach.
Currently this module only handles `starlette.concurrency.run_in_threadpool`. FastAPI dispatches every
synchronous dependency and Starlette dispatches every synchronous BackgroundTask through that helper,
which awaits an `anyi... | groundlight/edge-endpoint | app/profiling/instrumentation.py | .py | 2667f575446f48dd | 7.52 | 10 |
import json
import logging
import os
import threading
import time
from datetime import datetime
from pathlib import Path
from app.profiling.models import Trace
logger = logging.getLogger(__name__)
PROFILING_DIR = "/opt/groundlight/device/edge-profiling"
ROTATION_INTERVAL_SECONDS = 300 # 5 minutes
MAX_FILE_AGE_HOURS... | groundlight/edge-endpoint | app/profiling/manager.py | .py | 1609edb2f596b383 | 7.52 | 10 |
import logging
import time
from app.profiling import PROFILING_ENABLED, record_trace, start_trace
# Middleware is the sole setter of the tracer context; public API only exposes getters.
from app.profiling.context import _current_tracer
logger = logging.getLogger(__name__)
class ProfilingMiddleware:
"""Raw ASGI... | groundlight/edge-endpoint | app/profiling/middleware.py | .py | 5e13a8975822dfda | 7.52 | 10 |
#!/usr/bin/env python3
import os
import signal
import subprocess
import sys
import time
import argparse
import logging
import json
from functools import partial
from dataclasses import dataclass
from typing import List, Tuple
# Import from Qt – note: these come from pyqtgraph’s wrapper
from pyqtgraph.Qt import QtGui
f... | waterloo-rocketry/omnibus | launcher.py | .py | 2756987c063d1284 | 7.63 | 17 |
from pyqtgraph.parametertree.parameterTypes import ActionParameter, ActionParameterItem
class NoTextActionParameterItem(ActionParameterItem):
"""An action parameter item that works around
https://github.com/pyqtgraph/pyqtgraph/issues/2380.
This avoids the text displaying twice on MacOS dark mode.
"""
... | waterloo-rocketry/omnibus | src/dashboard/items/no_text_action_parameter.py | .py | 443719a257177dcc | 7.63 | 17 |
from dataclasses import dataclass
import socket
import time
import msgpack
import zmq
from datetime import datetime
from typing import Any, ClassVar
try:
from . import server
except ImportError:
# Python complains if we run `python -m omnibus` from the omnibus folder.
# This works around that complaint.
... | waterloo-rocketry/omnibus | src/omnibus/omnibus.py | .py | 1e7d44a3e53c162d | 7.63 | 17 |
import socket
import threading
import time
from typing import NoReturn
import argparse
import zmq
from zmq.devices import ThreadProxy
try:
from .util import BuildInfoManager
except ImportError:
from util import BuildInfoManager # pyright: ignore[reportImplicitRelativeImport]
SOURCE_PORT = 5075
SINK_PORT = 5... | waterloo-rocketry/omnibus | src/omnibus/server.py | .py | 73e62a49ffcf265f | 7.63 | 17 |
import time
class TickCounter:
"""
TickCounter is a wrapper class for counting ticks (events) in regular intervals,
such as frames per second.
"""
# count the number of ticks in the last running_average_duration seconds
def __init__(self, running_average_duration):
self.running_averag... | waterloo-rocketry/omnibus | src/omnibus/util/tick_counter.py | .py | c839d2b9422a2293 | 7.63 | 17 |
import signal
import sys
import os
from PySide6.QtCore import QTimer
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QApplication, QMessageBox
from tileserver import start_tileserver, stop_tileserver
from src.main_window import MapWindow
from config import ONLINE_MODE, MBTILES_PATH
should_force_close =... | waterloo-rocketry/omnibus | src/sinks/interamap/interamap.py | .py | ae42c6fa37b22b6a | 7.63 | 17 |
import zipfile
from datetime import datetime
from enum import IntEnum
import os
from PySide6.QtWidgets import QMessageBox, QApplication
from PySide6.QtCore import QThread, Signal, Qt
from fastkml import kml, geometry, times
from src.data_struct import Point_GPS, Info_GPS, LineString_GPS
import webbrowser
class GPS_... | waterloo-rocketry/omnibus | src/sinks/interamap/src/gps_cache.py | .py | a6ab130d31b6c543 | 7.63 | 17 |
import os
import sys
import http.server
import socketserver
import socket
import threading
from config import HTTP_SERVER_PORT
def check_permissions(folder: str) -> bool:
"""Return True if the folder is readable, otherwise False."""
return os.access(folder, os.R_OK)
def get_local_ip() -> str:
"""Attempt t... | waterloo-rocketry/omnibus | src/sinks/interamap/src/http_server.py | .py | 5bea5f45936922ab | 7.63 | 17 |
import os
from PySide6.QtWidgets import (
QMainWindow,
QVBoxLayout,
QWidget,
QHBoxLayout,
QPushButton,
QSizePolicy,
QLabel,
QSplitter,
QComboBox,
QFileDialog,
QMessageBox,
)
from PySide6.QtCore import Qt
from src.map_view import MapView
from src.http_server import get_shar... | waterloo-rocketry/omnibus | src/sinks/interamap/src/main_window.py | .py | bb6c7df547ba2327 | 7.63 | 17 |
from collections import defaultdict
import queue
import sys
import time
from typing import Any
import traceback
from omnibus import Receiver
from PySide6.QtCore import QThread, Signal
try:
from src.data_struct import Point_GPS, Info_GPS
from config import BoardID, BOARD_FIELDS
except ImportError:
from dat... | waterloo-rocketry/omnibus | src/sinks/interamap/src/real_time_parser.py | .py | f69e59dcc13f9375 | 7.63 | 17 |
import mwparserfromhell
import os
import proto.gen.equipment_pb2 as equipment_pb2
import proto.gen.npc_infos_pb2 as npc_infos_pb2
import pywikibot
import sys
import util
from google.protobuf.json_format import ParseDict, ParseError
from pywikibot import family, pagegenerators
from warnings import warn
class OSRSFami... | nkibler7/osrs-wiki-scraper | main.py | .py | 8f2f5c191bf38acf | 7.5 | 9 |
import base64
import pathlib
from uuid import UUID
from ariadne import (
ScalarType,
load_schema_from_path,
make_executable_schema,
snake_case_fallback_resolvers,
)
from django.contrib.contenttypes.models import ContentType
from hexa.assistant.schema import assistant_bindables, assistant_type_defs
fro... | BLSQ/openhexa-app | backend/config/schema.py | .py | df12d9ef829076ef | 7.65 | 19 |
from django.conf import settings
from django.http import HttpRequest
from mixpanel import Mixpanel
from sentry_sdk import capture_exception
from ua_parser import user_agent_parser
from hexa.user_management.models import AnonymousUser, Feature, User
mixpanel = None
if settings.MIXPANEL_TOKEN:
from mixpanel_async i... | BLSQ/openhexa-app | backend/hexa/analytics/api.py | .py | 8d1be5e1c43bd690 | 7.65 | 19 |
from typing import Callable
from django.http import HttpRequest, HttpResponse
from hexa.analytics.api import set_user_properties
def set_analytics_middleware(
get_response: Callable[[HttpRequest], HttpResponse],
) -> Callable[[HttpRequest], HttpResponse]:
"""Send the user properties to the analytics service... | BLSQ/openhexa-app | backend/hexa/analytics/middlewares.py | .py | 7a7930c12c254a5e | 7.65 | 19 |
from functools import cache
from importlib import import_module
from django.apps import AppConfig, apps
from django.db.models.base import ModelBase
class CoreAppConfig(AppConfig):
"""Base class for our own "core" apps (not connector plugins).
ANONYMOUS_URLS will be used by our authentication middleware
... | BLSQ/openhexa-app | backend/hexa/app.py | .py | 49d3a282166afef9 | 7.65 | 19 |
import io
import zipfile
from pydantic import BaseModel
from hexa.assistant.agents.base import BaseAgent
from hexa.assistant.instructions import InstructionSet
from hexa.assistant.models import Conversation, ToolInvocation
from hexa.mcp.tools.connections import list_connections
from hexa.mcp.tools.datasets import get... | BLSQ/openhexa-app | backend/hexa/assistant/agents/edit_pipeline_agent.py | .py | abd9afd8b008003a | 7.65 | 19 |
import logging
import re
import psycopg2
import sqlparse
from asgiref.sync import sync_to_async
from pydantic_ai import ModelRetry
from pydantic_ai.output import TextOutput
from hexa.assistant.agents.base import BaseAgent
from hexa.assistant.instructions import InstructionSet
from hexa.databases.query_text import Mul... | BLSQ/openhexa-app | backend/hexa/assistant/agents/generate_sql_agent.py | .py | bdd0f55903a512c1 | 7.65 | 19 |
from datetime import timedelta
from decimal import Decimal
from functools import cached_property
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.db import models
from django.db.mo... | BLSQ/openhexa-app | backend/hexa/assistant/models.py | .py | 6149f3e9fe2e2876 | 7.65 | 19 |
from ariadne import ObjectType, UnionType
from hexa.assistant.models import Conversation, Message, ToolInvocation
from hexa.assistant.types import TextSegment, ToolSegment
from hexa.core.graphql import result_page
assistant_conversation_object = ObjectType("AssistantConversation")
assistant_message_object = ObjectTyp... | BLSQ/openhexa-app | backend/hexa/assistant/schema/types.py | .py | fb8f6c3ea68028eb | 7.65 | 19 |
"""Loading, validation and diagram rendering for the node graph.
Shared by check.py (validation), kg.py (queries) and site.py (the site) so
the schema lives in exactly one place.
"""
import re
import textwrap
from pathlib import Path
import yaml
ROOT = Path(__file__).resolve().parent.parent
NODES_DIR = ROOT / "node... | kvark/aitia | tools/graph.py | .py | 2407ec6c5a52c59b | 7.48 | 8 |
# (C) Daniel Strano and the Qrack contributors 2017-2025. All rights reserved.
#
# Use of this source code is governed by an MIT-style license that can be
# found in the LICENSE file or at https://opensource.org/licenses/MIT.
from .qrack_simulator import QrackSimulator
from .qrack_system import Qrack
class QrackStabi... | unitaryfoundation/pyqrack | pyqrack/qrack_stabilizer.py | .py | 11a9af799b1e8e8e | 7.66 | 20 |
# (C) Daniel Strano and the Qrack contributors 2017-2025. All rights reserved.
#
# Use of this source code is governed by an MIT-style license that can be
# found in the LICENSE file or at https://opensource.org/licenses/MIT.
try:
# Written by Elara (custom OpenAI GPT)
import numpy as np
def quantize_by_r... | unitaryfoundation/pyqrack | pyqrack/stats/quantize_by_range.py | .py | ccf2cc36ebb2ccc3 | 7.66 | 20 |
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.ArObject import (
ARObject,
)
from armodel.models.M2.AUTOSARTemplates.SWComponentTemplate.Datatype.Datatypes import (
ApplicationDataType,
)
class ApplicationDeferredDataType(ApplicationDataType):
"""
A placeholder data ty... | melodypapa/py-armodel | src/armodel/models/M2/AUTOSARTemplates/AbstractPlatform/ApplicationDeferredDataType.py | .py | 53c0764ed493f070 | 7.63 | 17 |
from armodel.models.M2.AUTOSARTemplates.AdaptivePlatform.ApplicationDesign.PortInterface.Field import (
Field,
)
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.ArObject import (
ARObject,
)
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.Primitive... | melodypapa/py-armodel | src/armodel/models/M2/AUTOSARTemplates/AbstractPlatform/ApplicationInterface.py | .py | 2e461045860a80b9 | 7.63 | 17 |
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.ArObject import ARObject
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.PrimitiveTypes import Boolean
from armodel.models.M2.AUTOSARTemplates.SWComponentTemplate.Datatype.DataPrototypes import AutosarDataPro... | melodypapa/py-armodel | src/armodel/models/M2/AUTOSARTemplates/AdaptivePlatform/ApplicationDesign/PortInterface/Field.py | .py | 9227434663966baa | 7.63 | 17 |
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.ArObject import (
ARObject,
)
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.Identifiable import (
ARElement,
)
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.Primiti... | melodypapa/py-armodel | src/armodel/models/M2/AUTOSARTemplates/AdaptivePlatform/PlatformModuleDeployment/AdaptiveModule/PlatformModuleEthernetEndpointConfiguration.py | .py | f8682052af242843 | 7.63 | 17 |
from armodel.models.M2.AUTOSARTemplates.AdaptivePlatform.PlatformModuleDeployment.CryptoDeployment.CryptoKeySlotContent import ( # noqa: F401
CryptoKeySlotContent,
)
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.ArObject import (
ARObject,
)
from armodel.models.M2.AUTOSARTempl... | melodypapa/py-armodel | src/armodel/models/M2/AUTOSARTemplates/AdaptivePlatform/PlatformModuleDeployment/CryptoDeployment/CryptoKeySlot.py | .py | e5151105ef6946cb | 7.63 | 17 |
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.ArObject import (
ARObject,
)
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.Identifiable import (
Identifiable,
)
class CryptoKeySlotContent(Identifiable):
"""
This meta-class represents t... | melodypapa/py-armodel | src/armodel/models/M2/AUTOSARTemplates/AdaptivePlatform/PlatformModuleDeployment/CryptoDeployment/CryptoKeySlotContent.py | .py | 86cc5ee95f38558b | 7.63 | 17 |
from abc import ABC
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.ArObject import (
ARObject,
)
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.Identifiable import (
Identifiable,
)
from typing import Any, List, Optional
class IdsPlatformInstan... | melodypapa/py-armodel | src/armodel/models/M2/AUTOSARTemplates/AdaptivePlatform/PlatformModuleDeployment/IntrusionDetectionSystem/IdsPlatformInstantiation.py | .py | 16c028835b916ca6 | 7.63 | 17 |
from armodel.models.M2.AUTOSARTemplates.AdaptivePlatform.PlatformModuleDeployment.IntrusionDetectionSystem.IdsPlatformInstantiation import ( # noqa: F401
IdsPlatformInstantiation,
)
from armodel.models.M2.AUTOSARTemplates.GenericStructure.GeneralTemplateClasses.ArObject import (
ARObject,
)
class IdsmModuleI... | melodypapa/py-armodel | src/armodel/models/M2/AUTOSARTemplates/AdaptivePlatform/PlatformModuleDeployment/IntrusionDetectionSystem/IdsmModuleInstantiation.py | .py | 4f63627545f36c1c | 7.63 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.