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
import hmac import hashlib import os from flask import Flask, request, abort app = Flask(__name__) # Define your webhook signing secret here SIGNING_SECRET = os.environ["OPSLEVEL_SIGNING_SECRET"] # Define required and action-specific headers REQUIRED_HEADERS = {'X-OpsLevel-Timing'} # Ensure the first letter is capit...
OpsLevel/community-integrations
scripts/verify_opslevel_webhook_signature/python/verify_opslevel_webhook_signature.py
.py
d5d56ad4c9cd93f1
7.54
11
import abc class Protocol(metaclass=abc.ABCMeta): @classmethod def __subclasshook__(cls, subclass): return ( hasattr(subclass, "name") and hasattr(subclass, "debug") and callable(subclass.debug) and hasattr(subclass, "info") and callable(subc...
slackapi/python-slack-hooks
slack_cli_hooks/protocol/protocol.py
.py
841766d78ba1bc70
7.5
9
from unittest.mock import Mock from slack_cli_hooks.protocol.protocol import Protocol def debug(self, msg: str, *args, **kwargs): """This is a mock""" pass def info(self, msg: str, *args, **kwargs): """This is a mock""" pass def warning(self, msg: str, *args, **kwargs): """This is a mock""" ...
slackapi/python-slack-hooks
tests/mock_protocol.py
.py
7c8c63c6191ef3c1
7
9
"""Generate the static figures the document embeds. The narrative figures are rendered ahead of time rather than in live cells, so the page is readable the moment it loads. The Pyodide runtime is several megabytes and takes a few seconds to start; gating the argument behind it would mean a reader sees an empty page fi...
tmfreiberg/black-scholes-option-pricer
docs/make_figures.py
.py
b679556813064af9
7.45
7
"""Type aliases and helpers for the scalar/array boundary. Every mathematical function in this package accepts either Python floats or NumPy arrays, and returns whichever the caller supplied. That dual behaviour is what lets the same code price one option interactively and fill a 200x200 sensitivity grid, with no seco...
tmfreiberg/black-scholes-option-pricer
src/bsm/_numeric.py
.py
039f8c564184a38b
7.45
7
"""Command-line interface. Every capability the library offers is reachable from a shell, so any claim made in the documentation can be checked with a one-line command rather than a Python session. The entry point is ``bsm``. Percentages at the boundary --------------------------- The library works in decimals throug...
tmfreiberg/black-scholes-option-pricer
src/bsm/cli.py
.py
37c430fa3667ab8f
7.45
7
"""Rendering for surfaces and curves. Matplotlib is an optional dependency, declared under the ``plot`` extra. Everything else in the package works without it; importing this module without it installed raises an :class:`ImportError` that says which extra to install rather than a bare ``ModuleNotFoundError`` from thre...
tmfreiberg/black-scholes-option-pricer
src/bsm/plot.py
.py
81b206fbace65407
7.45
7
"""Brent's method for finding a root of a scalar function. Implied volatility is an inverse problem: the price is a known, strictly increasing function of volatility, and the task is to run it backwards. That makes a bracketing root-finder the right tool, and Brent's method the right root-finder — it keeps the guarant...
tmfreiberg/black-scholes-option-pricer
src/bsm/roots.py
.py
ed24dea33f32e324
7.45
7
"""A record of which parameter regimes have been explored. This is a log, not a cache. Caching would be indefensible: a 41-by-21 surface takes under a millisecond to compute, so storing one to avoid recomputing it would trade a free operation for a disk round trip and a consistency problem. What is worth storing is th...
tmfreiberg/black-scholes-option-pricer
src/bsm/store.py
.py
3f579daee1a2e00c
7.45
7
"""Value objects describing an option contract and the market it is priced in. The package draws a deliberate line between two layers: * This module is the **validated boundary**. Constructing a :class:`Contract` or a :class:`Market` checks every precondition the pricing formulas rely on, and raises immediately i...
tmfreiberg/black-scholes-option-pricer
src/bsm/types.py
.py
f531259a95268afe
7.45
7
"""Browser smoke test for the published document. Skipped unless `BSM_SITE_DIR` points at a built site, so a local `pytest` run is unaffected. In CI it runs against the artifact the deploy job is about to publish. What it checks is the one thing nothing else can: that a reader arriving at the page gets a working runt...
tmfreiberg/black-scholes-option-pricer
tests/e2e/test_document.py
.py
6d913fa494f65c1d
7.95
7
"""Absolute accuracy of the pricing pipeline, against a 50-digit reference. The CDF is checked against `math.erfc` in test_normal; that bounds the error in a probability. This module bounds the error in a *price*, which is the quantity anyone actually uses, and which amplifies the CDF error by roughly the spot level. ...
tmfreiberg/black-scholes-option-pricer
tests/unit/test_accuracy.py
.py
de0cba947acd0c96
7.95
7
"""Tests for the model-free no-arbitrage relationships.""" from __future__ import annotations import math import pytest from hypothesis import given from hypothesis import strategies as st from bsm.bounds import parity_residual, price_bounds from bsm.pricing import call_price, put_price from bsm.types import Option...
tmfreiberg/black-scholes-option-pricer
tests/unit/test_bounds.py
.py
98fab5b2018b0ddd
7.95
7
"""Tests for implied volatility.""" from __future__ import annotations import pytest from hypothesis import assume, given, settings from hypothesis import strategies as st from bsm import implied as implied_module from bsm.bounds import price_bounds from bsm.greeks import vega from bsm.implied import ( ImpliedVo...
tmfreiberg/black-scholes-option-pricer
tests/unit/test_implied.py
.py
0ecfdf808bd8f80a
7.95
7
"""Tests for Merton jump-diffusion and the smile it generates. Three things carry the module and are tested hardest: that zero intensity reduces exactly to Black-Scholes, that the model-free relationships survive a model with jumps in it, and that the smile has the shape the jump parameters imply rather than merely be...
tmfreiberg/black-scholes-option-pricer
tests/unit/test_merton.py
.py
ea844133c5a04789
7.95
7
"""Tests for the standard normal density and distribution. The central test is `test_matches_stdlib_oracle`. The shipped implementation is Hart's algorithm, chosen because it vectorises; `math.erfc` is exact to within an ulp but scalar-only. Pinning one against the other is what licenses the speed. """ from __future_...
tmfreiberg/black-scholes-option-pricer
tests/unit/test_normal.py
.py
39ee7ff7bb4cc961
7.95
7
"""Tests for Brent's method. The shipped implementation exists so the package needs no SciPy. SciPy is therefore the oracle: `TestAgainstScipy` runs both over the same problems and requires agreement to machine precision. """ from __future__ import annotations import math from collections.abc import Callable import...
tmfreiberg/black-scholes-option-pricer
tests/unit/test_roots.py
.py
1bef4e20dc9252c3
7.95
7
"""Tests for the validated boundary: Contract and Market.""" from __future__ import annotations import dataclasses import pytest from bsm.types import Contract, Market, OptionKind class TestOptionKind: def test_string_membership(self) -> None: assert OptionKind("call") is OptionKind.CALL asser...
tmfreiberg/black-scholes-option-pricer
tests/unit/test_types.py
.py
8d8cf55160b42c4d
7.95
7
"""Render gradients around arbitrary Rich renderables for the documentation.""" from __future__ import annotations from pathlib import Path from rich.console import Console from rich.markdown import Markdown from rich.table import Table as RichTable from rich_gradient import Gradient from rich_gradient.theme import...
maxludden/rich-gradient
examples/gradient_showcase.py
.py
6005a888dc2f28ad
7.56
12
"""Render SVG examples for gradient convenience renderables.""" from __future__ import annotations from pathlib import Path from rich.console import Console from rich_gradient import Columns, Pretty, Syntax, Table, Tree from rich_gradient.theme import GRADIENT_TERMINAL_THEME OUTPUT_DIR = Path(__file__).resolve().p...
maxludden/rich-gradient
examples/renderables_showcase.py
.py
8e3571384ff25740
7.56
12
"""Render the Spectrum table for documentation.""" from __future__ import annotations from pathlib import Path from rich.console import Console from rich_gradient.spectrum import Spectrum from rich_gradient.theme import GRADIENT_TERMINAL_THEME OUTPUT = Path(__file__).resolve().parents[1] / "docs" / "img" / "spectr...
maxludden/rich-gradient
examples/spectrum_overview.py
.py
8bb2b7658d0ca2cf
7.06
12
"""Compatibility wrapper for :mod:`rich_color_ext` optional helpers.""" from __future__ import annotations import sys from collections.abc import Callable from functools import lru_cache from typing import cast # rich_color_ext (<=0.1.x) installs Rich's traceback handler as an import side # effect; restore whatever ...
maxludden/rich-gradient
src/rich_gradient/_color_ext.py
.py
6999663716b1b4ff
7.56
12
"""Cached style ramps for gradient rendering.""" from __future__ import annotations from dataclasses import dataclass, field from math import ceil from rich.color_triplet import ColorTriplet from rich.style import Style @dataclass(frozen=True) class GradientRamp: """Precomputed Rich styles for a terminal-width...
maxludden/rich-gradient
src/rich_gradient/_gradient_ramp.py
.py
36c0b89dd82b8cdf
7.56
12
""" Logger utility for rich-gradient. Provides a Rich-styled, rotating, compressed log file and console output via loguru. This module follows loguru's library convention: rich-gradient's log records are disabled by default and the package never removes or shadows handlers the host application has configured. Enabling...
maxludden/rich-gradient
src/rich_gradient/_logger.py
.py
c754ffdffe1c430f
7.56
12
"""Animated gradient support built on top of Rich Live.""" import signal import time from collections.abc import Callable, Mapping, Sequence from contextlib import suppress from threading import Event, RLock, Thread from typing import Any from rich import get_console from rich.align import Align, AlignMethod, Vertica...
maxludden/rich-gradient
src/rich_gradient/animated_gradient.py
.py
5c617ec19b906293
7.56
12
"""Animated gradient Rule rendered with Rich Live. This module provides an AnimatedRule class that mirrors the behavior of ``rich_gradient.rule.Rule`` but animates the gradient over time using the same Live/animation machinery as ``AnimatedGradient`` and ``AnimatedPanel``. """ from __future__ import annotations from...
maxludden/rich-gradient
src/rich_gradient/animated_rule.py
.py
c8887de8c654e5d8
7.56
12
"""Pure-Python runtime configuration for rich-gradient (JSON file + env overrides).""" from __future__ import annotations import builtins import json import os from dataclasses import dataclass, field from pathlib import Path from typing import Any, ClassVar from loguru import logger from ._color_ext import install...
maxludden/rich-gradient
src/rich_gradient/config.py
.py
d2f79e25a49d1313
7.56
12
"""Gradient-enabled Rule built on Rich's Rule, powered by Gradient.""" from __future__ import annotations from collections.abc import Sequence from typing import Optional from rich.align import AlignMethod from rich.console import Console, ConsoleOptions, RenderResult from rich.rule import Rule as RichRule from rich...
maxludden/rich-gradient
src/rich_gradient/rule.py
.py
0fedf443aae6aa02
7.56
12
"""rich_gradient.spectrum Module providing a small color palette helper built on Rich. This module exposes: - SPECTRUM_COLORS: a mapping of hex color strings to human-friendly names. - Spectrum: a convenience class that builds lists of Rich Color, Style, and ColorTriplet objects drawn from the spectrum. It is it...
maxludden/rich-gradient
src/rich_gradient/spectrum.py
.py
7a86de42de568c69
8.06
12
"""A container for style information, used by `gradient.Gradient'.""" from rich.console import Console from rich.style import Style, StyleType from rich.table import Table as RichTable from rich.terminal_theme import TerminalTheme from rich.theme import Theme from rich_gradient.default_styles import DEFAULT_STYLES, s...
maxludden/rich-gradient
src/rich_gradient/theme.py
.py
df0e57e5e45b8f4f
7.56
12
"""Benchmarks for rich-gradient rendering paths.""" from __future__ import annotations from typing import Any import pytest from rich.console import Console, ConsoleRenderable from rich.text import Text as RichText from rich_gradient import AnimatedGradient, Gradient, Panel, Text def _benchmark_console(width: int...
maxludden/rich-gradient
tests/benchmark_perf.py
.py
b460834660a53b56
8.06
12
"""Tests for the animated panel component.""" import os from pathlib import Path from rich.console import Console from rich.panel import Panel as RichPanel from rich_gradient.animated_panel import AnimatedPanel from rich_gradient.panel import Panel os.environ.setdefault( "RICH_GRADIENT_CONFIG_HOME", str((Pa...
maxludden/rich-gradient
tests/test_animated_panel.py
.py
c61f0ded68ffa757
8.06
12
"""Tests for AnimatedText.""" from rich.text import Text as RichText from rich_gradient.animated_text import AnimatedText def test_animated_text_rich_text_property(): """Test that the rich_text property returns a RichText instance.""" animated = AnimatedText("Hello", colors=["#f00", "#0f0"]) rich_text =...
maxludden/rich-gradient
tests/test_animated_text.py
.py
b5fd3b285c069223
8.06
12
"""Tests for animated gradient functionality.""" # pylint: disable=protected-access import math import os import time from pathlib import Path import pytest from rich.console import Console from rich_gradient import CONFIG # type: ignore[reportMissingTypeStubs] from rich_gradient import AnimatedGradient, Gradient f...
maxludden/rich-gradient
tests/test_animation.py
.py
9103073795472b6d
8.06
12
"""Tests covering configuration discovery and integration.""" from __future__ import annotations import importlib import json import os from pathlib import Path from tempfile import TemporaryDirectory import pytest import rich_gradient as rg_pkg import rich_gradient.animated_gradient as ag_module def _reload_with...
maxludden/rich-gradient
tests/test_config.py
.py
b46d1aea2a813600
8.06
12
"""Tests for gradient convenience wrappers around Rich renderables.""" from __future__ import annotations from collections.abc import Iterable from rich.columns import Columns as RichColumns from rich.console import Console, RenderableType from rich.pretty import Pretty as RichPretty from rich.segment import Segment...
maxludden/rich-gradient
tests/test_custom_renderables.py
.py
454dd28bfc798a28
8.06
12
""" Test suite for edge cases in Gradient and Text, including long text, unicode, empty input, no colors, background, quit panel, and invalid color inputs. """ import pytest from rich.color import ColorParseError from rich.console import Console from rich.panel import Panel from rich.segment import Segment from rich_c...
maxludden/rich-gradient
tests/test_edge_cases.py
.py
9f5bc912c945f775
8.06
12
""" Test suite for Gradient class and color interpolation logic. Covers color computation, style merging, rendering, and quit panel logic. """ from __future__ import annotations from collections.abc import Iterable from typing import Any, TypeGuard import pytest from rich.color import Color, ColorParseError from ric...
maxludden/rich-gradient
tests/test_gradient.py
.py
dd471f6d51adfc86
7.06
12
"""Tests for the gradient-enabled Markdown renderables.""" import pytest from rich.markdown import Markdown as RichMarkdown from rich_gradient.animated_markdown import AnimatedMarkdown from rich_gradient.markdown import Markdown def test_markdown_initializes_with_string_content(): """Ensure Markdown strings are...
maxludden/rich-gradient
tests/test_markdown.py
.py
fc10c73a7a50b383
8.06
12
""" Test suite for Rule and AnimatedRule covering rendering, style, color validation, and context helpers. """ import os import time from pathlib import Path os.environ.setdefault( "RICH_GRADIENT_CONFIG_HOME", str((Path(__file__).parent / ".rg_config_test").resolve()), ) import pytest from rich.color import ...
maxludden/rich-gradient
tests/test_rule.py
.py
efc56ed499a11fdd
8.06
12
"""Regression tests for v0.4.0 side-effect and constructor fixes. Covers: import-time excepthook hygiene, the install_tracebacks opt-in paths, get_logger's library-safe handler management, and the Panel/Rule/AnimatedRule constructor fixes. """ from __future__ import annotations import os import subprocess import sys...
maxludden/rich-gradient
tests/test_side_effects.py
.py
40571b3cd90ccfcc
8.06
12
""" Test suite for Spectrum class covering color generation, inversion, style matching, and hex code consistency. """ from typing import Any import pytest from rich.color import Color from rich.style import Style from rich_gradient.spectrum import Spectrum def test_spectrum_default_length(): """ Test that ...
maxludden/rich-gradient
tests/test_spectrum.py
.py
5f3d09866d214cc1
8.06
12
"""Typed public response contracts for Pangram detection results.""" from typing import TypedDict __all__ = [ "BulkResultItem", "BulkResultMetadata", "BulkResults", "BulkResultsPage", "PredictionResult", "PredictionWindow", ] class _PredictionWindowRequired(TypedDict): text: str labe...
pangramlabs/pangram-sdk
pangram/schemas.py
.py
6e1318cc1d9753ea
7.48
8
''' Author: tbjuechen Date: 2024-08-12 Version: 1.0 Description: An ADB connector for the Mumu emulator. License: MIT ''' from .adb_connector import AdbConnector class MumuConnector(AdbConnector): name:str = 'Mumu' '''Connector for the Mumu emulator. Attributes ---------- host : str T...
tbjuechen/script
runner/connector/mumu_connector.py
.py
4bbc31afd4390798
7.64
18
''' Author: tbjuechen Date: 2024-08-12 Version: 1.0 Description: base class for all players License: MIT ''' from abc import ABC, abstractmethod class Player(ABC): '''Base class for all players Attributes ---------- acc : float The accuracy of the player model ''' def __init__(self, a...
tbjuechen/script
runner/player/base.py
.py
24bf621cc81cc48d
7.64
18
from __future__ import annotations from typing import Any from runner import Runner from runner.connector import AdbConnector, Connector from runner.player import Player class Schedule: """Create and control multiple task processes.""" def __init__(self) -> None: self.runners: list[Runner] = [] ...
tbjuechen/script
schedule.py
.py
ca69fc72577fcf51
7.64
18
import dronemanager from dronemanager.navigation.core import PathGenerator, WayPointType class DirectTargetGenerator(PathGenerator): """ Simply sends the target waypoint as static setpoints. """ CAN_DO_GPS = True WAYPOINT_TYPES = {WayPointType.POS_NED, WayPointType.POS_GLOBAL} def __init__(self,...
AImotion-Bavaria/DroneManager
src/dronemanager/navigation/directtargetgenerator.py
.py
a7dce52eeadc173b
7.48
8
import math import numpy as np import dronemanager from dronemanager.navigation.core import PathFollower, WayPointType, Waypoint from dronemanager.utils import dist_ned, heading_ned class VelocityFollower(PathFollower): """ Flies directly toward the waypoint facing towards it along the way. Turning towards the t...
AImotion-Bavaria/DroneManager
src/dronemanager/navigation/velocityfollower.py
.py
406893f38ba12344
7.48
8
""" Class for extra, loadable plugins. Plugins extend the functionality of DroneManager or Drone Classes by providing extra functions. They can also register their own commands to the CLI. """ import abc import asyncio from collections.abc import Coroutine import importlib.util import inspect import pathlib import sys...
AImotion-Bavaria/DroneManager
src/dronemanager/plugin.py
.py
85151f5985f0ebcb
7.48
8
""" Plugins for communication to other software Currently only features a basic UDP server which sends data on connected drones and running missions in a json format. """ import asyncio import select import threading import socket import errno import json import time import math from dronemanager.plugin import Plugin...
AImotion-Bavaria/DroneManager
src/dronemanager/plugins/external.py
.py
c302f5b9b6344855
7.48
8
""" Plugin and abstract base class for external sensors, such as weather sensors. They're specifically for plugins that connect to and sporadically query some external data source. Similar to missions, these are a special type of plugin with extra functions to support their intended purpose. The core extra component ...
AImotion-Bavaria/DroneManager
src/dronemanager/plugins/sensor.py
.py
63a7e85677b19463
7.48
8
import asyncio import struct from collections.abc import Callable import cv2 import numpy as np from dronemanager.plugin import Plugin class StreamPlugin(Plugin): """ Plugin to receive video stream from Unity via TCP. """ # This prefix is used for CLI commands (e.g., 'unity start') PREFIX = "stream" ...
AImotion-Bavaria/DroneManager
src/dronemanager/plugins/stream.py
.py
f77995e90518693d
7.48
8
""" This module contains generic utility functions used throughout the software, mostly relating to GPS and NED positions. Unless stated otherwise, a GPS coordinate is any indexable sequence with the latitude, longitude and AMSL in that order. """ import math import pathlib from collections.abc import Sequence from u...
AImotion-Bavaria/DroneManager
src/dronemanager/utils.py
.py
0333d824936556dc
7.48
8
""" Plugins for communication to other software """ import asyncio import socket import json import time import argparse LISTEN_TIME = 10 SERVER_PORT = 31659 class UDPClient: """ This client starts a connection and then keeps it alive until shut down. You can update the frequency of the messages by changing ...
AImotion-Bavaria/DroneManager
udp_dummyclient.py
.py
c922b5015c292019
7.48
8
import torch import torch.nn as nn # Define a custom tropical layer for neural networks # This layer computes a form of negative tropical distance between input and learnable weights class TropicalLayer(nn.Module): def __init__(self, in_features, out_features): super(TropicalLayer, self).__init__() ...
nijamudheen/CheMLFlow
DLModels/tropicallayer.py
.py
e92faaddb92069d0
7.6
15
import numpy as np import pandas as pd import logging import argparse import time import os import subprocess import sys from padelpy import from_smiles class PaDELDescriptorCalculator: """Class to calculate PaDEL descriptors for molecules with optional CPU usage control.""" def __init__(self, input_file,...
nijamudheen/CheMLFlow
GenDescriptors/PaDEL_descriptors.py
.py
9c3cc3f0d796266e
7.6
15
import pandas as pd import argparse import logging from rdkit import Chem from rdkit.Chem import Descriptors class RDKitDescriptorCalculator: """Class to calculate RDKit descriptors for molecules.""" def __init__(self, input_file, output_file): self.input_file = input_file self.output_file...
nijamudheen/CheMLFlow
GenDescriptors/RDKit_descriptors.py
.py
b2beca5f4ffc09bd
7.6
15
import numpy as np import pandas as pd import argparse import logging import sys try: from chembl_webresource_client.new_client import new_client except Exception as exc: logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") logging.error("ChEMBL API is unavailable: %s...
nijamudheen/CheMLFlow
GetData/get_ChEMBL_target_full.py
.py
a36e5ca7f502aa33
7.6
15
""" Plotting helpers for the time-series (Adaptive NVAR) pipeline. Renders the windowed-rollout comparison plot from the notebook `Prediction_on_test_MG_Adaptive_NVAR_10percent_noise.ipynb`: prediction vs ground-truth (clean) vs noisy observation, over the concatenated evaluation windows, with dotted window b...
nijamudheen/CheMLFlow
MLModels/training/timeseries_plots.py
.py
3a0026a2e06177ae
7.6
15
"""Typed configuration for the molecular landscape workflow.""" from __future__ import annotations from dataclasses import asdict, dataclass, field from pathlib import Path from typing import Any, Dict, List, Optional from .eda.config import EDAConfig _REPRESENTATION_CHOICES = {"morgan", "fcfp", "rdkit", "atompair...
nijamudheen/CheMLFlow
molecular_landscape/config.py
.py
7d652ad1c7f46772
7.6
15
import numpy as np def _set_uns(adata, neighbors_key): adata.uns["neighbors"] = adata.uns[neighbors_key] adata.uns["neighbors"]["connectivities_key"] = "connectivities" adata.uns["neighbors"]["distances_key"] = "distances" def _randomize_features(X, partition=None): """ Taken and adapted from op...
openproblems-bio/task_batch_integration
src/control_methods/utils.py
.py
16a8f51912933a21
7.6
15
"""Shared runner for the ConDo batch-integration method. Runs the agglomerative batch integrator: pick the seed batch with the highest per-batch pre-integration silhouette of cell_type on X_pca, then iteratively merge each next-best compatible (cell-type-overlapping) neighbour by fitting a ConDo adapter conditioned on...
openproblems-bio/task_batch_integration
src/methods/condo/condo_runner.py
.py
6c162f08879efa89
7.6
15
""" TabSeq Feature Ordering Module This module provides feature ordering functionality for tabular data using variance-based clustering and weighted integration. It can be used to reorder feature columns for deep learning models. Author: Zadid Habib """ import numpy as np import pandas as pd from sklearn.cluster imp...
zadid6pretam/TabSeq
tabseq_feature_ordering/feature_ordering.py
.py
26ed64a11bb2af72
7.57
13
"""kedro-graphql file for ensuring the package is executable as `kedro-graphql` and `python -m kedro_graphql` """ import importlib from pathlib import Path from kedro.framework.cli.utils import KedroCliError, load_entry_points from kedro.framework.project import configure_project def _find_run_command(package_name):...
cellsignal/kedro-graphql
src/kedro_graphql/__main__.py
.py
93ad0cb5c66d48b6
7.42
6
import ast import asyncio import json import os import threading import uuid import weakref from bson.objectid import ObjectId from pymongo import AsyncMongoClient from kedro_graphql.logs.logger import logger from kedro_graphql.models import Pipeline from .base import BaseBackend class MongoBackend(BaseBackend): ...
cellsignal/kedro-graphql
src/kedro_graphql/backends/mongodb.py
.py
723531f5d4dfe5bc
7.42
6
import os from importlib.metadata import entry_points from typing import Any from kedro.framework.hooks import _create_hook_manager, hook_impl from kedro.io import CatalogProtocol from kedro.pipeline import Pipeline from kedro_graphql.logs.logger import logger from .exceptions import InvalidPipeline def available_h...
cellsignal/kedro-graphql
src/kedro_graphql/hooks.py
.py
1633b822fb49577f
7.42
6
# All code below this file is attributed to: ## # The MIT License (MIT) ## # Copyright (c) 2015 Marsel Mavletkulov ## # 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, incl...
cellsignal/kedro-graphql
src/kedro_graphql/logs/json_log_formatter.py
.py
99ab0701a9d43db0
7.42
6
"""Pipeline-aware catalog resolution and validation.""" from kedro.io import AbstractDataset, DataCatalog, MemoryDataset from kedro.io.core import DatasetError from .exceptions import InvalidPipeline def normalize_pipeline_config(pipeline, catalog, parameters): """Resolve catalog patterns and retain only config...
cellsignal/kedro-graphql
src/kedro_graphql/pipeline_config.py
.py
824d43469bcbaff3
7.42
6
import asyncio import logging from datetime import datetime, timezone from queue import Empty as QueueEmptyException from queue import Queue from threading import Thread from typing import AsyncGenerator from celery.states import READY_STATES from starlette.concurrency import run_in_threadpool logger = logging.getLog...
cellsignal/kedro-graphql
src/kedro_graphql/pipeline_event_monitor.py
.py
6d20fd407dfcd868
7.42
6
""" This is a boilerplate pipeline 'example01' generated using Kedro 0.19.11 """ import time def uppercase(text: str) -> str: """Converts text to uppercase.""" return text.upper() def reverse(text: str) -> str: """Reverses the given text.""" return text[::-1] def append_timestamp(text: str) -> str...
cellsignal/kedro-graphql
src/kedro_graphql/pipelines/example01/nodes.py
.py
eb822ce8ec97565d
7.42
6
from datetime import datetime from .models import Pipeline, State TERMINAL_STATES = {State.ABORTED, State.FAILURE, State.SUCCESS} TRANSITIONS = { State.STAGED: {State.READY}, State.READY: {State.STARTED, State.ABORTING}, State.STARTED: { State.RETRY, State.ABORTING, State.FAILURE,...
cellsignal/kedro-graphql
src/kedro_graphql/run_state.py
.py
2056418727df9b84
7.42
6
from jinja2 import Environment, PackageLoader, select_autoescape import json from kedro.io import AbstractDataSet, DataCatalog, MemoryDataSet from kedro.pipeline import Pipeline from kedro.runner.runner import AbstractRunner from pluggy import PluginManager import re import requests import yaml class ArgoWorkflows...
cellsignal/kedro-graphql
src/kedro_graphql/runners/argo/argo.py
.py
8bae0e297c13ff19
7.42
6
import json from typing import List import jwt from kedro.io import AbstractDataset from strawberry.types import Info from ..models import DataSet, SignedUrl, SignedUrls, SignedUrlField from .base import SignedUrlProvider from datetime import datetime, timedelta from urllib.parse import urlencode from pathlib import Pa...
cellsignal/kedro-graphql
src/kedro_graphql/signed_url/local_file_provider.py
.py
570d53e3397c1ada
7.42
6
from qgis.PyQt.QtCore import QSettings from qgis.PyQt.QtWidgets import ( QDialog, QInputDialog, QLineEdit, QPushButton, QTextEdit, QVBoxLayout, ) from qgis.core import QgsCoordinateTransform, QgsProject, QgsVectorLayer import os import re import processing import requests # Inference Providers...
opengeoshub/vgridtools
huggingface.py
.py
561a061867d41dff
7.5
9
import importlib import subprocess import sys from qgis.PyQt.QtWidgets import QMessageBox from qgis.PyQt.QtCore import QSettings from concurrent.futures import ThreadPoolExecutor def check_and_install_libraries(filename): """Check and install required third-party Python libraries.""" settings = QSettings() ...
opengeoshub/vgridtools
install_packages/check_packages.py
.py
5b26be712ba74a6c
7.5
9
#!/usr/bin/env python # coding=utf-8 """This script uploads a plugin package to the plugin repository. Authors: A. Pasotti, V. Picavet git sha : $TemplateVCSFormat """ import sys import getpass import xmlrpc.client from optparse import OptionParser standard_library.install_aliases() # Configuration PROT...
opengeoshub/vgridtools
plugin_upload.py
.py
8046b01ec7264b40
7.5
9
"""DODO: rebuild the disordered regions of predicted protein structures. DODO takes a predicted structure -- typically from AlphaFold -- identifies its folded domains, intrinsically disordered regions and loops, and rebuilds the disordered parts so they adopt realistic polymer dimensions instead of AlphaFold's charact...
idptools/dodo
src/dodo/__init__.py
.py
9d91df1a3b3569e9
7.48
8
"""Command-line interface. One command with subcommands, replacing v1's three separate console scripts (``pdb-from-name``, ``pdb-from-pdb``, ``pdb-from-sequence``). Those were near-duplicate argparse files whose shared flags had drifted apart -- ``-apr`` meant ``--attempts_per_region`` in two of them and ``--attempts_...
idptools/dodo
src/dodo/cli.py
.py
cfe47ab99f9c8fff
7.48
8
"""Reposition folded domains so linker IDRs can adopt their predicted dimensions. This is step 3 of DODO's algorithm, and it is the step that makes the whole thing work. AlphaFold places folded domains at whatever separation its prediction happened to produce, which for a long disordered linker is essentially arbitra...
idptools/dodo
src/dodo/construct/place.py
.py
5803ed43b5874505
7.48
8
"""Tests for the backbone refinement pass. Refinement holds every alpha carbon fixed and rotates each peptide unit about the CA-CA axis -- the single degree of freedom a rigid peptide unit has once both alpha carbons are pinned. It is scored on four things at once: N-CA-C angle, steric clashes, phi/psi plausibility, a...
idptools/dodo
tests/unit/test_backbone_refine.py
.py
3aab24a373fb2fa2
7.98
8
"""The peptide-plane table is auditable: re-derivable from committed frames, with a pinned accuracy. ``dodo.construct.ca_backbone`` bakes measured peptide-plane lookup tables into source: a 4-CA 1D table keyed on one CA pseudo-dihedral, and a 5-CA 2D table keyed on two. Before this, their provenance lived outside the ...
idptools/dodo
tests/unit/test_backbone_table.py
.py
359ae403cef2d9bf
7.98
8
"""Tests for placing N, C and O from alpha carbons alone. Ground truth is a 60-residue slice of a real all-atom IDR simulation frame (``idr_frame_backbone.pdb``). The test strips it to alpha carbons, rebuilds, and compares against the atoms it threw away -- which is the only honest way to measure this, and is why the ...
idptools/dodo
tests/unit/test_ca_backbone.py
.py
63f031028669971f
7.98
8
"""Tests for the constants module. Mostly guards on internal consistency. The pre-rewrite code carried four divergent copies of the build-mode table (with three different values for ``super_compact``), three different CA-CA bond lengths, and two disagreeing atomic-mass tables. These tests assert that there is now one ...
idptools/dodo
tests/unit/test_constants.py
.py
3bdb3dc64d645d22
7.98
8
"""Tests for target dimension prediction. This is the module whose absence made the first v2 attempt unable to do the thing DODO exists for. It had no sparrow import anywhere, and substituted two *disagreeing* hardcoded placeholders (``1.0 * n_residues`` in the IDR builder, ``1.4 * n_residues`` for folded-domain spaci...
idptools/dodo
tests/unit/test_dimensions.py
.py
acdf9593c1ced679
7.98
8
"""Every code example in the shipped documentation must actually run. Not a stylistic check. Three examples were broken in ways a reader would hit immediately by copying them, and nothing noticed because nothing ran them: * ``target_dimensions("GSGSGSGS...", mode="compact")`` -- the literal ``...`` is not a sequence,...
idptools/dodo
tests/unit/test_documentation.py
.py
e52974d7272ecb2f
7.98
8
# bgm API 角色数据抓取。import 或单独运行。 # 单独运行: python scripts/lib/bangumi.py <character_id> import json import sys import time import requests UA = "vCal-ACGbday/1.0 (data check; github.com/Vanadiry)" BASE = "https://api.bgm.tv/v0" MAX_RETRY = 3 def _get(path): for attempt in range(MAX_RETRY): try: ...
Vanadiry/vCal-ACGbday
scripts/lib/bangumi.py
.py
83589bf1d6e2deec
7.45
7
""" FastAPI application setup. Creates the FastAPI app instance, configures middleware, and registers all routers. """ import time from contextlib import asynccontextmanager from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from data_api.core import config from data_api.core.se...
NTHU-SA/NTHU-Data-API
src/data_api/api/api.py
.py
cf88213781f77f61
7.57
13
""" Buses router. Handles HTTP endpoints for bus-related queries. Delegates business logic to domain services. """ from datetime import datetime from typing import Literal, Union from fastapi import APIRouter, Depends, HTTPException, Query, Response from data_api.api.schemas import buses as schemas from data_api.do...
NTHU-SA/NTHU-Data-API
src/data_api/api/routers/buses.py
.py
e08ed3e7673ce4a7
7.57
13
"""Courses router.""" from fastapi import APIRouter, Body, Depends, Query, Request, Response from data_api.api.schemas import courses as schemas from data_api.domain.courses import models, services router = APIRouter() def add_custom_header(response: Response): """Add X-Data-Commit-Hash header.""" response...
NTHU-SA/NTHU-Data-API
src/data_api/api/routers/courses.py
.py
a882763bfb4be594
7.57
13
""" Announcements API schemas. Pydantic models for announcements request/response validation. """ from enum import Enum from typing import Annotated, Optional from pydantic import BaseModel, BeforeValidator, Field, HttpUrl from data_api.utils.schema import url_corrector class AnnouncementArticle(BaseModel): "...
NTHU-SA/NTHU-Data-API
src/data_api/api/schemas/announcements.py
.py
5a27988ad994dcc1
7.57
13
""" Bus API schemas. Pydantic models for request/response validation. Enums are imported from domain layer to avoid duplication. """ from typing import Optional from fastapi import Query from pydantic import BaseModel, Field from data_api.domain.buses.enums import ( BusDay, BusDayWithCurrent, BusDirecti...
NTHU-SA/NTHU-Data-API
src/data_api/api/schemas/buses.py
.py
77c396e2b6f569e5
7.57
13
"""Courses API schemas.""" from enum import Enum from typing import Union from pydantic import BaseModel, Field, RootModel, field_validator class CourseFieldName(str, Enum): """Course field names for querying.""" id = "id" chinese_title = "chinese_title" english_title = "english_title" credit =...
NTHU-SA/NTHU-Data-API
src/data_api/api/schemas/courses.py
.py
07cf377ce6a03444
7.57
13
""" Dining API schemas. Pydantic models for dining request/response validation. """ from typing import Annotated, Optional from pydantic import BaseModel, BeforeValidator, Field, HttpUrl from data_api.domain.dining.enums import DiningBuildingName, DiningScheduleName from data_api.utils.schema import url_corrector ...
NTHU-SA/NTHU-Data-API
src/data_api/api/schemas/dining.py
.py
e80067c7bd6a0fa5
7.57
13
""" Data Manager for NTHU Data API This module provides a centralized data manager for fetching and caching data from data.nthusa.tw with improved architecture: - Separation of concerns (fetching, caching, file details management) - Configuration-based pre-fetching - Better error handling - Cleaner API """ import js...
NTHU-SA/NTHU-Data-API
src/data_api/data/nthudata.py
.py
1cb868422ce03681
7.57
13
""" Bus domain enums. This module contains all enumerations used in the bus domain. Moved from schemas to keep domain independent of Pydantic. """ from enum import Enum class BusStopsName(str, Enum): """Bus stop names.""" M1 = "北校門口" M2 = "綜二館" M3 = "楓林小徑" M4 = "人社院&生科館" M5 = "台積館" M6 =...
NTHU-SA/NTHU-Data-API
src/data_api/domain/buses/enums.py
.py
a70a4c20732e4f3d
7.57
13
""" Buses graph definition. Contains Route topology, Stop definitions, and Route selection logic. """ from typing import Literal, Optional from . import models # --- 1. Stop Definitions --- STOPS_DATA = { "M1": models.Stop("M1", "北校門口", "North Main Gate", "24.79589", "120.99633"), "M2": models.Stop("M2", "綜二...
NTHU-SA/NTHU-Data-API
src/data_api/domain/buses/graph.py
.py
3d1cff9c9d8d47ac
7.57
13
""" Buses domain models. Pure Python domain models representing business entities. """ from dataclasses import dataclass @dataclass(unsafe_hash=True) class Stop: """Bus stop data model.""" id: str # Added ID for easier lookup (e.g., "M1") name: str name_en: str latitude: str longitude: str ...
NTHU-SA/NTHU-Data-API
src/data_api/domain/buses/models.py
.py
d7d4f2572650da51
7.57
13
""" Buses domain service. Handles data fetching, caching, and processing using the Graph module. """ from __future__ import annotations from datetime import datetime, timedelta from itertools import product from typing import Any, Literal, Optional, cast from data_api.core import constants from data_api.data.manager...
NTHU-SA/NTHU-Data-API
src/data_api/domain/buses/services.py
.py
58ffccc8ff613d93
7.57
13
""" Courses domain models. Pure Python domain models without FastAPI or Pydantic dependencies. """ import re from dataclasses import dataclass, field from typing import Any, Optional, Union @dataclass class CourseData: """Course data model.""" id: str chinese_title: str english_title: str credi...
NTHU-SA/NTHU-Data-API
src/data_api/domain/courses/models.py
.py
816b7edebc9fdeea
7.57
13
""" Courses domain service. Handles course data fetching, processing, and querying. """ import operator from typing import Optional from data_api.data.manager import nthudata from data_api.domain.courses.models import Conditions, CourseData class CoursesService: """Service for course data operations.""" d...
NTHU-SA/NTHU-Data-API
src/data_api/domain/courses/services.py
.py
c2174f475e766a4f
7.57
13