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 |
|---|---|---|---|---|---|---|
'''
Author: BHM-Bob 2262029386@qq.com
Date: 2023-03-21 00:12:32
LastEditors: BHM-Bob 2262029386@qq.com
LastEditTime: 2025-04-07 21:56:41
Description:
'''
from typing import List
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
from .utils import GlobalSetting... | BHM-Bob/BA_PY | mbapy/dl_torch/data.py | .py | 23b6f3ca0ee222be | 7.3 | 3 |
'''
Author: BHM-Bob 2262029386@qq.com
Date: 2023-05-01 20:16:20
LastEditors: BHM-Bob
LastEditTime: 2023-05-01 20:17:32
Description:
'''
import math
import pickle
import time
import numpy as np
from hyperopt import STATUS_FAIL, STATUS_OK, Trials, fmin, hp, tpe
space = {
"a": hp.uniform("a", -10, 10)... | BHM-Bob/BA_PY | mbapy/dl_torch/hyper_search.py | .py | 8c7e689a2479553b | 7.3 | 3 |
"""Foodsharing.de binary sensor platform."""
import logging
from typing import Any
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.core i... | FaserF/ha-foodsharing | custom_components/foodsharing/binary_sensor.py | .py | a43804fc636bc086 | 7.3 | 3 |
"""Button platform for Foodsharing, with dynamic entity management."""
import logging
from typing import Any
from homeassistant.components.button import ButtonEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_reg... | FaserF/ha-foodsharing | custom_components/foodsharing/button.py | .py | 96a456ec4a646c5f | 7.3 | 3 |
"""Calendar platform for Foodsharing integration."""
import logging
from datetime import datetime
from homeassistant.components.calendar import CalendarEntity, CalendarEvent
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry imp... | FaserF/ha-foodsharing | custom_components/foodsharing/calendar.py | .py | 210dc18fb2bb6b0b | 7.3 | 3 |
"""Geo-location platform for Foodsharing."""
import logging
import math
from typing import Any
from homeassistant.components.geo_location import GeolocationEvent
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_registr... | FaserF/ha-foodsharing | custom_components/foodsharing/geo_location.py | .py | b372f7ccf2c02f60 | 7.3 | 3 |
"""Helpers for Foodsharing integration."""
from __future__ import annotations
import logging
from typing import Any
from homeassistant.config_entries import ConfigEntry
from .const import CONF_LOCATIONS
_LOGGER = logging.getLogger(__name__)
def get_locations_from_entry(entry: ConfigEntry) -> list[dict[str, Any]]... | FaserF/ha-foodsharing | custom_components/foodsharing/helpers.py | .py | 48753dae9d0b6e2a | 7.3 | 3 |
"""Fixtures for testing Foodsharing integration."""
from unittest.mock import MagicMock, patch
import pytest
@pytest.fixture(autouse=True)
def auto_mock_ha():
"""Mock the Home Assistant helpers that require a running instance."""
import homeassistant.helpers.frame as frame
with (
patch("homeass... | FaserF/ha-foodsharing | tests/conftest.py | .py | a05d2efd45936514 | 7.8 | 3 |
"""Test button platform for Foodsharing."""
from unittest.mock import AsyncMock, MagicMock
import pytest
from custom_components.foodsharing.button import (
FoodsharingCloseSlotButton,
FoodsharingRequestSlotButton,
)
@pytest.fixture
def mock_coordinator():
"""Mock coordinator."""
coordinator = Magic... | FaserF/ha-foodsharing | tests/test_button.py | .py | 6cd5dad212066184 | 7.8 | 3 |
from unittest.mock import MagicMock
from custom_components.foodsharing.sensor import (
FoodsharingBananasSensor,
FoodsharingBellsSensor,
FoodsharingBuddiesSensor,
FoodsharingFairteilerSensor,
FoodsharingGlobalStatsSensor,
FoodsharingMessagesSensor,
FoodsharingPickupsSensor,
FoodsharingR... | FaserF/ha-foodsharing | tests/test_sensor.py | .py | 4fd57fa655fde5ce | 7.8 | 3 |
"""Shared contracts for source-format importers."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from cad2d_ir.constants import CURRENT_IR_VERSION
from cad2d_ir.diagnostics import DiagnosticSeverity
class ImporterError(ValueError):
"""Base class for importe... | monozukuri-ai/cad2d-ir | src/cad2d_ir/importers/base.py | .py | e8e6c81fc161d892 | 7.15 | 1 |
#!/usr/bin/env python
# %%
import csv
import json
import logging
import os
from pathlib import Path
from typing import Any, Callable, List, Optional, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
from tqdm.auto import tqdm
logger = logging.getLogger(__name__)
def load_json(file: Union[str, Path]) ... | lzcn/outfit-datasets | ifashion/processing.py | .py | 1899bf39b85a7e7a | 7.39 | 5 |
#!/usr/bin/env python
import argparse
import os
import time
from multiprocessing import Pool
import requests
import torchutils
from PIL import Image
from tqdm.auto import tqdm
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Saf... | lzcn/outfit-datasets | iqon-3000/check_images.py | .py | 135a09e0a2a1a316 | 7.39 | 5 |
#!/usr/bin/env python
# %%
# create dataset for NGNN
import os
import numpy as np
import torchutils
from sklearn.metrics import roc_auc_score
# %%
# load polyvore maryland dataset
inputDir = "maryland-polyvore/release"
outputDir = "maryland-polyvore/processed"
dataDir = "maryland-polyvore/ngnn"
trainOutfits = torc... | lzcn/outfit-datasets | maryland-polyvore/create_tuples_ngnn.py | .py | e53da3e605d8e7a3 | 7.39 | 5 |
#!/usr/bin/env python
# %%
import os
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torchutils
# %% data configuration
inputDir = "release"
outputDir = "processed"
dataSet = "nondisjoint"
dataSet = "disjoint"
minSize = 2
maxSize = 14
numCate = 11
dataDir = os.path.j... | lzcn/outfit-datasets | polyvore-outfits/create_tuples_0309.py | .py | cc90a7732a8d63e7 | 7.39 | 5 |
#!/usr/bin/env python
# %%
import os
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torchutils
# %% data configuration
inputDir = "release"
outputDir = "processed"
# dataSet = "nondisjoint"
dataSet = "disjoint"
minSize = 4
maxSize = 8
dataDir = os.path.join(inputDir... | lzcn/outfit-datasets | polyvore-outfits/create_tuples_0408.py | .py | ca3daf5cf83eebe4 | 7.39 | 5 |
"""
Alexa Devices Alarm Control Panel using Guard Mode.
SPDX-License-Identifier: Apache-2.0
For more details about this platform, please refer to the documentation at
https://community.home-assistant.io/t/echo-devices-alexa-as-media-player-testers-needed/58639
"""
from asyncio import sleep
import logging
from typing... | geNAZt/home-assistant | custom_components/alexa_media/alarm_control_panel.py | .py | e3911e797bd7c90e | 7 | 0 |
"""
Alexa Devices Base Class.
SPDX-License-Identifier: Apache-2.0
For more details about this platform, please refer to the documentation at
https://community.home-assistant.io/t/echo-devices-alexa-as-media-player-testers-needed/58639
"""
import logging
from alexapy import AlexaAPI, hide_email
from .const import D... | geNAZt/home-assistant | custom_components/alexa_media/alexa_media.py | .py | 7d215adb329b731b | 7 | 0 |
"""
Alexa Devices Sensors.
SPDX-License-Identifier: Apache-2.0
For more details about this platform, please refer to the documentation at
https://community.home-assistant.io/t/echo-devices-alexa-as-media-player-testers-needed/58639
"""
import logging
from alexapy import hide_serial
from homeassistant.components.bin... | geNAZt/home-assistant | custom_components/alexa_media/binary_sensor.py | .py | 86b1e79b94ff6036 | 7 | 0 |
"""Optimized DataUpdateCoordinator for Alexa Media Player.
Optimizations:
- Debouncer for request coalescing
- Type-safe runtime data integration
"""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import TYPE_CHECKING, Any, Callable
from homeassistant.helpers.debounce i... | geNAZt/home-assistant | custom_components/alexa_media/coordinator.py | .py | 3895d9c6d348a70f | 7 | 0 |
"""Diagnostics support for Alexa Media Player."""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import fields, is_dataclass
from datetime import datetime
from itertools import islice
import re
from typing import Any
from homeassistant.config_entries import ConfigE... | geNAZt/home-assistant | custom_components/alexa_media/diagnostics.py | .py | 5d92d16cb9d5653a | 7 | 0 |
"""Alexa Media Exceptions"""
class EmptyDataException(Exception):
"""Empty data exception"""
class ForbiddenException(Exception):
"""Forbidden exception"""
class LoginForbiddenException(Exception):
"""Login forbidden exception"""
class LoginInvalidException(Exception):
"""Invalid login exception... | geNAZt/home-assistant | custom_components/alexa_media/exceptions.py | .py | 29bd09a02fc33649 | 7 | 0 |
"""
Helper functions for Alexa Media Player.
SPDX-License-Identifier: Apache-2.0
For more details about this platform, please refer to the documentation at
https://community.home-assistant.io/t/echo-devices-alexa-as-media-player-testers-needed/58639
"""
import asyncio
import functools
import hashlib
import logging
f... | geNAZt/home-assistant | custom_components/alexa_media/helpers.py | .py | a29cb6b95b3c1b38 | 7 | 0 |
"""
Alexa Devices Lights.
SPDX-License-Identifier: Apache-2.0
For more details about this platform, please refer to the documentation at
https://community.home-assistant.io/t/echo-devices-alexa-as-media-player-testers-needed/58639
"""
import datetime
import logging
from math import sqrt
from typing import Optional
... | geNAZt/home-assistant | custom_components/alexa_media/light.py | .py | 7fb8f091d655307d | 7 | 0 |
"""Performance metrics and caching for Alexa Media Player.
Provides boot time tracking and intelligent data caching.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import logging
import time
from typing import Any
from homeassistant.core import HomeAssistant
from .const import DOMA... | geNAZt/home-assistant | custom_components/alexa_media/metrics.py | .py | af17feb1ebab0431 | 7 | 0 |
"""Runtime data for Alexa Media Player integration.
This module implements the Platinum architecture using entry.runtime_data
instead of the legacy hass.data[DOMAIN] pattern.
"""
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
import logging
from typing import TYPE_CHECKING... | geNAZt/home-assistant | custom_components/alexa_media/runtime_data.py | .py | 64417022b3139b12 | 7 | 0 |
"""
Alexa Devices Switches.
SPDX-License-Identifier: Apache-2.0
For more details about this platform, please refer to the documentation at
https://community.home-assistant.io/t/echo-devices-alexa-as-media-player-testers-needed/58639
"""
import datetime
import logging
from alexapy import AlexaAPI
from homeassistant.... | geNAZt/home-assistant | custom_components/alexa_media/switch.py | .py | 3c487729561874e7 | 7 | 0 |
"""Support for Bambu Lab through MQTT."""
from __future__ import annotations
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
fro... | geNAZt/home-assistant | custom_components/bambu_lab/binary_sensor.py | .py | c8aff4bb8ef93c1c | 7 | 0 |
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import EntityCategory
from .const import DOMAIN, LOGGER
from .models import BambuLabEntity
from .pybambu.commands imp... | geNAZt/home-assistant | custom_components/bambu_lab/button.py | .py | ed99b30e6f297bcb | 7 | 0 |
"""Diagnostics support for Bambu Lab integration."""
from __future__ import annotations
import json
from datetime import datetime
from typing import Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
... | geNAZt/home-assistant | custom_components/bambu_lab/diagnostics.py | .py | 28bec3d1115c0463 | 7 | 0 |
from dataclasses import dataclass
from collections.abc import Callable
from homeassistant.components.fan import (
FanEntity,
FanEntityFeature,
FanEntityDescription
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform ... | geNAZt/home-assistant | custom_components/bambu_lab/fan.py | .py | 326d7d28dcb7d692 | 7 | 0 |
"""Frontend for Bambu Lab Cards"""
import logging
import os
import pathlib
from packaging.version import parse
from homeassistant.core import HomeAssistant
from homeassistant.helpers.event import async_call_later
from homeassistant.components.http import StaticPathConfig
from homeassistant.const import __version__
... | geNAZt/home-assistant | custom_components/bambu_lab/frontend/__init__.py | .py | 5bf5fbc03aff1a3b | 7 | 0 |
"""
Tests for get_hms_error_text and get_print_error_text.
Correctness may be affected by an update to the error_text.json; if this occurs
simply update the text or select a different locale, printer serial number, etc.
"""
import unittest
import os
import sys
# Add the parent directory to the Python path to find pyb... | geNAZt/home-assistant | custom_components/bambu_lab/pybambu/tests/test_error_lookup.py | .py | 3e7c302e5be0000c | 7.5 | 0 |
from unittest.mock import MagicMock
import json
import os
import asyncio
from typing import Dict, Any, Callable, Optional
from ..const import (
LOGGER,
)
from ..utils import safe_json_loads
class MqttMessageInfo:
"""Mock MQTT message info object."""
def __init__(self, mid: int = 1):
self.mid = mid... | geNAZt/home-assistant | custom_components/bambu_lab/pybambu/tests/test_utils.py | .py | 438c62b5c54fb79e | 7.5 | 0 |
import functools
import gzip
import json
import logging
import math
import requests
import socket
import re
from datetime import datetime, timedelta, timezone
from urllib3.exceptions import ReadTimeoutError
from bs4 import BeautifulSoup
from pathlib import Path
from .const import (
CURRENT_STAGE_IDS,
SPEED_PR... | geNAZt/home-assistant | custom_components/bambu_lab/pybambu/utils.py | .py | 2630bc4a0caf51cb | 7 | 0 |
"""Support for Bambu Lab through MQTT."""
from __future__ import annotations
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import EntityCategory
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant... | geNAZt/home-assistant | custom_components/bambu_lab/select.py | .py | 5c5f446f18794352 | 7 | 0 |
"""Deploy command which installs Transformers extension SLC,
scripts, creates connection objects"""
import logging
import click
import exasol.python_extension_common.connections.bucketfs_location as bl
from exasol.python_extension_common.cli.bucketfs_conn_object_cli import (
BucketfsConnObjectCli,
)
from exasol.p... | exasol/transformers-extension | exasol_transformers_extension/deploy.py | .py | dc5ec42cd6e7605b | 7.24 | 2 |
"""Class InstallScriptsConstants to encapsulate different sets of constants
for each set of UDFs to be installed."""
from pathlib import Path
from importlib_resources import files
class InstallScriptsConstants:
"""
Class to encapsulate different sets of constants for each set of
UDFs/scripts to be insta... | exasol/transformers-extension | exasol_transformers_extension/deployment/install_scripts_constants.py | .py | 60971f6fd480e384 | 7.24 | 2 |
"""
LanguageContainerDeployer for Transformers Extension Language Container
"""
from pathlib import Path
from typing import Optional
from exasol.python_extension_common.deployment.language_container_deployer import (
LanguageContainerDeployer,
)
class TeLanguageContainerDeployer(LanguageContainerDeployer):
... | exasol/transformers-extension | exasol_transformers_extension/deployment/te_language_container_deployer.py | .py | 9507a3a17c62a7bf | 7.24 | 2 |
"""
UDF for continuing a given text. May be used to return whole text,
or only the newly generated part.
"""
import transformers
from exasol_transformers_extension.udfs.models.base_model_udf import BaseModelUDF
from exasol_transformers_extension.udfs.models.prediction_tasks.text_generation import (
TextGenPredict... | exasol/transformers-extension | exasol_transformers_extension/udfs/models/ai_complete_extended_udf.py | .py | a92d35507473d1a3 | 7.24 | 2 |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <dm@sweetrpg.com>"
"""health.py
Health endpoints.
"""
from flask import Blueprint, current_app, jsonify
from werkzeug.exceptions import HTTPException
import json
import os
from sweetrpg_web_core import constants
blueprint = Blueprint("health", __name__, url_prefi... | sweetrpg/web-core | src/sweetrpg_web_core/blueprints/health/__init__.py | .py | 8ec02748909375b6 | 7 | 0 |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <dm@sweetrpg.com>"
"""Context helper functions.
"""
from flask import current_app, session, request
import os
from sweetrpg_web_core import constants
import hashlib
def get_context() -> dict:
"""Initialize a context object.
:return:
"""
email = s... | sweetrpg/web-core | src/sweetrpg_web_core/helpers/context.py | .py | 9dab62e3a624eaca | 7 | 0 |
"""
bsl.py — Bitstring Status List checker (JSON-LD or VC-JWT container)
- Accepts status list credentials delivered as **VC-JWT** (application/vc+jwt, application/jwt, text/plain)
or **JSON/JSON-LD** (application/ld+json, application/json).
- Implements multibase(base64url-nopad) + GZIP expansion, MSB-first bit or... | TalaoDAO/sandbox | bsl.py | .py | 9fe240cc77733083 | 7.15 | 1 |
""" for token see passwords.json
https://ssl.smsapi.com/#/payments/transfer/success
"""
from smsapi.client import SmsApiComClient
from smsapi.exception import SmsApiException
import logging
logging.basicConfig(level=logging.INFO)
def send_code(phone, code, mode) :
""" code = str, phone number with country code 336... | TalaoDAO/sandbox | components/sms.py | .py | fb6b9c1fbfb32fc3 | 7.15 | 1 |
"""Config shared by all Noteburst components."""
from typing import Annotated
from arq.connections import RedisSettings
from pydantic import Field, RedisDsn
from pydantic_settings import BaseSettings
from safir.metrics import MetricsConfiguration, metrics_configuration_factory
__all__ = ["BaseConfig"]
class BaseCo... | lsst-sqre/noteburst | src/noteburst/config/base.py | .py | 77b4718ae638c80a | 7.15 | 1 |
"""Config for the Noteburst worker."""
from enum import StrEnum
from pathlib import Path
from typing import Annotated, Self
from pydantic import Field, RedisDsn, model_validator
from rubin.nublado.client import (
NubladoImage,
NubladoImageByClass,
NubladoImageByReference,
NubladoImageClass,
)
from .f... | lsst-sqre/noteburst | src/noteburst/config/worker.py | .py | 126efdecd7b7d717 | 7.15 | 1 |
"""App metrics events."""
from typing import override
from safir.dependencies.metrics import EventDependency, EventMaker
from safir.metrics import EventManager, EventPayload
__all__ = [
"EnqueueNotebookExecutionFailure",
"EnqueueNotebookExecutionSuccess",
"Events",
"events_dependency",
]
class Enqu... | lsst-sqre/noteburst | src/noteburst/events.py | .py | e382664d34d0273e | 7.15 | 1 |
"""Exceptions for the Noteburst application."""
from typing import Self, override
from fastapi import status
from safir.fastapi import ClientRequestError
from safir.slack.blockkit import SlackException, SlackMessage, SlackTextField
from safir.slack.sentry import SentryEventInfo
__all__ = [
"NbexecTaskError",
... | lsst-sqre/noteburst | src/noteburst/exceptions.py | .py | 2cd53119bcc82ac3 | 7.15 | 1 |
"""Handlers for the app's external root, ``/noteburst/``."""
from typing import Annotated
from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field
from safir.dependencies.gafaelfawr import auth_logger_dependency
from safir.metadata import Metadata as SafirMetadata
from safir.metadata import get_me... | lsst-sqre/noteburst | src/noteburst/handlers/external.py | .py | ef7445e20194c533 | 7.15 | 1 |
"""JSON message models for the /v1/ API endpoints."""
import json
from datetime import datetime, timedelta
from enum import Enum
from typing import Annotated, Any
from arq.jobs import JobStatus
from fastapi import Request
from pydantic import AnyHttpUrl, BaseModel, Field
from rubin.nublado.client import (
Noteboo... | lsst-sqre/noteburst | src/noteburst/handlers/v1/models.py | .py | 5ad03f5d95e5e460 | 7.15 | 1 |
"""The main application factory for the noteburst service.
Notes
-----
Be aware that, following the normal pattern for FastAPI services, the app is
constructed when this module is loaded and is not deferred until a function is
called.
"""
import json
from collections.abc import AsyncIterator
from contextlib import as... | lsst-sqre/noteburst | src/noteburst/main.py | .py | 974a3da1d8f9098d | 7.15 | 1 |
"""A script for publishing periodic app metrics."""
import asyncio
from safir.metrics.arq import ArqEvents, publish_queue_stats
from safir.sentry import initialize_sentry
from noteburst import __version__
from .config.metrics import config
initialize_sentry(release=__version__)
def publish_periodic_metrics() -> ... | lsst-sqre/noteburst | src/noteburst/periodic_metrics.py | .py | 7be7c6d0d863e280 | 7.15 | 1 |
"""Management of Science Platform user identity for workers.
Each noteburst worker runs under a unique Science Platform user account. The
account is acquired through a redis-based lock.
"""
from pathlib import Path
from typing import Annotated
import yaml
from pydantic import BaseModel, Field, RootModel
from notebu... | lsst-sqre/noteburst | src/noteburst/worker/identity.py | .py | 04a57c553da7237c | 7.15 | 1 |
"""Noteburst worker lifecycle configuration."""
from datetime import UTC, datetime
from importlib.metadata import version
from typing import Any, ClassVar
import humanize
import structlog
from arq import cron
from rubin.gafaelfawr import GafaelfawrClient
from safir.logging import configure_logging
from safir.metrics.... | lsst-sqre/noteburst | src/noteburst/worker/main.py | .py | eb914e1e9492e4e7 | 7.15 | 1 |
"""Nublado interface."""
import asyncio
from dataclasses import dataclass
from typing import Self
from rubin.gafaelfawr import GafaelfawrClient
from rubin.nublado.client import (
NotebookExecutionResult,
NubladoClient,
NubladoImage,
)
from structlog.stdlib import BoundLogger
from .identity import Identit... | lsst-sqre/noteburst | src/noteburst/worker/nublado.py | .py | d88e34f8676e1f98 | 7.15 | 1 |
"""RSP and Nublado users."""
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Self
from rubin.gafaelfawr import GafaelfawrClient
from noteburst.config.frontend import config
__all__ = ["AuthenticatedUser", "User"]
@dataclass
class User:
"""A Rubin Science Plat... | lsst-sqre/noteburst | src/noteburst/worker/user.py | .py | f599e9cf15a6302a | 7.15 | 1 |
"""Test fixtures for noteburst tests."""
from collections.abc import AsyncGenerator, AsyncIterator
from pathlib import Path
from typing import Any
import pytest
import pytest_asyncio
import respx
import structlog
from asgi_lifespan import LifespanManager
from fastapi import FastAPI
from httpx import ASGITransport, As... | lsst-sqre/noteburst | tests/conftest.py | .py | f9d039953b40a41d | 7.65 | 1 |
# Copyright (C) 2022 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved.
# SPDX-License-Identifier: MIT
#
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, includi... | ansys/ansys-tools-filetransfer | src/ansys/tools/filetransfer/_client.py | .py | 553683a9c144209e | 7 | 0 |
# Copyright (C) 2022 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved.
# SPDX-License-Identifier: MIT
#
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, includi... | ansys/ansys-tools-filetransfer | tests/conftest.py | .py | 42e138be831b8c45 | 7.5 | 0 |
import pickle
import sys
from pathlib import Path
import networkx as nx
from omegaconf import DictConfig
from hydra import compose, initialize
sys.path.append("..")
from tools.graph_sampling_tools import add_one_random_node, combine_far_apart, get_all_sink_cases, get_all_subgraphs, get_longest_path, select_confounder... | owuordickson/gp-mining | benchmark/CausalRiver/generate_datasets.py | .py | 0abbb0f175f635ad | 7.15 | 1 |
__all__ = [
"add_one_random_node",
"combine_far_apart",
"get_all_subgraphs",
"get_all_sink_cases",
"get_longest_path",
"check_corr_character",
"select_confounder_samples",
"all_extensions",
]
import random
from itertools import combinations
import networkx as nx
import numpy as np
# ... | owuordickson/gp-mining | benchmark/CausalRiver/tools/graph_sampling_tools.py | .py | 002f7c828fd559c7 | 7.15 | 1 |
import numpy as np
import pandas as pd
from sklearn.metrics import (
precision_recall_curve,
roc_auc_score,
accuracy_score,
)
# precision recall warning.
np.seterr(divide="ignore", invalid="ignore")
def remove_diagonal(T):
# Takes in 3 dim tensor and removes diagonal of 2/3 dim.
out = []
f... | owuordickson/gp-mining | benchmark/CausalRiver/tools/scoring_tools.py | .py | 695df9e907d21ae9 | 7.15 | 1 |
import numpy as np
import pandas as pd
import pickle
import os
import datetime
from omegaconf import OmegaConf
def remove_trailing_nans(sample_prep):
"""
Removes samples that were not removed by interpolate.
"""
check_trailing_nans = np.where(sample_prep.isnull().values.any(axis=1) == 0)[0]
if not... | owuordickson/gp-mining | benchmark/CausalRiver/tools/tools.py | .py | 87a6939f282cf290 | 7.15 | 1 |
# Import libraries
import numpy as np
# Statistical & Baselines
from scipy.stats import pearsonr
from statsmodels.tsa.stattools import grangercausalitytests
# Tigramite & Graph Learning
from tigramite import data_processing as pp
from tigramite.pcmci import PCMCI
from tigramite.independence_tests.parcorr import ParC... | owuordickson/gp-mining | benchmark/Synthetic/baseline_methods.py | .py | 6b77fd93ef59782e | 7.15 | 1 |
# Import libraries
import numpy as np
import pandas as pd
from sklearn.metrics import precision_recall_fscore_support
def generate_timegraph_mock(length=1000):
"""Simulates a TimeGraph dataset with an explicit lag: X -> Y (lag=2)"""
np.random.seed(42)
X = np.random.normal(0, 1, length)
Y = np.zeros(l... | owuordickson/gp-mining | benchmark/Synthetic/benchmark.py | .py | ccabe4dd98b4e51e | 7.15 | 1 |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
# See the LICENSE file at the root of this
# repository for complete details.
import gc
import time
import numpy as np
from typing import cast
from .graank_base import BaseGrad
from ...gradual_patterns import GI, GP, TGP, PairwiseMatrix
class AntGRAANK(BaseGrad... | owuordickson/gp-mining | src/so4gp/algorithms/base/graank_aco.py | .py | 28f54f9adee591a9 | 7.15 | 1 |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
# See the LICENSE file at the root of this
# repository for complete details.
import copy
import time
import numpy as np
from itertools import combinations
from .graank_base import BaseGrad
from ...data_gp import DataGP
from ...gradual_patterns import GI, GP, TGP... | owuordickson/gp-mining | src/so4gp/algorithms/base/graank_alg.py | .py | 0eca877441eb8da1 | 7.15 | 1 |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
# See the LICENSE file at the root of this
# repository for complete details.
import copy
import random
import numpy as np
from dataclasses import dataclass
from ...data_gp import DataGP
from ...gradual_patterns import GI, GP, TGP
class BaseGrad(DataGP):
@da... | owuordickson/gp-mining | src/so4gp/algorithms/base/graank_base.py | .py | 8124e8ce4dcf05f4 | 7.15 | 1 |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
# See the LICENSE file at the root of this
# repository for complete details.
import time
import random
import numpy as np
from .graank_base import BaseGrad
class GeneticGRAANK(BaseGrad):
def __init__(self, *args, max_iter=1, n_pop=5, pc=0.5, gamma=1.0, mu... | owuordickson/gp-mining | src/so4gp/algorithms/base/graank_ga.py | .py | 2f6b5847d3359b6d | 7.15 | 1 |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
# See the LICENSE file at the root of this
# repository for complete details.
import time
import random
from .graank_base import BaseGrad
class HillClimbingGRAANK(BaseGrad):
def __init__(self, *args, max_iter: int = 1, step_size: float = 0.5, **kwargs):
... | owuordickson/gp-mining | src/so4gp/algorithms/base/graank_hc.py | .py | 58fe6f65895185db | 7.15 | 1 |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
# See the LICENSE file at the root of this
# repository for complete details.
import time
import random
from .graank_base import BaseGrad
class RandomGRAANK(BaseGrad):
def __init__(self, *args, max_iter: int = 1, **kwargs):
"""
Extract grad... | owuordickson/gp-mining | src/so4gp/algorithms/base/graank_rand.py | .py | 9e19a2949062bf19 | 7.15 | 1 |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
# See the LICENSE file at the root of this
# repository for complete details.
import time
import copy
import numpy as np
import pandas as pd
import multiprocessing as mp
from sklearn.cluster import KMeans
from sklearn.preprocessing import MinMaxScaler
from .graan... | owuordickson/gp-mining | src/so4gp/algorithms/base/tgrad.py | .py | 63e1d6fcafc923c8 | 7.15 | 1 |
# SPDX-License-Identifier: MIT
# See the LICENSE file at the root of this
# repository for complete details.
import time
import numpy as np
from sklearn.feature_selection import mutual_info_regression
from .tgrad import TGrad
class TGradAMI(TGrad):
def __init__(self, *args, **kwargs):
"""
Algori... | owuordickson/gp-mining | src/so4gp/algorithms/base/tgrad_ami.py | .py | 4e3dea561384a727 | 7.15 | 1 |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
# See the LICENSE file at the root of this
# repository for complete details.
"""
@author: Dickson Owuor
@credits: Thomas Runkler, Edmond Menya, and Anne Laurent
@license: MIT
@email: owuordickson@gmail.com
@created: 21 July 2021
A collection of miscellaneous cla... | owuordickson/gp-mining | src/so4gp/utils.py | .py | 04a39649bfeda30c | 7.15 | 1 |
"""A continuous flow model exercising rules, a capacity, a sensor and a derating.
The plant is a bottling line:
PUMP --water--> TANK --water--> MIXER --syrup--> BOTTLER
| ^
tank level run (discrete)
| |
... | edgemind-sas/muscadet | examples/continuous_01/continuous_01.py | .py | 8ca1ea9c8dd5a4c7 | 7 | 0 |
"""The continuous example produces the behaviour its narrative claims.
Run from this directory, as the other examples' sibling tests are::
pytest examples/continuous_01
"""
import cod3s
import pytest
#: The solver stops the integration ON a crossing rather than refining it to
#: machine precision, so a date is ... | edgemind-sas/muscadet | examples/continuous_01/test_continuous_01.py | .py | a7561e346b8ca834 | 7.5 | 0 |
"""
This example demonstrates how to create a basic Reliability Block Diagram (RBD) using the MUSCADET BDD framework.
The RBD consists of two source components in parallel, the second will start only if the first one is KO, two block component in parallel and a target component.
The sources produce a functional flow, w... | edgemind-sas/muscadet | examples/datacenter/datacenter_02.py | .py | e1f50ba28396021d | 7 | 0 |
"""Mini datacenter — composite var_prod_cond demonstrator.
A server depends on (power) AND (cooling), where:
- power is at-least-one of two redundant sources (P1, P2);
- cooling is a single mandatory source (C1).
Achieved with ``var_prod_cond=[["power_p1", "power_p2"], ["cooling"]]``
in default inner-mode "or": the o... | edgemind-sas/muscadet | examples/isimu/datacenter_lite.py | .py | 2134a7da66f2469c | 7 | 0 |
"""FlowOut(negate=True) demonstrator.
Two-stage inverter chain: Source -> INV1 -> INV2 -> Target. Each inverter
re-emits the negation of its input flow. As a result the target sees the
*same* value as the source (double inversion), but watching INV1 between
events shows the flip.
This exercises the ``negate=True`` br... | edgemind-sas/muscadet | examples/isimu/inverter_chain.py | .py | 3abb47305c359a68 | 7 | 0 |
"""k/n redundancy demonstrator.
System: 3 sources S1, S2, S3 feeding a target T configured with at-least-2
logic on its single input ``f1``. Each source carries a deterministic
delay failure mode firing at distinct dates so the user can step through
and observe the threshold being crossed.
Flow propagation timeline (... | edgemind-sas/muscadet | examples/isimu/rbd_kn.py | .py | 58bd07bf2114721f | 7 | 0 |
"""
This example demonstrates how to create a basic Reliability Block Diagram (RBD) using the MUSCADET framework.
The RBD consists of a source component, two block components in parallel, and a target component.
The source produces a functional flow, which is propagated through the blocks to the target.
The example als... | edgemind-sas/muscadet | examples/rbd_02/rbd_02.py | .py | 8d79801c0a9b288e | 7 | 0 |
"""
This example demonstrates how to create a basic Reliability Block Diagram (RBD) using the MUSCADET framework.
The RBD consists of a source component, two block components in parallel, and a target component.
The source produces a functional flow, which is propagated through the blocks to the target.
The example als... | edgemind-sas/muscadet | examples/rbd_03/rbd_03.py | .py | 9da5b5ecfb945f9c | 7 | 0 |
"""
This example demonstrates how to create a basic Reliability Block Diagram (RBD) using the MUSCADET framework.
The RBD consists of two source components in parallel, the second will start only if the first one is KO, one block component and a target component.
The sources produce a functional flow, which is propagat... | edgemind-sas/muscadet | examples/rbd_04/rbd_04.py | .py | af9bcc25a0461936 | 7 | 0 |
"""COD3S study system builders provided by muscadet.
Currently exposes :class:`PlatformExportBuilder`, which satisfies the
:class:`cod3s.scripts.builders.SystemBuilder` Protocol so a muscadet
flow system can be plugged into ``cod3s.scripts.study_runner.run_study``
when the model comes from a COD3S Platform JSON export... | edgemind-sas/muscadet | muscadet/builders.py | .py | 9e5f25c7c2504cc6 | 7 | 0 |
import Pycatshoo as pyc
#: Occurrence law of an instantaneous transition: it fires as soon as its
#: condition holds. Every automaton muscadet builds to watch a crossing uses
#: it -- a rule set's mode automaton (R12), a capacity's empty/full bounds
#: (R7) and a discrete production condition's threshold (R22) -- and ... | edgemind-sas/muscadet | muscadet/common.py | .py | c6a0dbef9ea65267 | 7 | 0 |
"""What the failure modes bearing on a continuous output leave of its rate.
A continuous output carries no boolean availability gate: a mode reaches it
through a **derating** instead, a factor in [0, 1] that multiplies what the
rules produced (R18, R19, KD10). The engine is a handful of functions over a
component, whi... | edgemind-sas/muscadet | muscadet/derating.py | .py | 71794fb3b7a5c251 | 7 | 0 |
import logging
from dataclasses import dataclass
from rest_framework.response import Response
from caching.internal_api_client import InternalAPIClient
from cms.topic.models import TopicPage
logger = logging.getLogger(__name__)
@dataclass
class GeographyData:
name: str
geography_type: str
def __eq__(s... | UKHSA-Internal/data-dashboard-api | caching/common/geographies_crawler.py | .py | 2793a5e93a72fd7c | 7.39 | 5 |
from django.db.models import Manager
from cms.common.models import CommonPage
from cms.topic.models import TopicPage
from cms.whats_new.models import WhatsNewChildEntry, WhatsNewParentPage
DEFAULT_TOPIC_PAGE_MANAGER = TopicPage.objects
DEFAULT_COMMON_PAGE_MANAGER = CommonPage.objects
DEFAULT_WHATS_NEW_PARENT_PAGE_MAN... | UKHSA-Internal/data-dashboard-api | caching/common/pages.py | .py | 00cca8d14afa0973 | 7.39 | 5 |
import logging
from collections.abc import Iterator
import requests
from defusedxml import ElementTree
from rest_framework.response import Response
from caching.common.geographies_crawler import (
GeographiesAPICrawler,
GeographyData,
)
from caching.common.pages import get_pages_for_area_selector
from caching... | UKHSA-Internal/data-dashboard-api | caching/frontend/crawler.py | .py | 2bbfaa6f13298e48 | 7.39 | 5 |
import os
from caching.frontend.crawler import FrontEndCrawler
from caching.public_api.handlers import get_cdn_auth_key
class FrontEndURLNotProvidedError(Exception): ...
def _get_frontend_base_url() -> str:
"""Returns the value of the "FRONTEND_URL" environment variable
Returns:
The value of the "... | UKHSA-Internal/data-dashboard-api | caching/frontend/handlers.py | .py | a4a44050253e8f73 | 7.39 | 5 |
from urllib.parse import quote_plus, urljoin
class FrontEndURLBuilder:
"""This is used by the `FrontEndCrawler` to construct URLs to send GET requests to all relevant pages"""
def __init__(self, *, base_url: str):
self._base_url = base_url
def build_url_for_sitemap(self) -> str:
"""Build... | UKHSA-Internal/data-dashboard-api | caching/frontend/urls.py | .py | 388764783804fc3e | 7.39 | 5 |
import logging
import time
from caching.common.geographies_crawler import (
GeographiesAPICrawler,
GeographyData,
)
from caching.private_api.crawler import PrivateAPICrawler
from caching.private_api.crawler.area_selector.concurrency import (
call_with_star_map_multiprocessing,
)
from cms.topic.models impor... | UKHSA-Internal/data-dashboard-api | caching/private_api/crawler/area_selector/orchestration.py | .py | e5bab55e57bef403 | 7.39 | 5 |
import logging
import os
from functools import wraps
from rest_framework.request import Request
from rest_framework.response import Response
from caching.private_api.management import CacheManagement, CacheMissError
from common.request_caching import get_request_caching
logger = logging.getLogger(__name__)
class C... | UKHSA-Internal/data-dashboard-api | caching/private_api/decorators.py | .py | 3ae9e2caae2228e6 | 7.39 | 5 |
import hashlib
import json
from rest_framework.renderers import JSONRenderer
from rest_framework.request import Request
from rest_framework.response import Response
from caching.private_api.client import (
RESERVED_NAMESPACE_KEY_PREFIX,
CacheClient,
InMemoryCacheClient,
)
class CacheMissError(Exception)... | UKHSA-Internal/data-dashboard-api | caching/private_api/management.py | .py | c167ee96b9361f5e | 7.39 | 5 |
#!/usr/bin/env python3
"""Generates release notes for a GitHub release by comparing the current and previous
releases, and fetching the release notes for each component in azimuth-ops."""
import argparse
import base64
import os
import easysemver
import requests
import yaml
API_URL = "https://api.github.com"
COMPONE... | azimuth-cloud/azimuth-config | .github/actions/release-notes/release_notes.py | .py | 7b4f1cd87fc2837f | 7.39 | 5 |
"""Base classes for typed audio effects."""
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, List, Optional
if TYPE_CHECKING:
import numpy as np
class Effect(ABC):
"""Base class for all typed effects.
Subclasses must implement:
- name: The sox effect name
- to_args(): Conve... | shakfu/cysox | src/cysox/fx/base.py | .py | 6a109a15e6c32cb4 | 7.15 | 1 |
"""Format conversion effects (rate, channels, bits)."""
from typing import List, Optional
from .base import Effect
class Rate(Effect):
"""Resample to a different sample rate.
Args:
sample_rate: Target sample rate in Hz.
quality: Resampling quality - 'quick', 'low', 'medium', 'high',
... | shakfu/cysox | src/cysox/fx/convert.py | .py | 9f49d93165b479f5 | 7.15 | 1 |
"""Reverb and spatial effects."""
from typing import List
from .base import Effect
class Reverb(Effect):
"""Add reverberation effect.
Args:
reverberance: Reverb time as percentage 0-100 (default: 50).
hf_damping: High frequency damping percentage 0-100 (default: 50).
room_scale: Roo... | shakfu/cysox | src/cysox/fx/reverb.py | .py | a359bdb7ad0a2da7 | 7.15 | 1 |
"""Volume and gain effects."""
from typing import List, Optional
from .base import Effect
# sox suggests a limiter gain "much less than 1"; 0.05 is its documented example.
DEFAULT_LIMITER_GAIN = 0.05
class Volume(Effect):
"""Adjust volume level.
Args:
db: Volume adjustment in decibels. Positive =... | shakfu/cysox | src/cysox/fx/volume.py | .py | c688530e129401d0 | 7.15 | 1 |
# Version utility functions
def lib_version(major: int, minor: int, patch: int) -> int:
"""Compute a 32-bit integer API version from three 8-bit parts."""
return ((major) << 16) + ((minor) << 8) + (patch)
def lib_version_code() -> int:
"""Get the current libSoX version code."""
return lib_version(14... | shakfu/cysox | src/cysox/utils.py | .py | 3c0c03b1c86c23c1 | 7.15 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.