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
""" Management command to initialize default event types. This should be run after migrations to set up the default event types. """ from django.core.management.base import BaseCommand from events.models import EventType class Command(BaseCommand): help = 'Initialize default event types for the events app' ...
surp-hovhannes/bahk
events/management/commands/init_event_types.py
.py
9c43f797bd0697a7
7.3
3
""" Management command to populate user activity feeds with historical data. """ from django.core.management.base import BaseCommand from django.contrib.auth import get_user_model from django.utils import timezone from datetime import timedelta from events.models import Event, UserActivityFeed from events.models impor...
surp-hovhannes/bahk
events/management/commands/populate_activity_feeds.py
.py
0bc5579559e77bee
7.3
3
""" Middleware to automatically track app open, session start/end, screen views, and ingest UTM parameters for attribution. This is lightweight and safe: it gracefully skips tracking if event types are not initialized, and only runs for authenticated users. """ import uuid from django.utils import timezone from djang...
surp-hovhannes/bahk
events/middleware.py
.py
c78a4997caeb76d1
7.3
3
# Generated by Django 4.2.11 on 2025-08-10 20:02 from django.db import migrations def create_user_account_created_event_type(apps, schema_editor): """Create EventType record for user account creation tracking.""" EventType = apps.get_model('events', 'EventType') # Respect settings flag to skip creating t...
surp-hovhannes/bahk
events/migrations/0004_create_user_account_created_event_type_record.py
.py
ee951a56233bae4f
7.3
3
# Generated for PR #229 analytics enhancements from django.db import migrations def update_checklist_used_event_type(apps, schema_editor): """Update CHECKLIST_USED event type to not require target.""" EventType = apps.get_model('events', 'EventType') try: checklist_event_type = EventType.obj...
surp-hovhannes/bahk
events/migrations/0008_make_checklist_used_target_optional.py
.py
f66596815ae600e7
7.3
3
# Copyright © 2026 Rafail Medzhidov <rafayt323@gmail.com> # SPDX-License-Identifier: MIT from datetime import timedelta from enum import Enum from http import HTTPStatus from typing import final, override from django.conf import settings from django.utils import timezone from dmr import Body, Controller, modify from ...
rafailmdzdv/ssaem
src/server/apps/auth/views.py
.py
8f8ab928418ffa99
7.15
1
# Copyright © 2026 Rafail Medzhidov <rafayt323@gmail.com> # SPDX-License-Identifier: MIT import importlib from typing import Any, final import punq @final class HasContainer: """ Base class for all parts that use ``resolve()`` function. Must be the first base class. """ __slots__ = ('_containe...
rafailmdzdv/ssaem
src/server/common/di.py
.py
455f2ade1d6c5e5f
7.15
1
# Copyright © 2026 Rafail Medzhidov <rafayt323@gmail.com> # SPDX-License-Identifier: MIT # NOTE: simple layers go on top! from collections.abc import Callable from typing import Any import punq def _global_namespace() -> dict[str, Any]: from django.conf import LazySettings # noqa: F401 from django.core.ca...
rafailmdzdv/ssaem
src/server/implemented.py
.py
cd999ff74be04666
7.15
1
# Copyright © 2026 Rafail Medzhidov <rafayt323@gmail.com> # SPDX-License-Identifier: MIT # Logging # https://docs.djangoproject.com/en/6.0/topics/logging/ # See also: # 'Do not log' by Nikita Sobolev (@sobolevn) # https://sobolevn.me/2020/03/do-not-log from __future__ import annotations from collections.abc import ...
rafailmdzdv/ssaem
src/server/settings/components/logging.py
.py
f5f5c55be4f15d76
7.15
1
# Copyright © 2026 Rafail Medzhidov <rafayt323@gmail.com> # SPDX-License-Identifier: MIT import logging from collections.abc import Iterator from typing import Any import pytest import schemathesis as st from django.conf import LazySettings from django.urls import reverse from schemathesis.specs.openapi.schemas impor...
rafailmdzdv/ssaem
tests/it/test_schema.py
.py
252324662f5381ff
7.65
1
# Copyright © 2026 Rafail Medzhidov <rafayt323@gmail.com> # SPDX-License-Identifier: MIT import pytest from django.conf import LazySettings @pytest.fixture(autouse=True) def _media_root( settings: LazySettings, tmpdir_factory: pytest.TempPathFactory, ) -> None: """Forces django to save media files into t...
rafailmdzdv/ssaem
tests/plugins/django_settings.py
.py
a277e2bee8b9087c
7.65
1
# Copyright © 2026 Rafail Medzhidov <rafayt323@gmail.com> # SPDX-License-Identifier: MIT import logging import re from typing import Final import pytest _LOGGING_FORMAT_RE: Final = re.compile( r"timestamp='.+' level='error' event='Test message' logger='django'", ) @pytest.fixture(name='logger') def logger_fixt...
rafailmdzdv/ssaem
tests/test_server/test_logging.py
.py
2d29642cc0a55c38
7.65
1
# Copyright © 2026 Rafail Medzhidov <rafayt323@gmail.com> # SPDX-License-Identifier: MIT from http import HTTPStatus from typing import Final import pytest from django.test import Client from django.urls import reverse _HEALTH_URL: Final = reverse('health_check') _ADMIN_URL: Final = reverse('admin:index') _ADMIN_DOC...
rafailmdzdv/ssaem
tests/test_server/test_urls.py
.py
6f840896f41f355e
7.65
1
import pygame from pygame.sprite import Sprite class Alien(Sprite): """A class to represent a single alien in the fleet.""" def __init__(self, ai_game): """Initialize the alien and set its starting position.""" super().__init__() self.screen = ai_game.screen self.settings = ai_...
boybands/Alien-Invasion
Alien Invasion/alien.py
.py
839fecd4474803f2
7
0
import pygame from pygame.sprite import Sprite class Bullet(Sprite): """A class to manage bullets fired from the ship""" def __init__(self, ai_game): """Create a bullet object at the ship's current position.""" super().__init__() self.screen = ai_game.screen self.settings = ai_...
boybands/Alien-Invasion
Alien Invasion/bullet.py
.py
d80bd9a28f07ea8e
7
0
import pygame.font class Button: def __init__(self, ai_game, msg): """Initialize button attributes.""" self.screen = ai_game.screen self.screen_rect = self.screen.get_rect() # Set the dimensions and properties of the button. self.width, self.height = 200, 50 self.b...
boybands/Alien-Invasion
Alien Invasion/button.py
.py
ffe28205800b11bb
7
0
class GameStats: """Track statistics for Alien Invasion.""" def __init__(self, ai_game): """Initialize statistics.""" self.settings = ai_game.settings self.reset_stats() # Start Alien Invasion in an active state. self.game_active = False # High score should nev...
boybands/Alien-Invasion
Alien Invasion/game_stats.py
.py
bb5d0f6ccccdaa25
7
0
import pygame.font from pygame.sprite import Group from ship import Ship class Scoreboard: """A class to report scoring information.""" def __init__(self, ai_game): """Initialize scorekeeping attributes.""" self.ai_game = ai_game self.screen = ai_game.screen self.screen_rect =...
boybands/Alien-Invasion
Alien Invasion/scoreboard.py
.py
e1b4e34c9f6cc67b
7
0
class Settings: """A class to store all settings for Alien Invasion.""" def __init__(self): """Initialize the game's settings.""" # Screen settings self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230, 230, 230) # Ship settings self.shi...
boybands/Alien-Invasion
Alien Invasion/settings.py
.py
89c0b2fe2425b781
7
0
import pygame from pygame.sprite import Sprite class Ship(Sprite): """A class to manage the ship.""" def __init__(self, ai_game): """Initialize the ship and set its starting position.""" super().__init__() self.screen = ai_game.screen self.screen_rect = ai_game.screen.get_rect(...
boybands/Alien-Invasion
Alien Invasion/ship.py
.py
d4f7a63d7333b8d1
7
0
import datetime import pandas as pd from qlib.data.inst_processor import InstProcessor class Resample1minProcessor(InstProcessor): """This processor tries to resample the data. It will reasmple the data from 1min freq to day freq by selecting a specific miniute""" def __init__(self, hour: int, minute: int, ...
kwbet12/qlib
examples/benchmarks/LightGBM/features_sample.py
.py
aafb6931820bdadb
7.35
4
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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...
kwbet12/qlib
examples/benchmarks/TFT/data_formatters/base.py
.py
db30b82640b06711
7.35
4
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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 applicab...
kwbet12/qlib
examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py
.py
0f4afb2e5fa7691f
7.35
4
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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...
kwbet12/qlib
examples/benchmarks/TFT/expt_settings/configs.py
.py
916bde44ed68e593
7.35
4
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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...
kwbet12/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
.py
1b810b6458985d34
7.35
4
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from pathlib import Path from typing import Union import numpy as np import pandas as pd import tensorflow.compat.v1 as tf import data_formatters.base import expt_settings.configs import libs.hyperparam_opt import libs.tft_model import libs.utils...
kwbet12/qlib
examples/benchmarks/TFT/tft.py
.py
c2052244ee54146b
7.35
4
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import copy import torch import numpy as np import pandas as pd from qlib.data.dataset import DatasetH device = "cuda" if torch.cuda.is_available() else "cpu" def _to_tensor(x): if not isinstance(x, torch.Tensor): return torch.te...
kwbet12/qlib
examples/benchmarks/TRA/src/dataset.py
.py
b90b568a1dd79780
7.35
4
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import fire import qlib import pickle from qlib.constant import REG_CN from qlib.config import HIGH_FREQ_CONFIG from qlib.utils import init_instance_by_config from qlib.data.dataset.handler import DataHandlerLP from qlib.data.ops import Opera...
kwbet12/qlib
examples/highfreq/workflow.py
.py
8146d06c1b628927
7.35
4
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ This example shows how a TrainerRM works based on TaskManager with rolling tasks. After training, how to collect the rolling results will be shown in task_collecting. Based on the ability of TaskManager, `worker` method offer a simple way for...
kwbet12/qlib
examples/model_rolling/task_manager_rolling.py
.py
98182c10b55bc9f6
7.35
4
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ This example is about how can simulate the OnlineManager based on rolling tasks. """ from pprint import pprint import fire import qlib from qlib.model.trainer import DelayTrainerR, DelayTrainerRM, TrainerR, TrainerRM from qlib.workflow impor...
kwbet12/qlib
examples/online_srv/online_management_simulate.py
.py
c804e3b5f661732d
7.35
4
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ This example shows how OnlineManager works with rolling tasks. There are four parts including first train, routine 1, add strategy and routine 2. Firstly, the OnlineManager will finish the first training and set trained models to `online` mod...
kwbet12/qlib
examples/online_srv/rolling_online_management.py
.py
516312bf0a3479bc
7.35
4
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ This example shows how OnlineTool works when we need update prediction. There are two parts including first_train and update_online_pred. Firstly, we will finish the training and set the trained models to the `online` models. Next, we ...
kwbet12/qlib
examples/online_srv/update_online_pred.py
.py
1bbad3770fdeb6e0
7.35
4
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ NOTE: - This scripts is a demo to import example data import Qlib - !!!!!!!!!!!!!!!TODO!!!!!!!!!!!!!!!!!!!: - Its structure is not well designed and very ugly, your contribution is welcome to make importing dataset easier """ from datetime...
kwbet12/qlib
examples/orderbook_data/create_dataset.py
.py
67d372a513e8a044
7.35
4
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import os import sys import fire import time import glob import shutil import signal import inspect import tempfile import functools import statistics import subprocess from datetime import datetime from ruamel.yaml import YAML from pathlib imp...
kwbet12/qlib
examples/run_all_model.py
.py
805d370b14c78d29
7.35
4
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from pathlib import Path from setuptools_scm import get_version __version__ = get_version(root="..", relative_to=__file__) __version__bak = __version__ # This version is backup for QlibConfig.reset_qlib_version import logging import os import p...
kwbet12/qlib
qlib/__init__.py
.py
49b314122cbfc704
7.35
4
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from typing import Dict, TYPE_CHECKING, Generator, Optional, Tuple, Union, cast import pandas as pd from qlib.backtest.decision import BaseTradeDecision from qlib.backtest.report import Indicator if TYPE_CHE...
kwbet12/qlib
qlib/backtest/backtest.py
.py
02ea6ea98049f0ac
7.85
4
import base64 import hashlib import uuid from pathlib import Path import orjson def derive_key(password: str, length: int) -> bytes: """Derive a fixed-length key from the password using SHA256.""" hasher = hashlib.sha256() hasher.update(password.encode()) key = hasher.digest() return key * (lengt...
Omg1221/search_evals
search_evals/io_utils.py
.py
784bf34f1a55ecee
7
0
#!/usr/bin/env python3 """Replace the [COMMIT LINK] placeholder in a reply file with the PR-scoped commit link. Usage: commit-link.py <reply-file> [--pr <number>] [--commit <hash>] Everything is self-derived when the optional flags are omitted: --pr auto-detected from the current branch via `gh pr view` --com...
LabAutomationAndScreening/copier-base-template
.claude/skills/address-pr-comments/commit-link.py
.py
41875e80075a8976
7.15
1
#!/usr/bin/env python3 """Fetch and group PR comments into threads for the address-pr-comments skill. Usage: fetch-pr-comments.py <pr_number> Outputs JSON array of actionable comment threads to stdout. Each entry: { "id": <root comment id>, "type": "pulls/comments" | "issues/comments", "author": "<login...
LabAutomationAndScreening/copier-base-template
.claude/skills/address-pr-comments/fetch-pr-comments.py
.py
a1879cd8ea6aa593
7.15
1
import argparse import os import shlex import subprocess import sys from pathlib import Path UV_VERSION = "0.12.6" PNPM_VERSION = "11.22.0" COPIER_VERSION = "9.17.1" COPIER_TEMPLATE_EXTENSIONS_VERSION = "0.3.3" PRE_COMMIT_VERSION = "4.6.2" TASK_VERSION = "3.53.1" DOWNLOAD_TIMEOUT_SECONDS = 90 # Where both uv's and Tas...
LabAutomationAndScreening/copier-base-template
.devcontainer/install-ci-tooling.py
.py
4217e1a92abecfb6
7.15
1
"""Used typically to calculate if all the files in the context of building a Docker image have changed or not.""" import argparse import subprocess import sys import zlib from pathlib import Path DEVCONTAINER_COMMENT_LINE_PREFIX = ( " // Devcontainer context hash (do not manually edit this, it's managed by a pre...
LabAutomationAndScreening/copier-base-template
.github/workflows/hash_git_files.py
.py
d87b8138d1a99e88
7.15
1
"""Update any project files that point to a private package registry to use public ones. Since the CI pipelines for testing these copier templates don't have access to private registries, we can't test installing from them as part of CI. Seems minimal risk, since the only problem we'd be missing is if the pyproject.t...
LabAutomationAndScreening/copier-base-template
template/.github/workflows/replace_private_package_registries.py
.py
709acdeb49b309ff
7.15
1
import asyncio import pytest from backend_api.background_tasks import background_task_exceptions from backend_api.background_tasks import background_tasks_set async def _wait_for_tasks(tasks_list: list[asyncio.Task[None]]): _, pending = await asyncio.wait(tasks_list, timeout=5.0) if pending: raise Ru...
LabAutomationAndScreening/copier-base-template
template/copier_template_resources/{% if template_might_want_to_use_python_asyncio %}python_asyncio{% endif %}/asyncio_fixtures.py
.py
805ba2cc2b8f601e
7.15
1
"""Shared helpers for the fix-mutants skill. All mutmut state lives under ``<backend_root>/mutants/``: - ``<backend_root>/mutants/<src path>.py.meta`` — per-source-file JSON whose ``exit_code_by_key`` maps each mutant name to the pytest exit code from its last run. The exit code is translated to a status via...
LabAutomationAndScreening/copier-base-template
template/template/.claude/skills/{% if template_uses_python %}fix-mutants{% endif %}/utils.py
.py
e48dd08455f2f5bb
7.15
1
#!/usr/bin/env python3 import click import os import json import logging from datetime import datetime from typing import Tuple, List, Set, Dict, Optional # Assuming terrain_utils.py is in the same directory or Python path from terrain_utils import ( TileManager, calculate_size_estimate, DEFAULT_CONCURRENC...
hudachan-bos/AWS-Dem-Downloader
terrain_cli.py
.py
0e1d89c4ef275f65
7
0
# src/llm_handler.py import os import requests import re import pandas as pd import concurrent.futures from tqdm import tqdm from src.config_manager import load_global_config from src.utils import Colors def _smart_chunk_text(text, max_chunk_words): """ Splits a large text into smaller chunks based on a maximu...
xispado/illumination_pipeline
src/llm_handler.py
.py
a2889a2308e3530a
7.35
4
# src/project_manager.py import os import sys import subprocess import json import ebooklib import warnings from ebooklib import epub from bs4 import BeautifulSoup from pathlib import Path # Local imports from src.config_manager import get_default_project_config from src.utils import Colors # Suppress the specific Fu...
xispado/illumination_pipeline
src/project_manager.py
.py
a82846665aae7cb9
7.35
4
# src/utils.py import os import sys import subprocess # A simple class to hold ANSI color codes for terminal output class Colors: CYAN = '\033[96m' YELLOW = '\033[93m' GREEN = '\033[92m' RED = '\033[91m' BOLD = '\033[1m' ENDC = '\033[0m' # Resets color to default def open_folder_in_explorer(pa...
xispado/illumination_pipeline
src/utils.py
.py
cd666f4dd15dd83d
7.35
4
"""Sphinx extension that ensures the widget JS bundle and admin SVG icons are available at build time. On RTD the ``pre_build`` job already builds and copies the widget bundle into ``static/``. This extension copies the bundle from the widget package's static directory as a fallback for local builds. It also copies D...
baseplate-admin/django-hstore-project
apps/docs/_extensions/widget_builder.py
.py
25cb0f35309b1458
7.35
4
from django.contrib.postgres.fields import HStoreField as DjangoHStoreField from django_hstore_widget.forms import HStoreFormField from django_hstore_widget.widgets import HStoreFormWidget class HStoreField(DjangoHStoreField): """Drop-in replacement for Django's ``HStoreField`` with the custom widget. Overr...
baseplate-admin/django-hstore-project
packages/django_hstore_field/src/django_hstore_field/fields.py
.py
b62f1a263bbf265c
7.35
4
import json import logging from django.contrib.postgres.forms import HStoreField from .widgets import HStoreFormWidget logger = logging.getLogger("django_hstore_widget") class HStoreFormField(HStoreField): """Form field that uses :class:`~django_hstore_widget.widgets.HStoreFormWidget`. Extends Django's bu...
baseplate-admin/django-hstore-project
packages/django_hstore_widget/src/django_hstore_widget/forms.py
.py
a80fb07c2a5f9865
7.35
4
import logging from django.contrib.admin.widgets import AdminTextareaWidget from django.template.loader import get_template from django.templatetags.static import static from django.utils.html import format_html, html_safe from django.utils.safestring import mark_safe logger = logging.getLogger("django_hstore_widget"...
baseplate-admin/django-hstore-project
packages/django_hstore_widget/src/django_hstore_widget/widgets.py
.py
4cd040adb32be41e
7.35
4
import pytest from cat.models import Cat from django.contrib.auth.models import User from django.test import Client from django.urls import reverse WAIT_TIME = 10_000 @pytest.fixture def admin_user(db): """Fixture to create an admin user.""" user = User.objects.create( username="murphy", is_s...
baseplate-admin/django-hstore-project
packages/django_hstore_widget/tests/test_hstore_field.py
.py
02926bab4382644d
7.85
4
#!/usr/bin/env python """Sync GitHub releases to CHANGELOG.md. Fetches releases from the current repo and updates CHANGELOG.md with the latest tags. """ import os import subprocess from datetime import datetime from pathlib import Path BASE_DIR = Path(__file__).parent.parent CHANGELOG = BASE_DIR / "CHANGELOG.md" PA...
baseplate-admin/django-hstore-project
scripts/sync_changelog.py
.py
c8364715f00f5f24
7.35
4
import os from csv import DictWriter from typing import Dict, List, Union from strava_pipeline.utils.conversions import ( c_to_f, meters_to_feet, meters_to_miles, ms_to_mph, ) def parse_activity( activity: Dict[str, Union[int, float, List[float]]], cols: List[str] ) -> Dict[str, Union[int, float,...
michaeljgallagher/strava_pipeline
strava_pipeline/utils/flatfile.py
.py
de73beb6d9cec408
7.15
1
import psycopg2 def push_csv_to_postgres( conn: psycopg2.extensions.connection, csv_path: str, table_name: str ) -> None: """ Pushes the data from a CSV file to a PostgreSQL table. :param conn: The PostgreSQL connection object. :param csv_path: The path to the CSV file. :param table_name: The...
michaeljgallagher/strava_pipeline
strava_pipeline/utils/postgres.py
.py
06d50619be24b6e3
7.15
1
import boto3 from botocore.exceptions import NoCredentialsError def connect_s3(): """ Create a boto3 session and connect to the S3 Resource Returns: connection to the S3 bucket """ try: s3 = boto3.resource("s3") return s3 except NoCredentialsError as e: raise e...
michaeljgallagher/strava_pipeline
strava_pipeline/utils/s3.py
.py
50bcbd4998942cd1
7.15
1
from datetime import datetime from itertools import count from time import sleep import requests def get_access_token(client_id: str, client_secret: str, refresh_token: str) -> str: """ Retrieves the access token from Strava API using the provided client ID, client secret, and refresh token. :param clie...
michaeljgallagher/strava_pipeline
strava_pipeline/utils/strava_api.py
.py
d997a22710217f93
7.15
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Command line interface to interact with the Dewey Data API. """ import argparse import csv import json import logging import sys from typing import Generator import requests from .dewdrop import DeweyData, DewdropError def info_writer(finfo: Generator, delimiter...
poliquin/dewdrop
dewdrop/__main__.py
.py
7295d3d96d2c5a68
7.15
1
""" Interact with Dewey Data API. """ import logging import os import requests import time from importlib.metadata import PackageNotFoundError, version from pathlib import Path from typing import Generator try: __version__ = version("dewdrop") except PackageNotFoundError: __version__ = "dev" BASE_URL = "htt...
poliquin/dewdrop
dewdrop/dewdrop.py
.py
4327379414b72921
7.15
1
"""Deterministic exit-rule helpers for the backtesting layer. These rules are intentionally stateless and conservative so we can compare whether weak satellite-strategy performance is caused by exits rather than entries. The helpers accept lightweight row/position objects (dict-like, ``pandas.Series``, or dataclass-st...
k11tos/usa_stock_finder
backtests/exit_rules.py
.py
8f91e3704f0b2687
7.65
1
"""Optional helpers for LM-review cohort analysis in backtest diagnostics. This module is intentionally isolated from the core backtest engine. It only operates on already-materialized DataFrames and structured LM review logs. """ from __future__ import annotations from collections.abc import Iterable from typing im...
k11tos/usa_stock_finder
backtests/lm_cohort_analysis.py
.py
662f73113e99f92c
7.65
1
"""Utility functions for compact backtest performance metrics. The helpers in this module are intentionally small and dependency-free so they can be reused across future backtest variants (universe, entry, and exit logic). """ from __future__ import annotations import math from datetime import date from typing impor...
k11tos/usa_stock_finder
backtests/metrics.py
.py
08bd4d0e8919ee20
7.65
1
"""Lightweight dataclasses for future backtesting workflows.""" from dataclasses import dataclass from datetime import date from enum import StrEnum class LMReviewDecision(StrEnum): """LM review decision for a candidate.""" PASSED = "passed" REJECTED = "rejected" SKIPPED = "skipped" class LMReview...
k11tos/usa_stock_finder
backtests/models.py
.py
cf89eeaa7630e006
7.65
1
""" config.py This module provides centralized configuration management for the USA Stock Finder application. All strategy parameters, thresholds, and environment variable validations are managed here. Configuration Categories: - Environment Variables: API keys, account numbers, Telegram settings - Strategy P...
k11tos/usa_stock_finder
config.py
.py
b49903d11d1e84ee
7.15
1
""" Common test configuration and fixtures for the USA Stock Finder application. This file provides shared fixtures and configuration that can be used across all test modules without explicit import statements. """ import json import os import tempfile from unittest.mock import AsyncMock, MagicMock, patch import pyt...
k11tos/usa_stock_finder
conftest.py
.py
e340ede65f0c928f
7.65
1
""" file_utils.py This module provides utility functions for file operations, specifically designed for handling CSV and JSON files in the context of stock market data processing. Key Features: - CSV file processing with symbol standardization - JSON file operations for data persistence - UTF-8 encoding s...
k11tos/usa_stock_finder
file_utils.py
.py
bbaa477ac21088fc
7.15
1
""" mylogger.py This module provides custom logging formatters and filters for structured JSON logging. It is based on the implementation from mCodingLLC's video tutorial on modern logging. Dependencies: - datetime: For timestamp handling - json: For JSON serialization - logging: Base logging functionalit...
k11tos/usa_stock_finder
mylogger.py
.py
5ee6e1ef8969baaa
7.15
1
"""Original Buff Dormeier AVSL live sell-signal calculation. This module implements the original AVSL path used by live AVSL sell decisions. The calculation is pure, based on caller-provided OHLCV data, and does not call network APIs. """ from __future__ import annotations import logging import numpy as np import p...
k11tos/usa_stock_finder
original_avsl.py
.py
50e9a7158c8a2111
7.15
1
""" telegram_utils.py This module provides utility functions for interacting with the Telegram Bot API. It handles asynchronous communication with Telegram's messaging service and includes error handling for network-related issues. Required Environment Variables: - TELEGRAM_BOT_TOKEN: Your Telegram bot token from...
k11tos/usa_stock_finder
telegram_utils.py
.py
8e37efca3c04cf25
7.15
1
"""Tests for backtest entry filter helpers.""" from __future__ import annotations import pandas as pd import pytest from backtests.entry_filters import ( apply_no_filter, apply_trend_basic, apply_trend_relaxed, apply_trend_strict, ) @pytest.fixture def candidate_snapshot_df() -> pd.DataFrame: "...
k11tos/usa_stock_finder
tests/test_backtest_entry_filters.py
.py
9a0cd98e75e7ad91
7.65
1
"""Tests for compact backtest summary metrics.""" from datetime import date import pytest from backtests.metrics import ( build_summary_metrics, calculate_cagr, calculate_equity_curve, calculate_max_drawdown, ) from backtests.models import BacktestTradeResult def _trade(symbol: str, entry: float, e...
k11tos/usa_stock_finder
tests/test_backtest_metrics.py
.py
4e4dfc705d80543a
7.65
1
""" test_file_utils.py This module contains unit tests for the file_utils module. It tests CSV reading, JSON saving/loading, and error handling scenarios. """ import json import os import tempfile import unittest from file_utils import load_json, read_csv_first_column, save_json class TestFileUtils(unittest.TestCa...
k11tos/usa_stock_finder
tests/test_file_utils.py
.py
bc995318b5b69826
7.65
1
""" test_improvements.py 테스트 케이스: 개선 사항 검증 - ZeroDivision 방지 테스트 - 데이터 부족 종목 제외 테스트 - 계좌 잔액 합산 테스트 - 환경 변수 검증 테스트 - 매수 수량 계산 로직 테스트 """ import os from unittest.mock import Mock, patch import pytest from config import ConfigError, EnvironmentConfig from stock_analysis import UsaStockFinder from stock_operations impo...
k11tos/usa_stock_finder
tests/test_improvements.py
.py
c9c72007063b7ee9
7.65
1
""" Advanced error handling and exception scenario tests for the USA Stock Finder application. This module tests complex error scenarios, edge cases, and error recovery mechanisms that go beyond basic error handling. """ import json import os import tempfile import unittest from unittest.mock import AsyncMock, MagicM...
k11tos/usa_stock_finder
tests/test_integration/test_advanced_error_handling.py
.py
0d5f8101466d5a0b
7.65
1
""" test_error_handling_integration.py Integration tests for error handling and exception scenarios. Tests how the system handles errors across different modules and workflows. """ import json import os import tempfile import unittest from unittest.mock import AsyncMock, MagicMock, patch from file_utils import load_...
k11tos/usa_stock_finder
tests/test_integration/test_error_handling_integration.py
.py
e2cc45454b25b994
7.65
1
""" test_file_operations_integration.py Integration tests for file operations with stock analysis. Tests the interaction between file I/O, data processing, and stock analysis modules. """ import csv import json import os import tempfile import unittest from file_utils import load_json, read_csv_first_column, save_js...
k11tos/usa_stock_finder
tests/test_integration/test_file_operations_integration.py
.py
a8ce7aed6945de34
7.65
1
""" test_stock_analysis_workflow.py Integration tests for the complete stock analysis workflow. Tests the interaction between stock analysis, file operations, and main logic. """ import json import os import tempfile import unittest from unittest.mock import AsyncMock, MagicMock, patch from main import generate_tele...
k11tos/usa_stock_finder
tests/test_integration/test_stock_analysis_workflow.py
.py
c6e72ca188024f17
7.65
1
""" test_telegram_integration.py Integration tests for Telegram notifications with stock selection. Tests the interaction between Telegram messaging, stock analysis, and main workflow. """ import asyncio import json import os import tempfile import unittest from unittest.mock import AsyncMock, MagicMock, patch from ...
k11tos/usa_stock_finder
tests/test_integration/test_telegram_integration.py
.py
455d48cdb839687e
7.65
1
import inspect from collections.abc import Callable from typing import Any from fastapi.routing import APIRouter as _APIRouter __all__ = ("APIRouter",) class APIRouter(_APIRouter): """Patched APIRouter for https://github.com/fastapi/fastapi/discussions/7504""" def add_api_route( self, path:...
yugokato/openapi-test-client
src/demo_app/patch/patch.py
.py
e2d8fb07bb0fb186
7.35
4
import glob import os import sys from importlib.metadata import PackageNotFoundError, version from pathlib import Path import yaml from api_client_core import setup_logging from api_client_core.endpoints import Stats from common_libs.logging import get_logger from common_libs.utils import list_items try: __versio...
yugokato/openapi-test-client
src/openapi_test_client/__init__.py
.py
01cfefad80d95a8b
7.85
4
from typing import Any, Unpack from openapi_test_client.clients.demo_app.api.base import DemoAppBaseAPI from openapi_test_client.libraries import endpoint from openapi_test_client.libraries.types import Kwargs, RestResponse class _TestAPI(DemoAppBaseAPI): TAGs = ("Test",) @endpoint.get("/v1/test/echo/{value...
yugokato/openapi-test-client
src/openapi_test_client/clients/demo_app/api/_test.py
.py
36beea764107064f
7.85
4
from typing import Unpack from openapi_test_client.clients.demo_app.api.base import DemoAppBaseAPI from openapi_test_client.libraries import endpoint from openapi_test_client.libraries.types import Kwargs, RestResponse, Unset class AuthAPI(DemoAppBaseAPI): TAGs = ("Auth",) @endpoint.is_public @endpoint....
yugokato/openapi-test-client
src/openapi_test_client/clients/demo_app/api/auth.py
.py
ba6223d4aef1beb0
7.85
4
from __future__ import annotations from typing import TYPE_CHECKING, Any, ClassVar from httpx2 import HTTPError from openapi_test_client.libraries.base.api_class import BaseOpenAPI from openapi_test_client.libraries.types import RestResponse from ..request_hooks.post_request import manage_auth_session if TYPE_CHEC...
yugokato/openapi-test-client
src/openapi_test_client/clients/demo_app/api/base/demo_app_api.py
.py
c6f603f18153de3a
7.85
4
from __future__ import annotations from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from openapi_test_client.clients.demo_app import DemoAppAPIClient from openapi_test_client.libraries import Endpoint from openapi_test_client.libraries.types import RestResponse def do_something_after_request( ...
yugokato/openapi-test-client
src/openapi_test_client/clients/demo_app/api/request_hooks/post_request.py
.py
33003ea8730281da
7.85
4
from __future__ import annotations from collections.abc import Callable from functools import wraps from typing import ParamSpec, TypeVar from openapi_test_client.libraries.types import RestResponse P = ParamSpec("P") R = TypeVar("R", bound=RestResponse) def do_something_before_and_after_request(f: Callable[P, R])...
yugokato/openapi-test-client
src/openapi_test_client/clients/demo_app/api/request_hooks/request_wrapper.py
.py
0702b95a28256b39
7.85
4
from typing import Annotated, Literal, Unpack from openapi_test_client.clients.demo_app.api.base import DemoAppBaseAPI from openapi_test_client.libraries import endpoint from openapi_test_client.libraries.types import Constraint, File, Format, Kwargs, Optional, RestResponse, Unset from ..models.users import Metadata ...
yugokato/openapi-test-client
src/openapi_test_client/clients/demo_app/api/users.py
.py
f4be3472b280fee8
7.85
4
from functools import cached_property from typing import Any from openapi_test_client.libraries.base.api_client import OpenAPIClient from .api._test import _TestAPI from .api.auth import AuthAPI from .api.users import UsersAPI class DemoAppAPIClient(OpenAPIClient): """API client for demo_app Usage: >>>...
yugokato/openapi-test-client
src/openapi_test_client/clients/demo_app/demo_app_client.py
.py
7fc879a4982564ad
7.85
4
""" This file was automatically generated by a script. Do NOT manually update the content. """ from __future__ import annotations from dataclasses import dataclass from typing import Annotated, Literal from openapi_test_client.libraries.types import Constraint, Format, Optional, ParamModel, Unset @dataclass class ...
yugokato/openapi-test-client
src/openapi_test_client/clients/demo_app/models/users.py
.py
471b18969d343971
7.85
4
"""OpenAPI-aware API base class with built-in Pydantic validation support.""" from __future__ import annotations import inspect import json from collections.abc import AsyncGenerator, Callable, Generator from contextlib import asynccontextmanager, contextmanager, nullcontext from functools import wraps from typing im...
yugokato/openapi-test-client
src/openapi_test_client/libraries/base/api_class.py
.py
f0ec63047647cac6
7.85
4
import ast import difflib import subprocess from common_libs.ansi_colors import ColorCodes, color from common_libs.logging import get_logger logger = get_logger(__name__) TAB = " " * 4 def format_code(code: str, remove_unused_imports: bool = True) -> str: """Format code string The following will be perform...
yugokato/openapi-test-client
src/openapi_test_client/libraries/code_gen/code.py
.py
3c4a0266710edc40
7.85
4
from __future__ import annotations import inspect from collections import defaultdict from dataclasses import asdict from types import NoneType, UnionType from typing import Annotated, Any, ForwardRef, Literal, Optional, Union, get_args, get_origin import openapi_test_client.libraries.types as openapi_types_module fr...
yugokato/openapi-test-client
src/openapi_test_client/libraries/code_gen/utils.py
.py
cd3c06a4b8cb5dbf
7.85
4
from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING, Any, ParamSpec from api_client_core.endpoints.endpoint import Endpoint as _Endpoint if TYPE_CHECKING: from openapi_test_client.libraries.base.api_class import BaseOpenAPI from openapi_test_client.libraries....
yugokato/openapi-test-client
src/openapi_test_client/libraries/endpoints/endpoint.py
.py
b5ca5d384dd5be27
7.85
4
from __future__ import annotations from typing import ParamSpec, cast import api_client_core.endpoints.utils.endpoint_model as core_endpoint_model_util from api_client_core.endpoints.endpoint_func import AsyncEndpointFunc as _AsyncEndpointFunc from api_client_core.endpoints.endpoint_func import EndpointFunc as _Endpo...
yugokato/openapi-test-client
src/openapi_test_client/libraries/endpoints/endpoint_func.py
.py
0df98d8701fb0955
7.85
4
""" Import/export ``Daf`` data from/to ``AnnData``. See the Julia `documentation <https://tanaylab.github.io/DataAxesFormats.jl/v0.3.0/anndata_format.html>`__ for details. """ __all__ = ["h5ad_as_daf", "daf_as_h5ad"] from typing import Any from typing import Optional from .data import DafReader from .data import Daf...
tanaylab/dafpy
dafpy/anndata_format.py
.py
7ccb945f45436e15
7
0
""" Concatenate multiple ``Daf`` data sets along some axis. See the Julia `documentation <https://tanaylab.github.io/DataAxesFormats.jl/v0.3.0/concat.html>`__ for details. """ # The enum values are named exactly as they are in Julia, so they are not UPPER_CASE. # pylint: disable=invalid-name from typing import Abstr...
tanaylab/dafpy
dafpy/concat.py
.py
ae4449444e8a2eaf
7
0
""" Concrete formats of ``Daf`` data sets. """ from typing import Optional from typing import Sequence from typing import Union from .data import DafReader from .data import DafReadOnly from .data import DafWriter from .julia_import import JlObject from .julia_import import _jl_pairs from .julia_import import jl from...
tanaylab/dafpy
dafpy/formats.py
.py
d4f1ec969cdc80e3
7
0
""" Functions from `TanayLabUtilities <https://tanaylab.github.io/TanayLabUtilities.jl>`__ which it is useful to make available. In principle we should put these in a separate ``TanayLabUtilities.py`` wrapper package, but that's too much of a hassle. """ # The enum values are named exactly as they are in Julia, so the...
tanaylab/dafpy
dafpy/generic_functions.py
.py
cbe2309db09428ac
7
0
""" Import the Julia environment. This imports the ``juliacall`` module to obtain a Julia run-time (as ``jl``), and uses it to import the ``DataAxesFormats.jl`` Julia package. How Julia is run, and which Julia is run, is left to ``juliacall``, and is configured by its own environment variables, which must be set befo...
tanaylab/dafpy
dafpy/julia_import.py
.py
a6acb16492804025
7
0
""" Reconstruct implicit axes. See the Julia `documentation <https://tanaylab.github.io/DataAxesFormats.jl/v0.3.0/reconstruction.html>`__ for details. """ __all__ = ["connect_axes", "reconstruct_axis", "unify_empty_vector_values"] from typing import AbstractSet from typing import Collection from typing import Mapping...
tanaylab/dafpy
dafpy/reconstruction.py
.py
b7a521b2876f0000
7
0