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 |
|---|---|---|---|---|---|---|
"""Campaign モデルのバリデーション・unique・url プロパティのテスト。"""
from django.db import IntegrityError
from django.test import TestCase, override_settings
from community.models import Community
from analytics.models import Campaign
@override_settings(SITE_URL='https://vrc-ta-hub.example')
class CampaignModelTest(TestCase):
@cla... | noricha-vr/vrc-ta-hub | app/analytics/tests/test_campaign_model.py | .py | cc01c9e50ba11160 | 8.13 | 17 |
"""Campaign CRUD view の権限境界テスト。
他集会のキャンペーンを一覧で見られないこと、直接 URL でも 404 になることを担保する。
"""
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from community.models import Community, CommunityMember
from analytics.models import Campaign
User = get_user_model()
... | noricha-vr/vrc-ta-hub | app/analytics/tests/test_campaign_views.py | .py | ca2e746a079fc867 | 8.13 | 17 |
"""アクセス解析ダッシュボードのテスト。
権限境界、期間切替、CSV出力、集計関数の正当性を検証する。
他人の community のデータが漏洩しないことを `source_medium` の識別子で直接確認する。
"""
import csv
import io
from datetime import date, timedelta
from django.test import TestCase, Client
from django.urls import reverse
from django.utils import timezone
from community.models import Community... | noricha-vr/vrc-ta-hub | app/analytics/tests/test_dashboard.py | .py | 740072aaba3cd51d | 8.13 | 17 |
"""ga4_client._build_client の資格情報フォールバックテスト。
ローカル開発: GOOGLE_APPLICATION_CREDENTIALS ファイルから読み込む。
Cloud Run 等: ファイル不在なら compute_engine 資格情報(metadata server 経由)。
"""
from datetime import date
from unittest.mock import MagicMock, patch
from django.test import TestCase, override_settings
from analytics import ga4_client
... | noricha-vr/vrc-ta-hub | app/analytics/tests/test_ga4_client.py | .py | 2339c9b5d7086405 | 7.13 | 17 |
from datetime import date
from django.test import TestCase
from community.models import Community
from event.models import Event, EventDetail
from analytics.models import Campaign, PageAnalytics
from analytics.path_resolver import resolve_page_path
class ResolvePagePathTest(TestCase):
@classmethod
def setU... | noricha-vr/vrc-ta-hub | app/analytics/tests/test_path_resolver.py | .py | 97010c9cb076c9e5 | 8.13 | 17 |
"""Phase 2 #10 #11 のテスト(未紐付けトラフィック / ポスタークリック)。"""
from datetime import timedelta
from unittest.mock import patch
from django.test import Client, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from analytics import services
from analytics.models import PageAnalytics, Pos... | noricha-vr/vrc-ta-hub | app/analytics/tests/test_phase2.py | .py | 26c319f8821c7168 | 8.13 | 17 |
"""QR コード PNG 生成ヘルパーのテスト。"""
from django.test import TestCase
from analytics.qr_generator import generate_qr_png
class GenerateQrPngTest(TestCase):
def test_returns_png_content_file(self):
cf = generate_qr_png('https://vrc-ta-hub.example/?utm_campaign=test')
# PNG マジックバイト
self.assertTrue(... | noricha-vr/vrc-ta-hub | app/analytics/tests/test_qr_generator.py | .py | 798ebfc1c8725c8b | 8.13 | 17 |
from datetime import timedelta
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.test import TestCase
from django.utils import timezone
from community.models import Community, CommunityMember
from analytics.models import PageAnalytics
from analytics impor... | noricha-vr/vrc-ta-hub | app/analytics/tests/test_services.py | .py | 6d3593483e62724d | 7.13 | 17 |
"""キャンペーン集計サービスのテスト。"""
from datetime import timedelta
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.utils import timezone
from community.models import Community, CommunityMember
from analytics import services
from analytics.models import Campaign, PageAnalytics
User = ... | noricha-vr/vrc-ta-hub | app/analytics/tests/test_services_campaign.py | .py | 234878e593d4d071 | 8.13 | 17 |
"""集計期間の境界値テスト(前日基準・当日除外)。
GA4 同期は午前1時に前日分までしか取得しないため、集計対象は
「前日(today-1) から遡った N 日間」= today-N 〜 today-1 のちょうど N 日。
当日(today) は集計に含めない。timezone.localdate() を固定して境界を厳密に検証する。
このファイルは「当日除外・N日ぴったり」仕様の正本テスト。他アプリの集計テストは
前日にデータを置く前提に揃えてあり当日除外そのものは検証しないため、本ファイルを
削除・縮小すると当日除外の回帰保証が失われる点に注意。
"""
from datetime import date, timed... | noricha-vr/vrc-ta-hub | app/analytics/tests/test_services_date_boundary.py | .py | 2faf3c2da2c62f38 | 8.13 | 17 |
from datetime import date, timedelta
from unittest.mock import patch
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from community.models import Community
from analytics.models import Campaign, PageAnalytics
TEST_TOKEN = 'test-request-token'
@... | noricha-vr/vrc-ta-hub | app/analytics/tests/test_sync.py | .py | 65b7c7e8e42c9729 | 8.13 | 17 |
"""GA4 アクセス解析の同期 view。
前日分(または指定日)のページ別アクセスデータを GA4 から取得し、
pagePath を内部コンテンツに紐付けて PageAnalytics に冪等に蓄積する。
"""
import logging
import secrets
from datetime import date, datetime, timedelta
from django.conf import settings
from django.db import transaction
from django.http import HttpResponse
from django.utils import ti... | noricha-vr/vrc-ta-hub | app/analytics/views.py | .py | b14eafdd58063c99 | 7.63 | 17 |
import logging
from django.utils import timezone
from rest_framework import authentication
from rest_framework import exceptions
from user_account.models import APIKey
logger = logging.getLogger(__name__)
# クライアントへ返す公開エラーコード。期限切れ・IP拒否・無効ユーザーを区別しないのは、
# 「そのキー自体は実在する」ことを攻撃者に教えないため(メッセージ統一と同じ理由)。
# 失敗の内訳は logger 側にだけ残... | noricha-vr/vrc-ta-hub | app/api_v1/authentication.py | .py | 6435778d5610d000 | 7.63 | 17 |
"""API v1 viewset の共通基底クラス。"""
import logging
from typing import Any
from django.db import connections
from django.db.utils import OperationalError
from rest_framework import status
from rest_framework.response import Response
logger = logging.getLogger(__name__)
# DB 再接続にも失敗した 503 のエラーコード。
DATABASE_UNAVAILABLE_COD... | noricha-vr/vrc-ta-hub | app/api_v1/base.py | .py | 5d42ebc91646a7a8 | 7.63 | 17 |
"""API v1 共通の DRF 例外ハンドラ。
DRF 標準のハンドラはレスポンス body に ``detail`` しか載せず、``ErrorDetail.code``
(機械可読なエラー種別)はクライアントへ届かない。ここで ``code`` を付与し、
API v1 のエラー契約を ``{"detail": "...", "code": "..."}`` に統一する。
既存クライアント互換のため **既存フィールドは削除・改名しない**(追加のみ)。
ValidationError のフィールド別エラー辞書もキーはそのまま維持し、
``detail`` / ``code`` を衝突しない場合だけ追記する。
"""
... | noricha-vr/vrc-ta-hub | app/api_v1/exception_handler.py | .py | dd2ab8ca94cf2319 | 7.63 | 17 |
"""api_v1 request body validation schemas (Pydantic)
既存 DRF Serializer は output (to_representation) でそのまま使い、
input validation のみ Pydantic に統一する。
エラーメッセージは既存 API レスポンス互換のため、日本語固定文字列で返す。
View 側は ValidationError をキャッチして既存の {"success": False, "error": "..."}
フォーマットに変換する。
このモジュールが ``schemas.py`` ではなく ``input_schemas.py``... | noricha-vr/vrc-ta-hub | app/api_v1/input_schemas.py | .py | e44d5f5f1926f0a5 | 7.63 | 17 |
import logging
from django.utils.deprecation import MiddlewareMixin
from user_account.models import APIKey
from .models import APIRequestLog
logger = logging.getLogger(__name__)
_API_PREFIX = '/api/v1/'
_PATH_MAX = 500
_UA_MAX = 500
_IP_MAX = 64
def _client_ip(request) -> str:
xff = request.META.get('HTTP_X_... | noricha-vr/vrc-ta-hub | app/api_v1/middleware.py | .py | 37acf171a5e2713a | 7.63 | 17 |
"""定期イベントプレビューAPI
request body validation は Pydantic (api_v1.input_schemas.RecurrencePreviewInput) に統一。
既存応答形式 {"success": bool, "error": str, "dates": [...], "count": int} は維持しつつ、
機械可読な {"detail": str, "code": str} を追加する(既存クライアント互換のため追加のみ)。
"""
import logging
from pydantic import ValidationError
from rest_framework.... | noricha-vr/vrc-ta-hub | app/api_v1/recurrence_preview.py | .py | 986f8cab635114dc | 7.63 | 17 |
"""Nox sessions."""
import os
import shlex
import shutil
import sys
from pathlib import Path
from textwrap import dedent
import nox
try:
from nox import Session
from nox import session
except ImportError:
message = f"""\
Nox failed to import.
Please install it using the following command:
{... | TGSAI/segy | noxfile.py | .py | 9eb5d82e5d534d6a | 7.59 | 14 |
"""Normalization logic for header field names."""
from rapidfuzz import process
from rapidfuzz.fuzz import WRatio
from segy.alias.segyio import SEGYIO_BIN_FIELD_MAP
from segy.alias.segyio import SEGYIO_TRACE_FIELD_MAP
from segy.alias.seis_unix import SEIS_UNIX_TRACE_FIELD_MAP
from segy.exceptions import InvalidFieldE... | TGSAI/segy | src/segy/alias/core.py | .py | b85a3316af64f328 | 7.59 | 14 |
"""Custom array interface.
We subclass NumPy ndarray with some methods to enrich it for
better use experience. Like dictionary or JSON dumps for
structured arrays.
See here for details:
https://numpy.org/doc/stable/user/basics.subclassing.html
"""
from __future__ import annotations
from copy import copy
from json i... | TGSAI/segy | src/segy/arrays.py | .py | 7f3a87749efedc1a | 7.59 | 14 |
"""SEG-Y parser configuration."""
from __future__ import annotations
from collections.abc import Mapping # noqa: TCH003
from typing import Any
from pydantic import Field
from pydantic_settings import BaseSettings
from pydantic_settings import SettingsConfigDict
from segy.schema import Endianness # noqa: TCH001
... | TGSAI/segy | src/segy/config.py | .py | f87e422748faaff5 | 7.59 | 14 |
"""SEG-Y library exceptions."""
class SegyError(Exception):
"""Base class for all exceptions in this library."""
class SegyFileSpecMismatchError(SegyError):
"""Raised when file spec with parsed fields don't match file size."""
class EndiannessInferenceError(SegyError):
"""Raised when endianness infere... | TGSAI/segy | src/segy/exceptions.py | .py | 65a2fcc94a00cb2c | 7.59 | 14 |
"""Factory methods for SEG-Y file creation."""
from __future__ import annotations
import logging
from datetime import UTC
from datetime import datetime
from typing import TYPE_CHECKING
from typing import cast
import numpy as np
from segy.arrays import HeaderArray
from segy.arrays import TraceArray
from segy.constan... | TGSAI/segy | src/segy/factory.py | .py | c20770607275f32a | 7.59 | 14 |
"""Low-level floating point conversion operations."""
from __future__ import annotations
from typing import TYPE_CHECKING
from typing import Any
import numba as nb
import numpy as np
if TYPE_CHECKING:
from collections.abc import Callable
from numpy.typing import NDArray
NDArrayUint32 = NDArray[np.uint... | TGSAI/segy | src/segy/ibm.py | .py | 19e6848683f14704 | 7.59 | 14 |
"""Utilities to extract information from the SEG-Y files.
We have the following inference options:
1. Endianness inference
2. Revision interpretation
3. Textual file header encoding inference
"""
from __future__ import annotations
import logging
import sys
from dataclasses import dataclass
from enum import Enum
from... | TGSAI/segy | src/segy/inference.py | .py | 323d4ccf409b5334 | 7.59 | 14 |
"""Core functionality for SEG-Y ninja templates."""
from __future__ import annotations
from abc import abstractmethod
from enum import StrEnum
from typing import TYPE_CHECKING
from typing import Literal
from typing import cast
from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic.alias_generat... | TGSAI/segy | src/segy/schema/base.py | .py | 07b00352e3848c80 | 7.59 | 14 |
"""Data format specification representing scalar and trace data types."""
from __future__ import annotations
from enum import StrEnum
from typing import TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from typing import Any
class ScalarType(StrEnum):
"""A class representing scalar data types."""
I... | TGSAI/segy | src/segy/schema/format.py | .py | 0b29f2dcf955d828 | 7.59 | 14 |
"""Specification representing header fields and headers."""
from __future__ import annotations
from collections import Counter
from typing import Any
import numpy as np
from pydantic import Field
from pydantic import field_validator
from pydantic import model_validator
from segy.schema.base import BaseDataType
from... | TGSAI/segy | src/segy/schema/header.py | .py | d050dd7924f4c9aa | 7.59 | 14 |
"""Data model implementations for SEG-Y file spec."""
from __future__ import annotations
from enum import Enum
from typing import TYPE_CHECKING
from pydantic import Field
from pydantic import model_validator
from segy.schema.base import CamelCaseModel
if TYPE_CHECKING:
from segy.schema.base import Endianness
... | TGSAI/segy | src/segy/schema/segy.py | .py | 0b4a0d218365f2e1 | 7.59 | 14 |
"""Classes for managing headers and header groups."""
from __future__ import annotations
from typing import Any
import numpy as np
from pydantic import Field
from segy.ebcdic import ASCII_TO_EBCDIC
from segy.ebcdic import EBCDIC_TO_ASCII
from segy.schema.base import BaseDataType
from segy.schema.format import Scala... | TGSAI/segy | src/segy/schema/text_header.py | .py | e35f46f92a60e270 | 7.59 | 14 |
"""Data model implementations for trace specification."""
from __future__ import annotations
from typing import TYPE_CHECKING
from typing import Any
import numpy as np
from pydantic import Field
from pydantic import model_validator
from segy.schema.base import BaseDataType
if TYPE_CHECKING:
from segy.schema.ba... | TGSAI/segy | src/segy/schema/trace.py | .py | 48363353babc1108 | 7.59 | 14 |
"""Metadata and attribute encoding for headers in the SEG-Y standard."""
from enum import IntEnum
class SegyEndianCode(IntEnum):
"""Enumeration for endianness indicator from raw SEG-Y bytes.
SEG-Y Revision 2 defines byte range 3297-3300 with an integer
constant (32-bit) for unambiguous detection of file... | TGSAI/segy | src/segy/standards/codes.py | .py | d7be2723c0a09d78 | 7.59 | 14 |
"""Base tuple and enum definitions for SEG-Y standard definitions."""
from __future__ import annotations
from collections import namedtuple
from enum import Enum
from segy.schema import HeaderField
FieldTuple = namedtuple("FieldTuple", ["byte", "format"])
class SegStandardEnum(FieldTuple, Enum):
"""A special ... | TGSAI/segy | src/segy/standards/fields/base.py | .py | f8be8f4010ad7176 | 7.59 | 14 |
"""SEG-Y binary header definitions."""
from segy.standards.fields.base import SegStandardEnum
# fmt: off
class Rev0(SegStandardEnum):
"""Definition of SEG-Y Rev0 binary headers."""
JOB_ID = (1, "int32")
LINE_NUM = (5, "int32")
REEL_NUM ... | TGSAI/segy | src/segy/standards/fields/binary.py | .py | e788e0644b64ea24 | 7.59 | 14 |
"""SEG-Y trace header definitions."""
from segy.standards.fields.base import SegStandardEnum
# fmt: off
class Rev0(SegStandardEnum):
"""Definition of SEG-Y Rev0 trace headers."""
TRACE_SEQ_NUM_LINE = (1, "int32")
TRACE_SEQ_NUM_REEL = (5, "int32")
ORIG_FIELD_RECORD_NUM = (9, "... | TGSAI/segy | src/segy/standards/fields/trace.py | .py | 72d94ff6a796f475 | 7.59 | 14 |
"""Implements a registry for various SEG-Y standards."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from segy.schema import SegySpec
logger = logging.getLogger(__name__)
segy_standard_registry = {}
def register_segy_standard(version_or_name: float |... | TGSAI/segy | src/segy/standards/registry.py | .py | 52f245698466d184 | 7.59 | 14 |
"""Transforms to apply to arrays and structured arrays."""
from __future__ import annotations
import logging
import sys
from abc import abstractmethod
from typing import TYPE_CHECKING
import numpy as np
from numpy.lib import recfunctions as rfn
from segy.inference import interpret_revision
from segy.schema import S... | TGSAI/segy | src/segy/transforms.py | .py | 75306563e85b5e3a | 7.59 | 14 |
"""Shared fixtures for tests."""
from __future__ import annotations
import pytest
from fsspec.implementations.memory import MemoryFileSystem
from segy.factory import get_default_text
from segy.schema import HeaderField
from segy.schema import HeaderSpec
from segy.schema import ScalarType
from segy.standards import g... | TGSAI/segy | tests/conftest.py | .py | 9706a54ae0dc521d | 8.09 | 14 |
"""Tests for accessors for SegyArrays."""
from __future__ import annotations
import pytest
from segy.accessors import TraceAccessor
from segy.schema import Endianness
from segy.schema import HeaderField
from segy.schema import HeaderSpec
from segy.schema import ScalarType
from segy.schema import TraceDataSpec
from s... | TGSAI/segy | tests/test_accessors.py | .py | 2713d1c5a2447932 | 8.09 | 14 |
"""Test Numpy array subclasses."""
import numpy as np
import pytest
from segy.arrays import HeaderArray
from segy.arrays import SegyArray
from segy.exceptions import InvalidFieldError
from segy.exceptions import NonSpecFieldError
def test_segy_array_copy() -> None:
"""Test copying a segy array with exact underl... | TGSAI/segy | tests/test_arrays.py | .py | ffbb5ca7cbaad969 | 8.09 | 14 |
"""Tests for the CLI."""
from __future__ import annotations
import os
import pytest
from typer.testing import CliRunner
from segy.cli.segy import app
runner = CliRunner()
@pytest.fixture
def s3_path() -> str:
"""Fixture for Stratton dataset on S3 (SEG Wiki)."""
return "s3://open.source.geoscience/open_da... | TGSAI/segy | tests/test_cli.py | .py | ec56f92a21a22f16 | 8.09 | 14 |
"""Tests for IBM and IEEE floating point conversions.
Some references for test values
https://en.wikipedia.org/wiki/IBM_hexadecimal_floating-point
https://www.crewes.org/Documents/ResearchReports/2017/CRR201725.pdf
"""
import numpy as np
import pytest
from segy.ibm import ibm2ieee
from segy.ibm import ibm2ieee_singl... | TGSAI/segy | tests/test_ibm_float.py | .py | 88edbe9d27e60cea | 8.09 | 14 |
"""Tests for indexing.
The indexer classes are tested via the `SegyFile` tests so no
need to test it here.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
import pytest
from segy.indexing import bounds_check
from segy.indexing import merge_cat_file
if TYPE_CHECKING:
... | TGSAI/segy | tests/test_indexing.py | .py | 43d14437d292c9c1 | 8.09 | 14 |
"""Test the inference utilities that are not covered via SegyFile."""
from __future__ import annotations
import numpy as np
from segy.ebcdic import ASCII_TO_EBCDIC
from segy.inference import infer_text_header_encoding
from segy.schema import TextHeaderEncoding
ROWS = 40
COLS = 80
def make_text(rows: int = ROWS) -... | TGSAI/segy | tests/test_inference.py | .py | c8088bfdc8a22a96 | 8.09 | 14 |
"""Tests for components that define fields and data types of a SEGY Schema."""
from __future__ import annotations
import pytest
from segy.schema import Endianness
from segy.schema import HeaderField
from segy.schema import HeaderSpec
from segy.schema import ScalarType
class TestHeaderSpec:
"""Tests for header ... | TGSAI/segy | tests/test_schema_data_type.py | .py | 9c73efb065ade84d | 8.09 | 14 |
"""Tests for segy spec components."""
import numpy as np
import pytest
from segy.schema import HeaderField
from segy.schema import ScalarType
from segy.schema import SegySpec
from segy.schema import TextHeaderEncoding
from segy.schema import TextHeaderSpec
from segy.schema import TraceDataSpec
from segy.schema.text_h... | TGSAI/segy | tests/test_schema_segy.py | .py | 5fdb222bef56cee3 | 8.09 | 14 |
"""Tests for HeaderField and HeaderSpec."""
from __future__ import annotations
import numpy as np
import pytest
from pydantic import ValidationError
from segy.schema import Endianness
from segy.schema import HeaderField
from segy.schema import HeaderSpec
from segy.schema import ScalarType
class TestHeaderField:
... | TGSAI/segy | tests/test_schema_struct_header.py | .py | de342c4c80601998 | 8.09 | 14 |
"""Tests for HeaderField and HeaderSpec helpers."""
from __future__ import annotations
from typing import TypeAlias
import pytest
from segy.schema import ScalarType
from segy.schema.header import HeaderField
from segy.schema.header import _validate_non_overlapping_fields
from segy.schema.header import ranges_overla... | TGSAI/segy | tests/test_schema_struct_header_helpers.py | .py | c2c34fdc619a1074 | 8.09 | 14 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
import asyncio
from logging.config import fileConfig
from alembic import context
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from horizon.backend.d... | MTSWebServices/horizon | horizon/backend/db/migrations/env.py | .py | e9eaa14d68c0b85c | 7.52 | 10 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
"""Add user table
Revision ID: b91de692624e
Revises:
Create Date: 2023-10-09 18:32:01.037500
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "b91de692624e"
down_revision = No... | MTSWebServices/horizon | horizon/backend/db/migrations/versions/2023-10-09_b91de692624e_.py | .py | 908d3a83cbb0f1c0 | 7.52 | 10 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
"""Add namespace table
Revision ID: e29b66594970
Revises: b91de692624e
Create Date: 2023-10-13 12:24:06.942579
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "e29b66594970"
d... | MTSWebServices/horizon | horizon/backend/db/migrations/versions/2023-10-13_e29b66594970_.py | .py | f192e493b88ec60a | 7.52 | 10 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
"""Add hwm table
Revision ID: edd2e353ca38
Revises: e29b66594970
Create Date: 2023-10-16 19:10:26.499633
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "edd2e353ca38"
down_re... | MTSWebServices/horizon | horizon/backend/db/migrations/versions/2023-10-16_edd2e353ca38_.py | .py | ac1ff72dc931cc35 | 7.52 | 10 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
"""Add hwm_history table
Revision ID: 6b9001985cd2
Revises: edd2e353ca38
Create Date: 2023-10-19 14:48:41.934231
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "6b9001985cd2"... | MTSWebServices/horizon | horizon/backend/db/migrations/versions/2023-10-19_6b9001985cd2_.py | .py | 5a94f577688a9167 | 7.52 | 10 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
"""Add credentials_cache table
Revision ID: dfce9f35c00e
Revises: 6b9001985cd2
Create Date: 2023-11-24 12:45:37.006395
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "dfce9f3... | MTSWebServices/horizon | horizon/backend/db/migrations/versions/2023-11-24_dfce9f35c00e_.py | .py | 8efa11dcc2bbe6a6 | 7.52 | 10 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
"""Add action to HWMHistory table
Revision ID: c2d6da81f9ec
Revises: 4bc3fffc0209
Create Date: 2024-02-22 15:47:40.155259
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "c2d6da81f9ec"
down_revision ... | MTSWebServices/horizon | horizon/backend/db/migrations/versions/2024-02-22_c2d6da81f9ec_.py | .py | af1fb637242bed67 | 7.52 | 10 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
"""Drop is_deleted column from user
Revision ID: 2452f82ae06c
Revises: 5c7a5c5a193b
Create Date: 2024-02-27 14:55:54.744041
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "24... | MTSWebServices/horizon | horizon/backend/db/migrations/versions/2024-02-27_2452f82ae06c_.py | .py | ac1c522c1f1d0a5d | 7.52 | 10 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
"""Add namespace history
Revision ID: 5c7a5c5a193b
Revises: c2d6da81f9ec
Create Date: 2024-02-27 13:25:07.367475
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "5c7a5c5a193b"... | MTSWebServices/horizon | horizon/backend/db/migrations/versions/2024-02-27_5c7a5c5a193b_.py | .py | e68b989e0e3970d2 | 7.52 | 10 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
"""Add owner_id to namespace
Revision ID: 09be8fd79dbc
Revises: 2452f82ae06c
Create Date: 2024-02-29 11:22:25.802243
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "09be8fd79... | MTSWebServices/horizon | horizon/backend/db/migrations/versions/2024-02-29_09be8fd79dbc_.py | .py | f974888f1d34dff0 | 7.52 | 10 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
"""Add namespace_user table
Revision ID: 4c60578f3f1d
Revises: 09be8fd79dbc
Create Date: 2024-03-01 11:30:36.778975
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "4c60578f3f1... | MTSWebServices/horizon | horizon/backend/db/migrations/versions/2024-03-01_4c60578f3f1d_.py | .py | 3dc8f82f97133b8f | 7.52 | 10 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
"""Add is_admin to User
Revision ID: ec64f7b42221
Revises: 4c60578f3f1d
Create Date: 2024-03-18 15:59:19.680251
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "ec64f7b42221"
... | MTSWebServices/horizon | horizon/backend/db/migrations/versions/2024-03-18_ec64f7b42221_.py | .py | 8f2110698d6073b5 | 7.52 | 10 |
# SPDX-FileCopyrightText: 2025-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
"""Drop user.is_active
Revision ID: 30798436c3fe
Revises: ec64f7b42221
Create Date: 2026-08-11 17:09:35.191305
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "30798436c3fe"
d... | MTSWebServices/horizon | horizon/backend/db/migrations/versions/2026-08-11_30798436c3fe_.py | .py | d2e16aadbdb3eb5a | 7.52 | 10 |
# _*_ coding: utf-8 _*_
"""跨页共用的小格式化函数。
放这里的门槛是"三个以上互不相干的调用点":结果页的明细表、结果池的来源列、
策略优选的重放窗口标签都要把同一个值渲染成同一种样子。它们原本分散挂在
``BacktestApp`` 上,页面拆成各自的 Mixin 之后就没有共同的归属了——Mixin 里的
``@staticmethod`` 拿不到 ``self``,也就够不着别的 Mixin 上的同类函数。
调用方仍写 ``BacktestApp._format_detail_index(...)``:类里按同名 staticmethod
别名暴露。
"""
import os
import ... | Grefer/DeltaLab | deltalab_ui/formatting.py | .py | 96ebb6f59d81f3a1 | 7.6 | 15 |
# _*_ coding: utf-8 _*_
"""界面主题:matplotlib 后端、中文字体、配色、左侧表单的统一度量。
本模块在 **import 期**就把全局绘图环境配好(后端 → 字体 → rcParams),并
提供一组无状态的表单布局助手。它不 import 项目里的任何其他模块,因此界面
层任何一处都能安全引入,不会形成环。
import 顺序是有意的:``matplotlib.use()`` 必须早于 ``import
matplotlib.pyplot``。后端选择因此放在本模块最顶部——只要谁先 import 了
``deltalab_ui.theme``,后端就已经定死,其余模块再 import p... | Grefer/DeltaLab | deltalab_ui/theme.py | .py | ddbb4d7c011d16cb | 7.6 | 15 |
# _*_ coding: utf-8 _*_
"""与具体页面无关的 Tk 控件小工具。
两个都是"挂上去就不用再管"的行为增强:让标签的折行宽度跟随实际槽位,以及
给控件挂一个轻量悬浮提示。三个页面都在用,而它们是 ``@staticmethod``——页面
各自成 Mixin 之后,Mixin 里的静态方法拿不到 ``self``,够不着别的 Mixin 上的
同类函数,所以下沉到这里。
调用方仍写 ``BacktestApp._attach_tooltip(...)``:类里按同名 staticmethod
别名暴露,测试也一直是这么调的。
"""
import tkinter as tk
from deltalab... | Grefer/DeltaLab | deltalab_ui/widgets.py | .py | 12271cd3811e1a33 | 7.6 | 15 |
# _*_ coding: utf-8 _*_
"""Wind 取数区间、交易日历倒推与行情粒度解析。
这一层全是纯函数:输入是 GUI 收集出来的 state dict,输出是补齐了起止日期与
实际 BarSize 的 state dict,中间不碰任何 tkinter 控件。抽出来的直接动机是它
们本来就是 ``BacktestApp`` 上的一堆 ``@staticmethod``——挂在窗口类上只是历史
原因,测试也一直绕开实例直接按类名调用。
调用方仍写 ``BacktestApp._resolve_wind_bar_size(...)``:类里按同名
staticmethod 别名暴露,与 ``history_sel... | Grefer/DeltaLab | deltalab_ui/wind_resolve.py | .py | f1e2a95e8cc854c8 | 7.6 | 15 |
# _*_ coding: utf-8 _*_
"""
Created on 1月 29 13:59 2024
@author: Grefer
"""
import time
import numpy as np
try:
from .constants import ANNUAL_DAYS
from .mc_engine import McGbmQ
from .option_base import OptionBase
except ImportError:
from constants import ANNUAL_DAYS
from mc_engine import McGbmQ
... | Grefer/DeltaLab | pricing/Option_AS.py | .py | da50fe28316c6d08 | 7.6 | 15 |
# _*_ coding: utf-8 _*_
"""
Created on 12月 20 11:05 2023
@author: Grefer
"""
from scipy.stats import norm
from math import log, sqrt, exp
try:
from .constants import ANNUAL_DAYS
from .option_base import OptionBase
except ImportError:
from constants import ANNUAL_DAYS
from option_base import OptionBase... | Grefer/DeltaLab | pricing/Option_Vanilla.py | .py | 8727ee46eb01bebe | 7.6 | 15 |
# _*_ coding: utf-8 _*_
"""
滚动历史回测驱动器(Phase 3)
给定一个期权配置和一条 Wind 历史行情,按固定步长向前滚动:
在每个窗口上用事前 HV 构造期权实例,分别跑
1) 真实历史路径(path_source="historical")
2) 同 σ 生成的一条 GBM 对照路径(path_source="gbm")
并将两边的对冲 PnL、离散化误差等汇总到一张 DataFrame。
语义说明(与 from_wind / from_csv 对齐):
- 历史价格保留真实水平(不再 rebase 到 option_cfg['s0'])。
- option_cfg['s0'... | Grefer/DeltaLab | pricing/rolling_backtest.py | .py | b793a6f46da30018 | 7.1 | 15 |
# _*_ coding: utf-8 _*_
"""
交易日历模块(离线优先)
提供 A 股交易日序列,解析顺序:
1) 本地缓存文件 data/tradingday.csv(或 pricing/tradingday.csv)—— 纯离线,默认路径
2) akshare(免费公开数据源,非 Wind 接口)—— 文件缺失/不够新时刷新
3) WindPy —— 最后兜底
成功联网获取后会回写本地文件,之后即可纯离线使用。
仓库已预置 data/tradingday.csv(覆盖至 2026 年底)。到期日超出文件范围且联网
刷新失败时**直接报错**,不再沿用覆盖不足的旧文件——旧行为(对齐原 MATL... | Grefer/DeltaLab | pricing/trade_calendar.py | .py | 6e08994bc2bcaf1e | 7.6 | 15 |
"""全局测试夹具。
这里只放**必须在每个测试上自动生效**的隔离。需要显式声明的夹具留在各测试
文件里(例如 ``history_store_dir``)。
"""
from __future__ import annotations
import pytest
import backtest_pool_store
import history_bar_cache
import history_store
@pytest.fixture(autouse=True)
def isolate_backtest_pool(tmp_path, monkeypatch):
"""把回测结果池的落盘目录指向临时目录。
... | Grefer/DeltaLab | tests/conftest.py | .py | 7e257763119f3c4b | 8.1 | 15 |
# _*_ coding: utf-8 _*_
"""CSV 数据源的导入引导:模板、表头探测与「价格列」候选联动。
这一组守的是**新用户第一次用 CSV 能不能跑通**:模板必须是 ``from_csv`` 直接
读得进的格式(表头写错一个字,用户拿到的就是一份跑不通的样例),表头探测必须
在选文件时就把可用列摆出来,而不是等回测跑到一半从 ``from_csv`` 抛
「列 X 不在 CSV 中」。
不打 ``gui`` 标记:模板与表头是纯函数,控件联动那几条用 ``SimpleNamespace``
假 self 调类级方法,都不需要窗口服务器。
"""
from __future__ import annotatio... | Grefer/DeltaLab | tests/test_csv_import_guide.py | .py | 912621e8e567e9c1 | 8.1 | 15 |
"""左侧参数面板的滚轮行为。
回归背景:面板原来用 ``<Enter>``/``<Leave>`` 动态挂载 ``bind_all`` 滚轮。指针
只要从 Canvas 挪到面板里任意子控件(LabelFrame / Label / Entry / Combobox…)
上,Canvas 就收到 ``<Leave>`` 把滚轮解绑——而参数区表面几乎全被子控件盖住,
于是「鼠标停在参数上滚轮没反应,只有压着右侧滚动条才滚得动」。
这里不模拟真实指针(无头环境下的坐标命中不稳),而是替换 ``winfo_containing``
直接指定指针下的控件,专门盯住「按控件归属判断是否滚面板」这段逻辑。
"""
from __futu... | Grefer/DeltaLab | tests/test_gui_left_panel_scroll.py | .py | 697d4e45cd0913ca | 8.1 | 15 |
"""分段 bar 级结果的磁盘缓存。
两条底线:命中必须与重跑**逐位一致**(差一点点就等于给用户看假数据),
输入变了必须 miss(宁可重跑 620 ms,也不能读到不匹配的结果)。
"""
from __future__ import annotations
import copy
import os
from dataclasses import replace
import numpy as np
import pandas as pd
import pytest
import history_bar_cache as cache
from pricing import (CloseToCloseStrateg... | Grefer/DeltaLab | tests/test_history_bar_cache.py | .py | 0a805d7ebcc948ed | 8.1 | 15 |
import sys
import adios2
import numpy as np
def is_inside_same_side(p: np.ndarray, a: np.ndarray, b: np.ndarray, c: np.ndarray) -> bool:
"""
Checks if a point p is inside the triangle defined by vertices a, b, and c.
This uses the "same-side" technique, which is computationally efficient.
Args:
... | UT-CHG/SWEMniCS | examples/postprocess.py | .py | 98307e983325de7e | 7.59 | 14 |
"""Utility script to convert ADCIRC mesh information into a format usable by FEniCS."""
import ufl
import numpy as np
from dolfinx import io,fem,mesh,cpp,plot
from mpi4py import MPI
import sys
import adios4dolfinx
from constants import R
import argparse as ap
import json
import os
try:
from dolfinx.fem import func... | UT-CHG/SWEMniCS | src/swemnics/ADCIRC_2_FENICS.py | .py | 795f5f0c68e2e0d9 | 7.59 | 14 |
"""
Classes for testcases arising from ADCIRC input files.
Specifically, these classes enable tidal potential forcing, reading boundary conditions from a file, and reading the binary files produced by ADCIRC_2_FENICS.py.
"""
from swemnics import problems as Problems
from mpi4py import MPI
from dataclasses import data... | UT-CHG/SWEMniCS | src/swemnics/adcirc_problem.py | .py | d69fcaf28deb6ca5 | 7.59 | 14 |
"""Handling of boundary conditions and facet tags.
"""
from dolfinx import fem as fe
import dolfinx.mesh as mesh
from ufl import (div, as_tensor, as_vector, inner, dx,ds,Measure)
import numpy as np
class BoundaryCondition:
"""A class describing a boundary condition.
"""
def __init__(self, type, marker, f... | UT-CHG/SWEMniCS | src/swemnics/boundarycondition.py | .py | e9322f7befa1f1c8 | 7.59 | 14 |
"""Classes for meteorological forcing.
Currently only OceanWeather-esque (gridded) forcing is supported, and must be provided in an HDF5 file.
"""
from dolfinx import fem as fe
from swemnics.constants import R
import numpy as np
class GriddedForcing:
"""Supports meteorological forcing on a regular lat/lon grid"... | UT-CHG/SWEMniCS | src/swemnics/forcing.py | .py | 68ca2c61a3b23655 | 7.59 | 14 |
"""
Custom Newton solver for general nonlinear variational problems.
This was implemented because more control was desired over the Newton iteration than provided by the built-in NonlinearProblem class.
"""
from dolfinx import fem as fe, nls, log,geometry,io,cpp
import dolfinx.fem.petsc as petsc
import ufl
from mpi4... | UT-CHG/SWEMniCS | src/swemnics/newton.py | .py | 36943ab41d5b0e7b | 7.59 | 14 |
from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Optional
from .nb_types import Nb, PathOrStr
__all__ = [
"get_nb_names",
"get_nb_names_from_list",
"is_notebook",
"read_nb",
"write_nb",
]
def read_nb(path: PathOrStr) -> Nb | None:
"""Read ... | ayasyrev/nbmetaclean | src/nbmetaclean/helpers.py | .py | 18efef9f17a4e7c1 | 7.54 | 11 |
from __future__ import annotations
from pathlib import Path
import subprocess
import pytest
from nbmetaclean.helpers import read_nb, write_nb
from nbmetaclean.version import __version__
def run_app(
nb_path: Path,
args: list[str] = [],
) -> tuple[str, str]:
"""run app"""
run_result = subprocess.run... | ayasyrev/nbmetaclean | tests/test_app_check.py | .py | 9d8d9b4477518c6f | 7.04 | 11 |
from __future__ import annotations
from pathlib import Path
import subprocess
from nbmetaclean.helpers import read_nb, write_nb
def run_app(
nb_path: Path | list[Path] | None = None,
args: list[str] | None = None,
cwd: Path | None = None,
) -> tuple[str, str]:
"""run app"""
args = args or []
... | ayasyrev/nbmetaclean | tests/test_app_clean.py | .py | 52fbc3edc78168ec | 7.04 | 11 |
from nbmetaclean.check import check_nb_ec, check_nb_errors, check_nb_warnings
from nbmetaclean.helpers import read_nb
def test_check_nb_ec():
"""test check_nb_ec"""
# base notebook - no execution_count
test_nb = read_nb("tests/test_nbs/test_nb_3_ec.ipynb")
result = check_nb_ec(test_nb)
assert not ... | ayasyrev/nbmetaclean | tests/test_check.py | .py | b0d68001823470f3 | 7.04 | 11 |
import copy
import os
from pathlib import Path
from pytest import CaptureFixture
from nbmetaclean.clean import (
NB_METADATA_PRESERVE_MASKS,
CleanConfig,
clean_cell,
clean_nb,
clean_nb_file,
filter_meta_mask,
filter_metadata,
)
from nbmetaclean.helpers import read_nb, write_nb
def test_g... | ayasyrev/nbmetaclean | tests/test_clean.py | .py | 67400d06936ce7cc | 7.04 | 11 |
from pathlib import Path
from nbmetaclean.helpers import get_nb_names, get_nb_names_from_list, is_notebook
def test_is_notebook():
"""test is_notebook"""
assert is_notebook(Path("tests/test_nbs/test_nb_1.ipynb"))
assert not is_notebook(Path("tests/test_nbs/test_nb_1.py"))
assert not is_notebook(Path(... | ayasyrev/nbmetaclean | tests/test_get_nbnames.py | .py | 13539d1d436913ef | 7.04 | 11 |
from pathlib import Path
from nbmetaclean.helpers import read_nb, write_nb
def test_read_nb():
"""test read notebook"""
file = Path("tests/test_nbs/test_nb_1.ipynb")
nb = read_nb(file)
assert isinstance(nb, dict)
assert nb["metadata"]["language_info"] == {"name": "python"}
assert nb["metadata... | ayasyrev/nbmetaclean | tests/test_read_write.py | .py | 45456794d0f32846 | 8.04 | 11 |
import datetime
from typing import Annotated
import bcrypt
import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy import select
from sqlalchemy.orm import Session
from advanced.config import settings
from advanced.database import get_db
from adv... | mirpo/fastapi-gen | packages/template-advanced/src/advanced/auth.py | .py | 113513bcce4f72e2 | 7.56 | 12 |
from sqlalchemy import Boolean, Column, DateTime, Integer, String
from sqlalchemy.sql import func
from advanced.database import Base
class User(Base):
"""
User model for authentication
TODO: Extend with additional fields as needed:
- profile_picture, bio, last_login
- roles table relationship for... | mirpo/fastapi-gen | packages/template-advanced/src/advanced/models.py | .py | 1001f1d4ff5d8d24 | 7.56 | 12 |
from fastapi import WebSocket
class ConnectionManager:
"""
WebSocket connection manager for real-time features
TODO: Extend with:
- Room-based connections (user groups, channels)
- Message persistence
- Connection authentication
- Scaling across multiple servers with Redis pub/sub
"""
... | mirpo/fastapi-gen | packages/template-advanced/src/advanced/realtime.py | .py | 9bc34407a6c27642 | 7.56 | 12 |
import asyncio
import datetime
from pathlib import Path
import jwt
import pytest
from fastapi.testclient import TestClient
from advanced.auth import create_access_token
from advanced.config import Settings, settings
from advanced.database import Base, engine
from advanced.main import app, limiter
from advanced.realti... | mirpo/fastapi-gen | packages/template-advanced/tests/test_main.py | .py | 1d6e83289db158c8 | 8.06 | 12 |
import pytest
from fastapi.testclient import TestClient
import langchain_app.main as main_module
from langchain_app.main import app
@pytest.fixture(scope="session")
def client():
with TestClient(app) as test_client:
yield test_client
def test_health_check(client):
response = client.get("/health")
... | mirpo/fastapi-gen | packages/template-langchain/tests/test_main.py | .py | 37a510fe24f94265 | 8.06 | 12 |
import pytest
from fastapi.testclient import TestClient
from llama_app.main import LlamaService, app, settings
@pytest.fixture(scope="session")
def client():
with TestClient(app) as test_client:
yield test_client
def test_health_check(client):
"""Test health check endpoint returns model information... | mirpo/fastapi-gen | packages/template-llama/tests/test_main.py | .py | 632036906b1c019a | 8.06 | 12 |
import urllib.parse
import pytest
from fastapi import HTTPException
from fastapi.testclient import TestClient
from nlp.main import NLPService, app, settings
@pytest.fixture(scope="session")
def client():
# Model configuration comes from .env_dev; CI forces CPU via the CI env var
with TestClient(app) as test... | mirpo/fastapi-gen | packages/template-nlp/tests/test_main.py | .py | 134f57c9f01b12f8 | 7.06 | 12 |
__all__ = [
"NoWidgetBuilderFoundError",
"NotYetSubmittedError",
"StreamlitPydanticFormError",
]
class StreamlitPydanticFormError(Exception):
pass
class NotYetSubmittedError(StreamlitPydanticFormError):
"""Raised when trying to access the value of a form that has not been submitted yet."""
... | shunichironomura/streamlit-pydantic-form | src/streamlit_pydantic_form/_exceptions.py | .py | 84dabc6a9f81bac0 | 7.48 | 8 |
__all__ = [
"DynamicForm",
"StaticForm",
]
import warnings
from collections.abc import Callable, Generator, Sequence
from contextlib import contextmanager
from inspect import isclass
from types import GenericAlias, TracebackType
from typing import Any, Generic, Self, TypeVar, get_args, get_origin
import stream... | shunichironomura/streamlit-pydantic-form | src/streamlit_pydantic_form/_form.py | .py | 64fe5ccdb0992524 | 7.48 | 8 |
"""
To define a custom guardrail pyfunc, the following must be implemented:
1. def _translate_output_guardrail_request(self, model_input) -> Translates the model input between an OpenAI Chat Completions (ChatV1, https://platform.openai.com/docs/api-reference/chat/create) response and our custom guardrails format.
2. d... | andyweaves/databricks | notebooks/ai_guardrails/code_shield/llama-code-shield.py | .py | 197b2a90be6ec3cb | 7.56 | 12 |
"""
Custom Guardrail using LlamaFirewall with PromptGuard and Llama Guard 4.
This guardrail combines two scanners in a single input endpoint:
1. LlamaFirewall PromptGuard — detects jailbreaks and prompt injections
2. Llama Guard 4 — detects harmful content across 14 safety categories (S1-S14)
The request is rejected ... | andyweaves/databricks | notebooks/ai_guardrails/llama_firewall/llama-firewall-input.py | .py | 46e26cf732c4c59d | 7.56 | 12 |
"""
Custom Guardrail using Llama Guard 3 model.
This guardrail:
1. Translates OpenAI Chat Completions format to Llama Guard 3 format
2. Uses Llama Guard 3 to detect harmful content across 14 safety categories
3. Parses safety categories and translates the response to Databricks Guardrails format
"""
from typing import... | andyweaves/databricks | notebooks/ai_guardrails/llama_guard/llama-guard-3.py | .py | 487a683083b254fe | 7.56 | 12 |
"""
Custom Guardrail using Llama Guard 4 model.
This guardrail:
1. Translates OpenAI Chat Completions format to Llama Guard 4 format
2. Uses Llama Guard 4 to detect harmful content across 14 safety categories
3. Parses safety categories and translates the response to Databricks Guardrails format
"""
from typing import... | andyweaves/databricks | notebooks/ai_guardrails/llama_guard/llama-guard-4.py | .py | c1c22d65ee14b356 | 7.56 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.