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
"""Integration tests around Component functionality.""" from typing import AbstractSet, Mapping from ansys.engineeringworkflow.api import Property import ansys.tools.variableinterop as atvi import pytest import ansys.modelcenter.workflow.api as mc_api import ansys.modelcenter.workflow.grpc_modelcenter as grpcmc de...
ansys/pymodelcenter
integration/test_component.py
.py
86813484e51fa48c
7.92
6
"""Integration tests around Engine functionality.""" import os from typing import Collection, Mapping import ansys.engineeringworkflow.api as ewapi import ansys.modelcenter.workflow.api as mcapi import ansys.modelcenter.workflow.grpc_modelcenter as grpcmc def test_can_create_a_new_workflow(engine) -> None: # A...
ansys/pymodelcenter
integration/test_engine.py
.py
b958774ff84eb2de
7.92
6
"""Integration tests around Group functionality.""" from typing import List import unittest import ansys.tools.variableinterop as atvi import pytest import ansys.modelcenter.workflow.api as mcapi @pytest.mark.workflow_name("linked_quadratics.pxcz") def test_can_get_link_information(workflow) -> None: case = un...
ansys/pymodelcenter
integration/test_links.py
.py
46d0ef4fbbf2de01
7.92
6
# 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/pymodelcenter
src/ansys/modelcenter/workflow/api/iassembly.py
.py
692a4a6096b27abf
7.42
6
# 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/pymodelcenter
src/ansys/modelcenter/workflow/api/idatapin.py
.py
530e83880c7468b2
7.42
6
# 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/pymodelcenter
src/ansys/modelcenter/workflow/api/idatapin_link.py
.py
e1b265f9e992ab00
7.42
6
# 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/pymodelcenter
src/ansys/modelcenter/workflow/api/idatapinreferencebase.py
.py
518682e784c7faeb
7.42
6
# 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/pymodelcenter
src/ansys/modelcenter/workflow/api/ireferencearraydatapin.py
.py
f2db44179715c435
7.42
6
import numpy as np import scipy.sparse as sp from pydiso.mkl_solver import ( MKLPardisoSolver as Solver, get_mkl_max_threads, get_mkl_pardiso_max_threads, get_mkl_version, set_mkl_threads, set_mkl_pardiso_threads, ) from concurrent.futures import ThreadPoolExecutor import pytest import sys np.r...
simpeg/pydiso
tests/test_pydiso.py
.py
0c804c897f8b788e
8.14
18
from fastapi import APIRouter, Request from infrastructure.configuration.app import get_app_settings from infrastructure.security import get_limiter router = APIRouter(tags=["System"]) limiter = get_limiter() settings = get_app_settings() # Route53 uses this as a healthcheck every 30 seconds and the alb uses this a...
cds-snc/sre-bot
app/api/routes/system.py
.py
13c90117ce5ddfb8
7.56
12
#!/usr/bin/env python3 """Freeze-baseline guardrail for deprecated `infrastructure.clients` imports. Scans every .py file under app/ (this script's parent directory) for imports of the deprecated `infrastructure.clients` package and compares the result against the checked-in baseline (app/bin/baselines/deprecated_infr...
cds-snc/sre-bot
app/bin/check_deprecated_infra_client_imports.py
.py
da527619ec928991
7.56
12
#!/usr/bin/env python3 """Freeze-baseline guardrail for SDK typing anti-patterns. Scans every .py file under app/integrations/ for retired SDK anti-patterns and compares the result against the checked-in baseline (app/bin/baselines/sdk_typing_antipatterns.txt). Files already in the baseline are grandfathered; any file...
cds-snc/sre-bot
app/bin/check_sdk_typing.py
.py
02848bc6d3c6fe98
7.56
12
"""Sentinel SIEM adapter for audit events. Converts internal AuditEvent records into flat format required by Sentinel. All metadata fields are stringified and prefixed with 'audit_meta_' for queryability in Sentinel's query language. """ from typing import Any from infrastructure.audit.models import AuditEvent cla...
cds-snc/sre-bot
app/infrastructure/audit/adapters/sentinel.py
.py
27734b081944c612
7.56
12
"""AWS Config client implementation. Provides operations to interact with AWS Config service, enabling retrieval of configuration compliance and resource details, with consistent error handling via OperationResult. """ from typing import Any from infrastructure.clients.aws.executor import execute_aws_api_call from i...
cds-snc/sre-bot
app/infrastructure/clients/aws/config.py
.py
f2b4240bd6658655
7.56
12
"""AWS Cost Explorer client implementation. Provides operations to interact with AWS Cost Explorer service, enabling retrieval of cost and usage data with consistent error handling via OperationResult. """ from typing import Any import structlog from infrastructure.clients.aws.executor import execute_aws_api_call f...
cds-snc/sre-bot
app/infrastructure/clients/aws/cost_explorer.py
.py
87f47132263a6159
7.56
12
"""Base AWS client utilities for infrastructure clients. Provides `get_boto3_client` and `execute_aws_api_call` with the OperationResult pattern. This module intentionally avoids reading settings at import time and accepts configuration via parameters. """ import time from collections.abc import Callable from typing ...
cds-snc/sre-bot
app/infrastructure/clients/aws/executor.py
.py
70dc3bf0d247b91c
7.56
12
"""AWS Clients facade for all AWS service operations. Provides attribute-based access to per-service clients (DynamoDB, Identity Store, Organizations, SSO Admin) with consistent error handling and OperationResult return types. Composition-based design: each service has a focused client class, composed together in a l...
cds-snc/sre-bot
app/infrastructure/clients/aws/facade.py
.py
8acf9a8773bf2efd
7.56
12
"""AWS GuardDuty client implementation. Provides operations to interact with AWS GuardDuty service, enabling retrieval of detectors and findings statistics with consistent error handling via OperationResult. """ import structlog from infrastructure.clients.aws.executor import execute_aws_api_call from infrastructure...
cds-snc/sre-bot
app/infrastructure/clients/aws/guard_duty.py
.py
da7eb7b6f76d9ade
7.56
12
"""AWS Health client for checking the health of AWS services. Provides aggregated health check operations for AWS services, enabling monitoring and alerting for service availability and performance issues. """ from collections.abc import Callable, Iterable import structlog from infrastructure.clients.aws.config imp...
cds-snc/sre-bot
app/infrastructure/clients/aws/health.py
.py
a47ec1fd23b36cc3
7.56
12
"""Session provider for AWS client operations. Centralizes boto3 session creation, credential management, and configuration building for all AWS service clients. Handles role assumption and parameter propagation for cross-account access. """ from typing import Any import structlog from infrastructure.clients.aws.ex...
cds-snc/sre-bot
app/infrastructure/clients/aws/session_provider.py
.py
04421da91537fd2b
7.56
12
"""Low-level Google API execution utilities with retry and error handling.""" import time from collections.abc import Callable from typing import Any import structlog from googleapiclient.errors import HttpError from infrastructure.operations.result import OperationResult logger = structlog.get_logger() # Error c...
cds-snc/sre-bot
app/infrastructure/clients/google_workspace/executor.py
.py
807e990e31f91ffc
7.56
12
"""Google Workspace clients facade for all service operations.""" from functools import lru_cache from typing import TYPE_CHECKING import structlog from infrastructure.clients.google_workspace.directory import DirectoryClient from infrastructure.clients.google_workspace.docs import DocsClient from infrastructure.cli...
cds-snc/sre-bot
app/infrastructure/clients/google_workspace/facade.py
.py
af5abf333c96121c
7.56
12
"""Google Workspace session provider for authentication and service creation.""" import json import structlog from google.oauth2 import service_account from googleapiclient.discovery import Resource, build logger = structlog.get_logger() class SessionProvider: """Manages Google Workspace API authentication and...
cds-snc/sre-bot
app/infrastructure/clients/google_workspace/session_provider.py
.py
e63c99f772361ea8
7.56
12
"""MaxMind GeoIP2 client for geolocation operations. Provides type-safe access to MaxMind GeoIP2 database with consistent error handling and OperationResult return types. """ from dataclasses import dataclass from functools import cache from typing import TYPE_CHECKING import geoip2.database import structlog from ge...
cds-snc/sre-bot
app/infrastructure/clients/maxmind/client.py
.py
98473694f8614795
7.56
12
"""Application-level settings and singleton provider.""" from functools import lru_cache from typing import Literal from pydantic import Field, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict class AppSettings(BaseSettings): """App-level settings including CORS policy while Securi...
cds-snc/sre-bot
app/infrastructure/configuration/app.py
.py
f41bdd143931bce3
7.56
12
"""ATIP feature settings.""" from functools import lru_cache from pydantic import Field from infrastructure.configuration.base import FeatureSettings class AtipSettings(FeatureSettings): """ATIP (Access to Information and Privacy) feature configuration. Environment Variables: ATIP_ANNOUNCE_CHANNEL...
cds-snc/sre-bot
app/infrastructure/configuration/features/atip.py
.py
c5cd0c19f835965b
7.56
12
"""AWS operations feature settings.""" from functools import lru_cache from pydantic import Field from infrastructure.configuration.base import FeatureSettings class AWSFeatureSettings(FeatureSettings): """AWS operations feature configuration. Environment Variables: AWS_ADMIN_GROUPS: List of admin...
cds-snc/sre-bot
app/infrastructure/configuration/features/aws_ops.py
.py
68ee90796a67a59d
7.56
12
"""Groups module feature settings.""" import json from functools import lru_cache from typing import Any import structlog from pydantic import Field, field_validator from infrastructure.configuration.base import FeatureSettings logger = structlog.get_logger().bind(component="config.groups") class GroupsFeatureSet...
cds-snc/sre-bot
app/infrastructure/configuration/features/groups.py
.py
a16c2939ae59ef27
7.56
12
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the...
OpenVoiceOS/ovos-utils
ovos_utils/__init__.py
.py
6610132a81746c0d
7.42
6
from functools import lru_cache, wraps from time import monotonic_ns from typing import Callable, Optional, Any class classproperty(property): """ A decorator for creating a class-level property. Credit to Denis Rhyzhkov on Stackoverflow: https://stackoverflow.com/a/13624858/1280629 Example: ...
OpenVoiceOS/ovos-utils
ovos_utils/decorators.py
.py
f4efd4951bd4a077
7.42
6
import os from os.path import join, isdir from typing import List from ovos_utils.log import LOG from ovos_bus_client.util import wait_for_reply from ovos_utils.system import is_installed, has_screen, is_process_running _default_gui_apps = ( "ovos-gui-app", "ovos-shell", "mycroft-gui-app", "mycroft-em...
OpenVoiceOS/ovos-utils
ovos_utils/gui.py
.py
e2545354553ac69e
7.42
6
import json from copy import copy def nested_get(base, key_list): """Access a nested object in base by item sequence.""" if not len(key_list): return None val = copy(base) for key in key_list: if key not in val: return None val = val[key] return val def nested...
OpenVoiceOS/ovos-utils
ovos_utils/json_helper.py
.py
2d4ceda1e574e1c3
7.42
6
import warnings from os import listdir from os.path import isdir, join from typing import Optional from ovos_utils.file_utils import resolve_resource_file from ovos_utils.log import deprecated from ovos_utils.version import VERSION_MAJOR @deprecated("use 'standardize_lang' from 'ovos_spec_tools' instead", ...
OpenVoiceOS/ovos-utils
ovos_utils/lang/__init__.py
.py
8518282ddf73cf69
7.42
6
import time class Stopwatch: """ Simple time measuring class. """ def __init__(self): self.timestamp = None self.time = None def start(self): """ Start a time measurement """ self.time = None self.timestamp = time.time() def la...
OpenVoiceOS/ovos-utils
ovos_utils/metrics.py
.py
0aaee5d17852d86f
7.42
6
import re from difflib import SequenceMatcher from enum import IntEnum, auto from ovos_utils.log import LOG try: import rapidfuzz except ImportError: rapidfuzz = None class MatchStrategy(IntEnum): SIMPLE_RATIO = auto() RATIO = auto() PARTIAL_RATIO = auto() TOKEN_SORT_RATIO = auto() TOKEN...
OpenVoiceOS/ovos-utils
ovos_utils/parse.py
.py
52aac3699d44ad9a
7.42
6
import os import platform import random import string from os import makedirs from os.path import exists, join from socket import gethostname import pexpect from ovos_utils.log import LOG, deprecated from ovos_utils.version import VERSION_MAJOR try: # pycryptodomex from Cryptodome.Cipher import AES except Im...
OpenVoiceOS/ovos-utils
ovos_utils/security.py
.py
5e79cb944c61e4d0
7.42
6
from typing import Any, Set from ovos_bus_client.util import wait_for_reply def get_non_properties(obj: Any) -> Set[str]: """Get attributes that are not properties from object. Will return members of object class along with bases down to MycroftSkill. Args: obj: object to scan Returns: ...
OpenVoiceOS/ovos-utils
ovos_utils/skills.py
.py
605358155dca66f8
7.42
6
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from smtplib import SMTP_SSL from typing import Optional from ovos_utils.log import LOG def send_smtp( user: str, pswd: str, sender: str, destinatary: str, subject: str, contents: str, host: str, port:...
OpenVoiceOS/ovos-utils
ovos_utils/smtp_utils.py
.py
c288652d93d87bd4
7.42
6
import os import subprocess import wave from copy import deepcopy from os.path import isfile from typing import Optional from shutil import which from ovos_utils.log import LOG try: from ovos_config.config import read_mycroft_config except ImportError: LOG.warning("Config not provided and ovos_config not ava...
OpenVoiceOS/ovos-utils
ovos_utils/sound.py
.py
03e473711556bc49
7.42
6
# Copyright © 2016-2021 Scott Stevenson <scott@stevenson.io> # # Permission to use, copy, modify, and/or distribute this software for # any purpose with or without fee is hereby granted, provided that the # above copyright notice and this permission notice appear in all # copies. # # THE SOFTWARE IS PROVIDED "AS IS" AN...
OpenVoiceOS/ovos-utils
ovos_utils/xdg_utils.py
.py
5278475e7e191546
7.42
6
# Copyright (c) 2025-2026 University of Bern. All rights reserved. import numpy as np def paired_point_matching(source, target): """ Calculates the transformation T that maps the source to the target point clouds. :param source: A N x 3 matrix with N 3D points. :param target: A N x 3 matrix with N 3D p...
persmed/cas-assignment
assignments/registration/registration.py
.py
8c14324728396216
7.42
6
import argparse import glob import os import platform import shutil import subprocess import sys import textwrap def find_exe(name: str) -> str: """Find an actual executable target Given the name of an executable, find the actual path to use. Parameters ---------- name : str The undecorat...
ansys/pyensight
doc/make.py
.py
b28334cf475609c4
7.52
10
"""Sphinx documentation configuration file.""" from datetime import datetime import json import os import sys from ansys.pyensight.core import VERSION as __version__ from ansys_sphinx_theme import ansys_favicon, get_version_match from sphinx_gallery.sorting import FileNameSortKey sys.path.insert(0, os.path.join(os.p...
ansys/pyensight
doc/source/conf.py
.py
9355d33df40ded7b
7.52
10
import json import logging import os import platform import subprocess import sys import tempfile from typing import Optional import uuid import carb.settings import omni.ext import omni.kit.app import omni.kit.pipapi """ The current kit leverages an EnSight installation. It can find this via environmental variable/...
ansys/pyensight
exts/ansys.tools.omniverse.core/ansys/tools/omniverse/core/extension.py
.py
fc62f7721f5c85b1
7.52
10
# Copyright (C) 2022 - 2026 ANSYS, Inc. and/or its affiliates. # 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, including without limita...
ansys/pyensight
src/ansys/pyensight/core/common.py
.py
58db919199123af8
7.52
10
# Copyright (C) 2022 - 2026 ANSYS, Inc. and/or its affiliates. # 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, including without limita...
ansys/pyensight
src/ansys/pyensight/core/ensobj.py
.py
3b94625b821547a0
7.52
10
# Copyright (C) 2022 - 2026 ANSYS, Inc. and/or its affiliates. # 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, including without limita...
ansys/pyensight
src/ansys/pyensight/core/launch_ensight.py
.py
d78607279b80e834
7.52
10
# Copyright (C) 2022 - 2026 ANSYS, Inc. and/or its affiliates. # 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, including without limita...
ansys/pyensight
src/ansys/pyensight/core/utils/adr.py
.py
9bb89edc5452d51d
7.52
10
# Copyright (C) 2022 - 2026 ANSYS, Inc. and/or its affiliates. # 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, including without limita...
ansys/pyensight
src/ansys/pyensight/core/utils/readers.py
.py
332b40184dad97e9
7.52
10
# Copyright (C) 2022 - 2026 ANSYS, Inc. and/or its affiliates. # 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, including without limita...
ansys/pyensight
src/ansys/pyensight/core/utils/support.py
.py
9076e57efe1ddbce
7.52
10
""" Adding OIDC authentication to the project. References: https://gitlab.com/nsf-muses/calculation-engine/-/blob/main/app/app_base/auth_backends.py """ from mozilla_django_oidc.auth import OIDCAuthenticationBackend from django.conf import settings from django.core.exceptions import ObjectDoesNotExist import u...
scimma/blast
app/app/auth_backend.py
.py
caef0974ec417f75
7.45
7
import os import sys from pathlib import Path import json # TODO: Redundant definitions of global config variables should be avoided, but we # cannot currently run in a Django shell *before* initializing the data files. # from django.conf import settings CUTOUT_ROOT = os.getenv("CUTOUT_ROOT", "/data/cutout_cdn") ...
scimma/blast
app/entrypoints/initialize_data.py
.py
28e32d2b4cfd9cee
7.45
7
from astropy.coordinates import Angle from astropy.coordinates import SkyCoord from astropy.io.votable import parse from astroquery.vizier import Vizier def catalog_photometry(position, catalog, search_radius=Angle(1.0, unit="arcsec")): """ Downloads catalog photometry for the closest match within a given sea...
scimma/blast
app/host/catalog_photometry.py
.py
d7976863342efed0
7.45
7
import functools import re from django.utils import timezone from django.conf import settings # from .models import ExternalResourceCall from .models import UsageMetricsLog import json from textwrap import shorten # def log_resource_call(resource_name): # """ # Decorator which saves metadata about a call to ...
scimma/blast
app/host/decorators.py
.py
81992af335459cc2
7.45
7
#!/usr/bin/python3 # -*- coding: utf-8 -*- import argparse import logging import re import sys from typing import Optional import pymysql from pymysql.cursors import Cursor import yaml BATCH_SIZE = 300 def extract_dbnames(qtext: str, qdb: str, regex, db_regex) -> Optional[str]: """ Attempt to determine th...
toolforge/quarry
maintenance/multiinstance_migration.py
.py
57e8e597fdacec53
7.66
20
from sqlalchemy import Column, Integer, Unicode, ForeignKey, DateTime from sqlalchemy.orm import relationship from .base import Base from .query import Query # noqa class QueryRevision(Base): __tablename__ = "query_revision" id = Column(Integer, primary_key=True) text = Column(Unicode(4096)) query_d...
toolforge/quarry
quarry/web/models/queryrevision.py
.py
d41d295f6455199e
7.66
20
class RangeBasedPagination(object): """ Generic range based pagination. """ def __init__( self, queryset, page_key, limit, base_url, referrer_url=None, get_params={}, ): """ Instantiate RangeBasedPagination. Args: ...
toolforge/quarry
quarry/web/utils/pagination.py
.py
6349a6a90abb2353
7.66
20
from datetime import datetime, timedelta from flask import Blueprint templatehelpers = Blueprint("templatehelpers", __name__) def get_pretty_delay(diff: timedelta, suffix="", default="just now"): """ Returns string representing "time since" e.g. 3 days ago, 5 hours ago etc. From http://flask.pocoo.o...
toolforge/quarry
quarry/web/webhelpers.py
.py
392f45701b0bb9fe
7.66
20
import pytest from mock_alchemy.mocking import UnifiedAlchemyMagicMock # @pytest.mark.usefixtures([mocker, client]) class TestLogin: @pytest.fixture(autouse=True) def setup_method(self, mocker, client): # mock_alchemy is not great at understanding post data; # to work around we use string ID...
toolforge/quarry
tests/test_login.py
.py
2efd4adf38936f66
7.16
20
from datetime import datetime import json import pytest from mock_alchemy.mocking import UnifiedAlchemyMagicMock from quarry.web.models.query import Query from quarry.web.models.queryrevision import QueryRevision from quarry.web.models.queryrun import QueryRun from quarry.web.models.user import User class TestQuery...
toolforge/quarry
tests/test_query.py
.py
d649858bcb907768
7.16
20
from datetime import datetime import pytest from mock_alchemy.mocking import UnifiedAlchemyMagicMock from quarry.web.models.query import Query from quarry.web.models.star import Star from quarry.web.models.queryrevision import QueryRevision from quarry.web.models.queryrun import QueryRun from quarry.web.models.user i...
toolforge/quarry
tests/test_results.py
.py
41b2d60195c10a12
7.16
20
from datetime import datetime import json import pytest from mock_alchemy.mocking import UnifiedAlchemyMagicMock from quarry.web.models.query import Query from quarry.web.models.queryrevision import QueryRevision from quarry.web.models.queryrun import QueryRun from quarry.web.models.user import User # @pytest.mark....
toolforge/quarry
tests/test_run.py
.py
6a40adc53850463a
7.16
20
from datetime import datetime import pytest from sqlalchemy import func from mock_alchemy.mocking import UnifiedAlchemyMagicMock from quarry.web.models.query import Query from quarry.web.models.star import Star from quarry.web.models.queryrevision import QueryRevision from quarry.web.models.queryrun import QueryRun f...
toolforge/quarry
tests/test_user.py
.py
9e537f775ae24470
7.16
20
import itertools import threading from abc import ABC, abstractmethod from collections.abc import Iterator from typing import Any, NoReturn import requests from bigc.exceptions import ( BadGatewayError, BigCommerceException, BigCommerceNetworkError, GatewayTimeoutError, InternalServerError, Se...
MedShift/bigc
src/bigc/api_client.py
.py
770caadcf9fdbdd5
7.5
9
from __future__ import annotations import inspect from typing import Any, ClassVar _status_code_exc_class_map: dict[int, type[BigCommerceException]] = {} class BigCommerceException(Exception): """Base exception class for BigCommerce API errors.""" DEFAULT_MESSAGE: ClassVar[str] = 'Request to BigCommerce fa...
MedShift/bigc
src/bigc/exceptions.py
.py
55217ddd01b240aa
7.5
9
from collections.abc import Iterator from typing import Any from bigc.api_client import BigCommerceV2APIClient class BigCommerceCurrenciesV2API: def __init__(self, api: BigCommerceV2APIClient): self._api = api def all( self, *, params: dict[str, Any] | None = None, ti...
MedShift/bigc
src/bigc/resources/currencies_v2.py
.py
d52c1a81a5e290ee
7.5
9
from collections.abc import Iterator from typing import Any from bigc.api_client import BigCommerceV3APIClient from bigc.exceptions import DoesNotExistError class BigCommerceOrdersV3API: def __init__(self, api: BigCommerceV3APIClient): self._api = api def get_refund_quote( self, orde...
MedShift/bigc
src/bigc/resources/orders_v3.py
.py
777a1609fdb93a47
7.5
9
from collections.abc import Iterator from typing import Any from bigc.api_client import BigCommerceV3APIClient class BigCommercePricingV3API: def __init__(self, api: BigCommerceV3APIClient): self._api = api def get_pricing( self, data: dict[str, Any], *, timeout: floa...
MedShift/bigc
src/bigc/resources/pricing_v3.py
.py
75802dbdb0c1cbe9
7.5
9
import atexit import logging import os import re import sys import textwrap from functools import lru_cache from importlib.metadata import EntryPoint, entry_points from importlib.util import find_spec from typing import Any, Callable, Dict, Iterable, List, Literal, Optional, Union from semantic_version import SimpleSp...
SpeysideHEP/spey
src/spey/__init__.py
.py
94a7c76d7e6bb3de
7.52
10
"""Configuration class for Statistical Models""" import copy from dataclasses import dataclass from typing import Dict, List, Optional, Tuple, Union @dataclass class ModelConfig: r""" Container to hold certain properties of the backend and statistical model. This will ensure the consistency of the comput...
SpeysideHEP/spey
src/spey/base/model_config.py
.py
9d54ff0edba492f7
7.52
10
"""Tools for computing confidence level and pvalues at the asymptotic limit""" from typing import List, Tuple from .distributions import AsymptoticTestStatisticsDistribution from .utils import expected_pvalues, pvalues __all__ = ["compute_asymptotic_confidence_level"] def __dir__(): return __all__ def comput...
SpeysideHEP/spey
src/spey/hypothesis_testing/asymptotic_calculator.py
.py
6c2df0da6525d931
8.02
10
""" Test statistic distributions Similar implementation can be found in https://github.com/scikit-hep/pyhf/blob/main/src/pyhf/infer/calculators.py """ import numpy as np from scipy.stats import norm __all__ = ["AsymptoticTestStatisticsDistribution", "EmpricTestStatisticsDistribution"] def __dir__(): return __a...
SpeysideHEP/spey
src/spey/hypothesis_testing/distributions.py
.py
334b810cba4c179c
7.02
10
"""Functions for computation of test statistic""" import logging import warnings from typing import Callable, Tuple import numpy as np from spey.system.exceptions import AsimovTestStatZero, UnknownTestStatistics __all__ = ["qmu", "qmu_tilde", "q0", "get_test_statistic", "compute_teststatistics"] log = logging.getL...
SpeysideHEP/spey
src/spey/hypothesis_testing/test_statistics.py
.py
b4f37d1ed659c073
7.02
10
from typing import List, Text, Tuple import numpy as np from .distributions import EmpricTestStatisticsDistribution from .utils import expected_pvalues, pvalues __all__ = ["compute_toy_confidence_level"] def __dir__(): return __all__ def compute_toy_confidence_level( signal_like_test_statistic: List[floa...
SpeysideHEP/spey
src/spey/hypothesis_testing/toy_calculator.py
.py
b5872cb28ddaa631
8.02
10
"""Tools for computing upper limit on parameter of interest""" import logging from collections import deque from functools import partial from typing import Callable, List, Literal, Optional, Tuple, Union import numpy as np import scipy from spey.hypothesis_testing.test_statistics import compute_teststatistics from ...
SpeysideHEP/spey
src/spey/hypothesis_testing/upper_limits.py
.py
5511261a049c1d09
8.02
10
""" Routines for computing pvalues Similar implementation can be found in https://github.com/scikit-hep/pyhf/blob/main/src/pyhf/infer/calculators.py """ import warnings from typing import List, Tuple, Union import numpy as np from .distributions import ( AsymptoticTestStatisticsDistribution, EmpricTestStati...
SpeysideHEP/spey
src/spey/hypothesis_testing/utils.py
.py
ba3cd3e4bda4eaf8
8.02
10
import logging from dataclasses import dataclass from typing import Any, List, Dict from .core import fit __all__ = ["fit"] log = logging.getLogger("Spey") @dataclass class ValidateOpts: """ Whitelist filter for optimiser keyword options. Used by :mod:`spey.optimizer.scipy_tools` and :mod:`spey.op...
SpeysideHEP/spey
src/spey/optimizer/__init__.py
.py
01d30624f6de0e57
7.52
10
"""Optimisation tools based on scipy""" import logging import warnings from typing import Callable, Dict, List, Tuple import numpy as np import scipy from . import ValidateOpts # pylint: disable=W1201, W1203, R0913 log = logging.getLogger("Spey") _scipy_opts = ValidateOpts( opt_list=["method", "maxiter", "dis...
SpeysideHEP/spey
src/spey/optimizer/scipy_tools.py
.py
bc00213e8a6145fb
7.52
10
"""Logging style for spey""" import logging import sys from contextlib import contextmanager # pylint: disable=C0103 class ColoredFormatter(logging.Formatter): """Coloured logging formatter for spey. Wraps the standard :class:`logging.Formatter` with ANSI escape sequences keyed on log level so spey outp...
SpeysideHEP/spey
src/spey/system/logger.py
.py
a5745ad5662ab90c
7.52
10
import json import logging import pathlib from datetime import datetime, timezone from platform import python_version from typing import Literal import requests from semantic_version import SimpleSpec, Version from spey._version import __version__ log = logging.getLogger("Spey") __all__ = ["get_bibtex", "check_upda...
SpeysideHEP/spey
src/spey/system/webutils.py
.py
a37a3dc53575ab41
7.52
10
from enum import Enum, auto __all__ = ["ExpectationType"] # pylint: disable=C0103 class ExpectationType(Enum): """ Expectation type has been used to determine the nature of the statistical model through out the package. It consists of three main arguments: * :obj:`~spey.ExpectationType.observed...
SpeysideHEP/spey
src/spey/utils.py
.py
85e4e206174e143b
7.52
10
import types import numpy as np import pytest from spey.base import backend_base class SimpleBackend(backend_base.BackendBase): """Minimal concrete BackendBase implementation for testing defaults.""" def config(self, allow_negative_signal: bool = True, poi_upper_bound: float = 10.0): return types.S...
SpeysideHEP/spey
tests/test_backend_base.py
.py
1632b802be035a68
7.02
10
"""Test asymptotic calculator""" import numpy as np from spey.hypothesis_testing.asymptotic_calculator import ( compute_asymptotic_confidence_level, ) from spey.hypothesis_testing.toy_calculator import compute_toy_confidence_level def test_compute_asymptotic_confidence_level(): """Test asymptotic CL compute...
SpeysideHEP/spey
tests/test_cls_computer.py
.py
db710910182c6e1a
8.02
10
import numpy as np import types import pytest from spey.optimizer import core as core_mod class FakeModelConfig: def __init__(self, suggested_init, poi_index=0, suggested_fixed=None): self.suggested_init = list(suggested_init) self.poi_index = poi_index self.suggested_fixed = ( ...
SpeysideHEP/spey
tests/test_core_fit.py
.py
fb60df07309feb42
7.02
10
import numpy as onp import math import pytest from spey.backends.distributions import ( Poisson, Normal, MultivariateNormal, MainModel, ConstraintModel, MixtureModel, ) def test_poisson_expected_and_logprob_and_sample(): # negative loc gets clipped to small positive value p = Poisson...
SpeysideHEP/spey
tests/test_distributions.py
.py
f72cb659e18cbae2
7.02
10
"""Example: the `numeric` subpackage for large-scale / numerical work. Install with `pip install 'gale-shapley-algorithm[numeric]'` to pull in numpy. This demonstrates: - Running Gale-Shapley on int16 rank matrices (both men-optimal and women-optimal). - Checking stability of an arbitrary matching. - Enumeratin...
oedokumaci/gale-shapley-algorithm
examples/numeric_usage.py
.py
929fd98225f84651
7.5
9
"""Pydantic request/response models for the API.""" from typing import Self from pydantic import BaseModel, model_validator class MatchingRequest(BaseModel): """Request body for matching endpoints.""" proposer_preferences: dict[str, list[str]] responder_preferences: dict[str, list[str]] @model_val...
oedokumaci/gale-shapley-algorithm
src/gale_shapley_algorithm/_api/models.py
.py
10fbb518acfcf6d6
7.5
9
"""API route handlers.""" from fastapi import APIRouter from gale_shapley_algorithm._api.models import MatchingRequest, MatchingResponse, StepsResponse from gale_shapley_algorithm._api.step_through import _build_matching_response, run_step_through from gale_shapley_algorithm.matching import _build_algorithm from gale...
oedokumaci/gale-shapley-algorithm
src/gale_shapley_algorithm/_api/routes.py
.py
5a6bbd30b91bac79
7.5
9
"""Step-through execution of the Gale-Shapley algorithm, capturing per-round state.""" from gale_shapley_algorithm._api.models import ( MatchingResponse, ProposalAction, RoundStep, StepsResponse, ) from gale_shapley_algorithm.matching import _build_algorithm from gale_shapley_algorithm.person import Re...
oedokumaci/gale-shapley-algorithm
src/gale_shapley_algorithm/_api/step_through.py
.py
ddaf8d03992df6bc
7.5
9
"""Command line application module for Gale-Shapley algorithm.""" import random from typing import TYPE_CHECKING import typer from gale_shapley_algorithm._cli import console from gale_shapley_algorithm._cli.display import display_preferences, display_results from gale_shapley_algorithm._cli.prompts import ( prom...
oedokumaci/gale-shapley-algorithm
src/gale_shapley_algorithm/_cli/app.py
.py
7cd63c174d6efeda
7.5
9
"""Rich output formatting for the CLI.""" from typing import TYPE_CHECKING from rich.table import Table from gale_shapley_algorithm._cli import console if TYPE_CHECKING: from gale_shapley_algorithm.result import MatchingResult, StabilityResult def display_preferences( proposer_side: str, responder_sid...
oedokumaci/gale-shapley-algorithm
src/gale_shapley_algorithm/_cli/display.py
.py
b1c5f091ccc7066c
7.5
9
"""Interactive prompt functions for the CLI.""" from rich.prompt import IntPrompt, Prompt from gale_shapley_algorithm._cli import console def prompt_side_names() -> tuple[str, str]: """Prompt for proposer and responder side names. Returns: Tuple of (proposer_side_name, responder_side_name). """...
oedokumaci/gale-shapley-algorithm
src/gale_shapley_algorithm/_cli/prompts.py
.py
d2fcb6f6dc5e0c7b
7.5
9
"""Algorithm module.""" from dataclasses import dataclass from typing import Final from gale_shapley_algorithm.person import Proposer, Responder from gale_shapley_algorithm.result import MatchingResult @dataclass(slots=True) class Algorithm: """Gale-Shapley Algorithm class. Uses slots for memory efficiency...
oedokumaci/gale-shapley-algorithm
src/gale_shapley_algorithm/algorithm.py
.py
490e223e0ab11707
7.5
9
"""Convenience function for creating matchings.""" from gale_shapley_algorithm.algorithm import Algorithm from gale_shapley_algorithm.person import Proposer, Responder from gale_shapley_algorithm.result import MatchingResult def _build_algorithm( proposer_preferences: dict[str, list[str]], responder_preferen...
oedokumaci/gale-shapley-algorithm
src/gale_shapley_algorithm/matching.py
.py
6ce01632a28ab4ae
7.5
9
"""Numpy Gale-Shapley deferred acceptance on rank matrices.""" from __future__ import annotations from collections.abc import Callable, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING try: import numpy as np except ImportError as e: # pragma: no cover raise ImportError( "...
oedokumaci/gale-shapley-algorithm
src/gale_shapley_algorithm/numeric/gs.py
.py
8675f69b62acbf08
7.5
9
"""Vectorized stability checks for rank-matrix matchings.""" from __future__ import annotations from typing import TYPE_CHECKING try: import numpy as np except ImportError as e: # pragma: no cover raise ImportError( "The `numeric` subpackage requires numpy. Install with `pip install gale-shapley-alg...
oedokumaci/gale-shapley-algorithm
src/gale_shapley_algorithm/numeric/stability.py
.py
5fc994a2f01077c4
7.5
9
"""Person module. Creates the units in the matching environment. Person class is also the base class for Proposer and Responder classes. """ from __future__ import annotations class Person: """Person class, base class for Proposer and Responder.""" def __init__(self, name: str, side: str) -> None: ...
oedokumaci/gale-shapley-algorithm
src/gale_shapley_algorithm/person.py
.py
67a6d8446fdf9f1d
7.5
9
"""Result types for the Gale-Shapley algorithm.""" from dataclasses import dataclass @dataclass(frozen=True) class MatchingResult: """Result of running the Gale-Shapley algorithm.""" rounds: int matches: dict[str, str] unmatched: list[str] self_matches: list[str] all_matched: bool @datacla...
oedokumaci/gale-shapley-algorithm
src/gale_shapley_algorithm/result.py
.py
aeb1e8c7ceaf380f
7.5
9
"""Stability analysis for matchings.""" from gale_shapley_algorithm.algorithm import Algorithm from gale_shapley_algorithm.person import Proposer, Responder from gale_shapley_algorithm.result import StabilityResult def is_individually_rational(proposers: list[Proposer], responders: list[Responder]) -> bool: """C...
oedokumaci/gale-shapley-algorithm
src/gale_shapley_algorithm/stability.py
.py
d358a245b2873ca2
7.5
9
"""Tests for the algorithm module.""" from gale_shapley_algorithm.algorithm import Algorithm from gale_shapley_algorithm.person import Proposer, Responder from gale_shapley_algorithm.result import MatchingResult class TestAlgorithmProperties: """Tests for Algorithm properties.""" def test_persons_property( ...
oedokumaci/gale-shapley-algorithm
tests/algorithm_test.py
.py
42c5d5895a904a5c
7
9