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 |
|---|---|---|---|---|---|---|
"""Tests for plot command."""
import argparse
import json
import os
from pathlib import Path
from typing import Any, List, Tuple
from unittest.mock import MagicMock, Mock, mock_open, patch
import pytest
pytest.importorskip("matplotlib")
from con_duct import cli, plot # noqa: E402
from con_duct._formatter import FILE... | con/duct | test/test_plot.py | .py | 45d42a888bef832d | 7.06 | 12 |
import argparse
from typing import Any
import unittest
from unittest.mock import MagicMock, mock_open, patch
from con_duct import cli, pprint_json
from con_duct._formatter import SummaryFormatter
class TestPPrint:
@patch("con_duct.pprint_json.pprint")
def test_pprint_json(self, mock_pprint: MagicMock, tmp_pa... | con/duct | test/test_pprint.py | .py | c76c06cbb34ea4a5 | 7.06 | 12 |
import json
import os
from pathlib import Path
from utils import run_duct_command
from con_duct._constants import SUFFIXES
from con_duct.ls import LS_FIELD_CHOICES, _flatten_dict
def test_info_fields(temp_output_dir: str) -> None:
"""
Generate the list of fields users can request when viewing info files.
... | con/duct | test/test_schema.py | .py | d766dfbee3255a40 | 7.06 | 12 |
from __future__ import annotations
from io import BytesIO
from pathlib import Path
from typing import Any
def run_duct_command(cli_args: list[str], **kwargs: Any) -> int:
"""Helper to run duct with test-friendly defaults.
Args:
cli_args: Command and its arguments as a list (e.g., ["echo", "hello"])
... | con/duct | test/utils.py | .py | 26e37d4967c5e2e3 | 8.06 | 12 |
import CDocs_utils as CDocs
import os
def define_env(env):
"""
This is the hook for the variables, macros and filters.
"""
@env.macro
def CSharp_Include(file, startToken, endToken, tabLeft=True ):
"Include..."
baseDir = os.path.dirname(env.page.file.src_path)
myDir = os.pa... | microsoft/DynamicTelemetry | main/__init__.py | .py | 70c3d8a74d254135 | 7.06 | 12 |
#!/usr/bin/env python3
import json
import subprocess
import sys
from pathlib import Path
from typing import List, Dict
def find_markdown_files(base_path: str) -> List[Path]:
"""Recursively find all markdown files in the given directory."""
base = Path(base_path)
return list(base.rglob("*.md"))
def check... | microsoft/DynamicTelemetry | tools/check_markdown_lint.py | .py | ff809b60ca96d86b | 7.56 | 12 |
"""Freeze an adjudicated review revision into deterministic benchmark artifacts."""
from __future__ import annotations
import hashlib
import io
import json
import os
import shutil
import tempfile
import zipfile
from pathlib import Path
from typing import Any
from pydantic import BaseModel, ConfigDict, Field
from pe... | lamalab-org/perla-extract | review_workbench/ground_truth_export.py | .py | 252571b973b2810d | 7.5 | 9 |
#!/usr/bin/env python3
"""Import validated extraction-run directories as immutable review seeds."""
from __future__ import annotations
import json
import sys
from pathlib import Path
import click
from loguru import logger
REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(REPO_ROOT), str(REPO_ROOT ... | lamalab-org/perla-extract | review_workbench/import_runs.py | .py | a9758eaf213252ca | 7.5 | 9 |
#!/usr/bin/env python3
"""Create a minimal Vercel deployment directory for the review workbench."""
from __future__ import annotations
import shutil
from pathlib import Path
import click
REPO_ROOT = Path(__file__).resolve().parents[1]
WORKBENCH_ROOT = REPO_ROOT / "review_workbench"
DEFAULT_OUTPUT = WORKBENCH_ROOT /... | lamalab-org/perla-extract | review_workbench/prepare.py | .py | df1b23e0abeb059a | 7.5 | 9 |
"""Atomic persistence contracts for collaborative ground-truth review."""
from __future__ import annotations
from pathlib import Path
from typing import Any, Protocol
from pydantic import BaseModel, ConfigDict, Field, model_validator
from perla_extract.study_extraction.artifacts import write_json_exclusive
class ... | lamalab-org/perla-extract | review_workbench/review_storage.py | .py | 9171720737e073a3 | 7.5 | 9 |
"""Persistent data and selection policy for PapersBot."""
from __future__ import annotations
import re
from datetime import datetime, timezone
from pathlib import Path
from pydantic import BaseModel, Field, field_validator
class SelectionPolicy(BaseModel):
"""Describe relevance as data so the bot is not tied t... | lamalab-org/perla-extract | src/perla_extract/papersbot/models.py | .py | a5359a598b356d38 | 7.5 | 9 |
"""Public API for evidence-complete, device-centered study records.
Exports are loaded on first access so lightweight consumers of a single schema or
artifact helper do not import model providers, parsers, or optional export stacks.
"""
from __future__ import annotations
from importlib import import_module
from typi... | lamalab-org/perla-extract | src/perla_extract/study_extraction/__init__.py | .py | 11b455f7f810ee9f | 7.5 | 9 |
"""Write inspectable extraction artifacts without exposing partial files."""
from __future__ import annotations
import json
import os
import tempfile
import time
from pathlib import Path
def _replace_after_contention(source: Path, target: Path) -> None:
"""Publish a completed file despite brief same-target cont... | lamalab-org/perla-extract | src/perla_extract/study_extraction/artifacts.py | .py | 49e7380006929a49 | 7.5 | 9 |
"""Centralize identifier invariants shared by candidate collection and linking."""
from __future__ import annotations
from collections import Counter
from .models import EntityKind, StudyExtraction
def entity_id_lists(study: StudyExtraction) -> dict[EntityKind, list[str]]:
"""Return identifiers without convert... | lamalab-org/perla-extract | src/perla_extract/study_extraction/identifiers.py | .py | 853790d37612cfae | 7.5 | 9 |
"""Audit explicit identity links between candidates from different windows."""
from __future__ import annotations
from pydantic import Field, model_validator
from .identifiers import duplicate_entity_ids, entity_id_lists, window_namespace
from .models import CrossWindowIdentityLink, ShortText, StrictModel, StudyExtr... | lamalab-org/perla-extract | src/perla_extract/study_extraction/identity_linking.py | .py | a6dc65e79935bc7a | 7.5 | 9 |
"""Create a compact, independent inventory for routing and recall review.
The inventory is intentionally shallower than the final extraction. It identifies
which present-study records exist and where, without extracting their values. This
makes it cheap enough to run first, useful for excluding clearly irrelevant bloc... | lamalab-org/perla-extract | src/perla_extract/study_extraction/inventory.py | .py | 5fef5c33f5925478 | 7.5 | 9 |
"""One logging policy for the study extractor's CLI and library modules."""
from __future__ import annotations
import sys
from loguru import logger
def _stderr(message: object) -> None:
"""Resolve stderr at write time so Click and test runners can capture logs."""
sys.stderr.write(str(message))
def conf... | lamalab-org/perla-extract | src/perla_extract/study_extraction/logging.py | .py | eb9a0a9125128974 | 7.5 | 9 |
"""Evidence-backed records for extracting a complete photovoltaic study.
These models preserve distinctions that the historical flat PERLA schema cannot
represent, especially device identity, measurement protocol, population results,
and multiple stability experiments. They deliberately contain generic reported values... | lamalab-org/perla-extract | src/perla_extract/study_extraction/models.py | .py | 4feec2325eaeec5b | 7.5 | 9 |
"""Pydantic mirror of the pinned NOMAD fields emitted by PERLA Extract.
Keeping this small outbound contract separate makes an upstream schema upgrade a
reviewable data-contract change rather than an accidental change to projection logic.
"""
from __future__ import annotations
from typing import Literal
from pydant... | lamalab-org/perla-extract | src/perla_extract/study_extraction/nomad_contract.py | .py | 5e685b0f23ce1525 | 7.5 | 9 |
"""Plan bounded model calls without losing evidence from long supplements.
Partitioning is based on parser-produced blocks, pages, and section paths. It
does not search for domain terms. Every block is primary evidence in exactly
one window; a small main paper may additionally be repeated as read-only context
for su... | lamalab-org/perla-extract | src/perla_extract/study_extraction/partitioning.py | .py | d2a6f232d7efb88f | 7.5 | 9 |
"""Reusable heartbeat for operations whose libraries may otherwise stay silent."""
from __future__ import annotations
import threading
import time
from collections.abc import Iterator
from contextlib import contextmanager
from .logging import logger
@contextmanager
def heartbeat(operation: str, interval_seconds: f... | lamalab-org/perla-extract | src/perla_extract/study_extraction/progress.py | .py | 38411f7a1682232e | 7.5 | 9 |
"""Create stable, directly citable passages from parser evidence blocks.
Models need to choose supporting evidence, but they do not need to reproduce text we
already own. This module divides parser blocks into sentence-, row-, or bounded
passages and gives each passage a content-derived identifier. Model responses c... | lamalab-org/perla-extract | src/perla_extract/study_extraction/spans.py | .py | 024da731b64ea3ce | 7.5 | 9 |
"""Translate compact model evidence references into the public study schema.
The public schema keeps exact quotations beside every claim for review and export.
The model-facing schema instead accepts only precomputed evidence-span identifiers.
Python expands those identifiers after generation, so the model chooses evi... | lamalab-org/perla-extract | src/perla_extract/study_extraction/transport.py | .py | 8d9278cdc9d9b91f | 7.5 | 9 |
import click
from stellar_contract_bindings import __version__
from stellar_contract_bindings.python import command as python_command
from stellar_contract_bindings.java import command as java_command
from stellar_contract_bindings.flutter import command as flutter_command
from stellar_contract_bindings.php import com... | lightsail-network/stellar-contract-bindings | stellar_contract_bindings/cli.py | .py | faa185a2d5eda4bb | 7.54 | 11 |
from stellar_sdk import SorobanServer
from stellar_sdk import xdr, Address
from stellar_sdk.sep.contract_spec import ContractSpec
from stellar_contract_bindings.metadata import get_token_sc_spec_entry
def get_specs_by_wasm_bytes(wasm: bytes) -> list[xdr.SCSpecEntry]:
"""Get the contract specs by wasm bytes.
... | lightsail-network/stellar-contract-bindings | stellar_contract_bindings/utils.py | .py | 3568f64b17d96afa | 7.54 | 11 |
import com.example.Client;
import org.stellar.sdk.scval.Scv;
import org.stellar.sdk.xdr.SCVal;
import java.util.Arrays;
import java.util.LinkedHashMap;
/** Exercises the generated tuple classes, which replaced javatuples. */
public class TupleSmoke {
static int failures = 0;
static void check(String label, bo... | lightsail-network/stellar-contract-bindings | tests/java/TupleSmoke.java | .java | 60424f3a1dc8f060 | 7.04 | 11 |
"""Compile the generated Java, rather than only asserting on its text.
Two of the three Java codegen bugs found so far (PR #27, and the nested-lambda
name collision fixed alongside this file) produced source that read correctly
and did not compile. Text assertions cannot catch that class of defect; only a
compiler can... | lightsail-network/stellar-contract-bindings | tests/test_java_compile.py | .py | 8540ffe48913fe57 | 8.04 | 11 |
"""Tests for the Java binding generator."""
from stellar_sdk import xdr
from stellar_contract_bindings.java import generate_binding
def _type(t: xdr.SCSpecType) -> xdr.SCSpecTypeDef:
return xdr.SCSpecTypeDef(t)
def _void_case(name: bytes) -> xdr.SCSpecUDTUnionCaseV0:
return xdr.SCSpecUDTUnionCaseV0(
... | lightsail-network/stellar-contract-bindings | tests/test_java_generator.py | .py | 2f56ec95a9a9bf79 | 8.04 | 11 |
"""Tests for the Python binding generator (non-event specs)."""
import ast
import inspect
import black
import pytest
from stellar_sdk import scval, xdr
from stellar_contract_bindings.python import (
_ADDRESS_TYPES,
_PY_TYPES,
_SCVAL_CODECS,
from_scval,
generate_binding,
python_docstring,
... | lightsail-network/stellar-contract-bindings | tests/test_python_generator.py | .py | 148940b97c365f68 | 8.04 | 11 |
"""Crown component proportions from Brown (1978) and Snell & Little (1983).
Primary sources, transcribed and verified against the original tables:
- Brown, J.K. 1978. Weight and Density of Crowns of Rocky Mountain
Conifers. USDA For. Serv. Res. Pap. INT-197. **Table 1** (p. 10):
live crown weight of dominant and ... | silvxlabs/fastfuels-core | fastfuels_core/allometry/brown.py | .py | 5108fa780a394990 | 7.42 | 6 |
"""Crown width from the FVS/FOFEM species coefficients.
Crookston, N.L. & Stage, A.R. 1999. Percent Canopy Cover and Stand
Structure Statistics from the Forest Vegetation Simulator. USDA For.
Serv. Gen. Tech. Rep. RMRS-GTR-24. Reached through the Fire and Fuels
Extension to FVS (Reinhardt & Crookston, eds.); the coeff... | silvxlabs/fastfuels-core | fastfuels_core/allometry/fvs.py | .py | 18d5ebd80310a82c | 7.42 | 6 |
"""National-scale biomass estimators from Jenkins et al. (2003).
Jenkins, J.C., Chojnacky, D.C., Heath, L.S., Birdsey, R.A. 2003.
National-scale biomass estimators for United States tree species.
*Forest Science* 49(1): 12-35.
Total aboveground biomass for 10 species groups (their Eq. 1, Table 4)::
agb = exp(b0 ... | silvxlabs/fastfuels-core | fastfuels_core/allometry/jenkins.py | .py | 0f88a27d58b83dad | 7.42 | 6 |
"""Metric-unit wrappers over the NSVB biomass estimators.
The National Scale Volume and Biomass system (Westfall et al. 2024,
USDA GTR WO-104; the ``nsvb`` package) works in inches, feet, and
pounds. These wrappers take the FastFuels metric convention (cm, m) and
return kilograms.
"""
from __future__ import annotatio... | silvxlabs/fastfuels-core | fastfuels_core/allometry/nsvb.py | .py | c563f4b0f645694f | 7.42 | 6 |
# External Imports
import geopandas as gpd
from pandas import DataFrame
from geopandas import GeoDataFrame
from pandera.pandas import DataFrameSchema
class ObjectIterableDataFrame:
schema: DataFrameSchema
data: DataFrame | GeoDataFrame
def __init__(self, data):
self.data = self.schema.validate(da... | silvxlabs/fastfuels-core | fastfuels_core/base.py | .py | 09d2d94570c0566b | 7.42 | 6 |
"""Canopy bulk density (kg/m**3), reduced from the vertical profile."""
from __future__ import annotations
import numpy as np
from fastfuels_core.canopy_fuel.profile import FUELCALC_LAYER_DEPTH
SLAB_EDGE = "slab"
FUELCALC_EDGE = "fuelcalc"
TRUNCATE_EDGE = "truncate"
VALID_EDGES = (SLAB_EDGE, FUELCALC_EDGE, TRUNCATE... | silvxlabs/fastfuels-core | fastfuels_core/canopy_fuel/bulk_density.py | .py | cf0bbedd6ee4c3cc | 7.42 | 6 |
"""Canopy base height and canopy height (m), from a bulk-density threshold.
Both are read off the same vertical profile with the same scan, so they
are produced together: CBH is the bottom of the lowest layer clearing
the threshold and canopy height the top of the highest. Callers writing
the pair into a LANDFIRE-keye... | silvxlabs/fastfuels-core | fastfuels_core/canopy_fuel/canopy_height.py | .py | 7935d93d9b16d0a6 | 7.42 | 6 |
"""Per-cell projected canopy cover (%).
Crowns are flat disks at the tree top. What varies between methods is
how crowns that overlap each other are counted, and which trees are
counted at all; every method clips crowns to the cell the same way, so
the methods differ only in that treatment and compare directly.
"""
f... | silvxlabs/fastfuels-core | fastfuels_core/canopy_fuel/cover.py | .py | 959124eafbddd771 | 7.42 | 6 |
"""Exact disk / axis-aligned-rectangle intersection area.
Both the vertical profile and canopy cover attribute a circular crown
to the cells it covers, and both need the intersection area exactly
rather than by sampling: a crown straddling a cell boundary must give
each cell its true share, and the shares must sum to ... | silvxlabs/fastfuels-core | fastfuels_core/canopy_fuel/geometry.py | .py | 1a2f6d8274056213 | 7.42 | 6 |
"""Per-cell vertical bulk-density profile (kg/m**3 by layer).
The profile is the intermediate every stand-level fuel metric reduces:
each tree's available canopy fuel is spread vertically over its crown
into fixed-depth layers and horizontally over the cells its crown
covers, then accumulated per cell. CBD, CBH/CH and... | silvxlabs/fastfuels-core | fastfuels_core/canopy_fuel/profile.py | .py | d3872cf6e0b44d30 | 7.42 | 6 |
"""FuelCalc reference tables for canopy fuel computation, loaded lazily.
Transcribed from the FuelCalc 1.7 User's Guide, Appendix D (pp. 68-81).
The vertical-distribution cubics originate in Reinhardt, Scott, Gray &
Keane 2006 (Can. J. For. Res. 36:2803-2814, Table 4); FuelCalc's PP, PS,
and IC rows match the Ninemile... | silvxlabs/fastfuels-core | fastfuels_core/canopy_fuel/ref_data.py | .py | b818dc50d953dafb | 7.42 | 6 |
from abc import ABC, abstractmethod
class CrownProfileModel(ABC):
"""
Abstract base class representing a tree crown profile model.
The crown profile model is a rotational solid that can be queried at any
height to get a radius, or crown width, at that height.
This abstract class provides methods ... | silvxlabs/fastfuels-core | fastfuels_core/crown_profile_models/abc.py | .py | 239543624fa23f46 | 7.42 | 6 |
# Core imports
from __future__ import annotations
# Internal imports
from fastfuels_core.ref_data import SPCD_PARAMS, JENKINS_PARAMS
from fastfuels_core.crown_profile_models.abc import CrownProfileModel
# External imports
import numpy as np
from numpy.typing import NDArray
class BetaCrownProfile(CrownProfileModel):... | silvxlabs/fastfuels-core | fastfuels_core/crown_profile_models/beta.py | .py | 576987618df61fa1 | 7.42 | 6 |
# Core imports
from __future__ import annotations
# Internal imports
from fastfuels_core.crown_profile_models.abc import CrownProfileModel
# External imports
import numpy as np
from numpy.typing import NDArray
class ConeCrownProfile(CrownProfileModel):
"""
Cone crown profile.
A single right circular co... | silvxlabs/fastfuels-core | fastfuels_core/crown_profile_models/cone.py | .py | b8cc335930c606a0 | 7.42 | 6 |
# Core imports
from __future__ import annotations
# Internal imports
from fastfuels_core.crown_profile_models.abc import CrownProfileModel
# External imports
import numpy as np
from numpy.typing import NDArray
class CylinderCrownProfile(CrownProfileModel):
"""
Cylinder crown profile.
A right circular c... | silvxlabs/fastfuels-core | fastfuels_core/crown_profile_models/cylinder.py | .py | 7723a4685fef9501 | 7.42 | 6 |
# Core imports
from __future__ import annotations
# Internal imports
from fastfuels_core.crown_profile_models.abc import CrownProfileModel
# External imports
import numpy as np
from numpy.typing import NDArray
class EllipsoidCrownProfile(CrownProfileModel):
"""
Double half-ellipsoid crown profile.
Two ... | silvxlabs/fastfuels-core | fastfuels_core/crown_profile_models/ellipsoid.py | .py | 494d18532d6d8699 | 7.42 | 6 |
# Core imports
from __future__ import annotations
# Internal imports
from fastfuels_core.crown_profile_models.abc import CrownProfileModel
# External imports
import numpy as np
from numpy.typing import NDArray
class ParaboloidCrownProfile(CrownProfileModel):
"""
Double-paraboloid crown profile.
Two par... | silvxlabs/fastfuels-core | fastfuels_core/crown_profile_models/paraboloid.py | .py | 6bf0e1f67caee5a0 | 7.42 | 6 |
# Core imports
from __future__ import annotations
# Internal imports
from fastfuels_core.ref_data import SPCD_PARAMS
from fastfuels_core.crown_profile_models.abc import CrownProfileModel
# External imports
import numpy as np
from numpy.typing import NDArray
# See Purves et al. (2007) Table S2 in Supporting Informati... | silvxlabs/fastfuels-core | fastfuels_core/crown_profile_models/purves.py | .py | 65f4b5442911df23 | 7.42 | 6 |
"""
This module contains functions for plotting data from the fastfuels_core
package.
"""
import numpy as np
import pyvista as pv
import matplotlib.pyplot as plt
import matplotlib.collections as collections
def plot_voxelized_tree(data, quantity="", **kwargs):
viz_array = data.copy()
viz_array[viz_array == 0... | silvxlabs/fastfuels-core | fastfuels_core/plotting.py | .py | caae139040d3a019 | 7.42 | 6 |
"""
Point process module for expanding trees to a region of interest (ROI) and
generating random tree locations based on a specified point process.
"""
# Core imports
from __future__ import annotations
# External imports
import dask
import dask.dataframe as dd
import numpy as np
import pandas as pd
from numpy import ... | silvxlabs/fastfuels-core | fastfuels_core/point_process.py | .py | 2fd97f8f4cab7319 | 7.42 | 6 |
# Core imports
from __future__ import annotations
from typing import Literal
# External imports
import numpy as np
from numpy import ndarray
# Type definitions
CenteringMode = Literal["cell", "vertex"]
def _get_vertical_tree_coords(step, tree_height, crown_base_height, z_origin=None):
"""
Returns the z cell... | silvxlabs/fastfuels-core | fastfuels_core/voxelization/_coords.py | .py | 63c1efb1bed50357 | 7.42 | 6 |
# Core imports
from __future__ import annotations
from typing import TYPE_CHECKING
# Internal imports
from fastfuels_core.voxelization._coords import (
CenteringMode,
_get_horizontal_tree_coords,
_get_vertical_tree_coords,
_resample_coords_grid_to_subgrid,
)
if TYPE_CHECKING:
from fastfuels_core.t... | silvxlabs/fastfuels-core | fastfuels_core/voxelization/marching_squares.py | .py | 5028d74114f906e1 | 7.42 | 6 |
"""Mass-distribution models: spread a tree's crown mass across occupied voxels.
This is the step *after* voxelization. The occupancy step (marching squares or
subgrid sampling) produces a volume-fraction grid; a ``DensityField`` then turns
that occupancy into a bulk-density grid (kg/m^3) by deciding *how much* of the
... | silvxlabs/fastfuels-core | fastfuels_core/voxelization/mass_distribution.py | .py | ba23a13946203581 | 7.42 | 6 |
# Core imports
from __future__ import annotations
# External imports
import numpy as np
from numpy import ndarray
from scipy.ndimage import distance_transform_edt
def compute_crown_probability_field(
volume_fraction_array: ndarray,
alpha: float,
beta: float,
rho: float = None,
) -> tuple[ndarray, int... | silvxlabs/fastfuels-core | fastfuels_core/voxelization/sampling.py | .py | 706b607f046d8599 | 7.42 | 6 |
# Core imports
from __future__ import annotations
from functools import cached_property
from typing import TYPE_CHECKING
# Internal imports
from fastfuels_core.voxelization._coords import (
CenteringMode,
_get_horizontal_tree_coords,
_get_vertical_tree_coords,
)
from fastfuels_core.voxelization.marching_sq... | silvxlabs/fastfuels-core | fastfuels_core/voxelization/tree.py | .py | 4ab9c12cd2b72ff3 | 7.42 | 6 |
"""
This script creates the spcd_parameters.json file shipped with
fastfuels-core in the data directory of the package
NOTE: cd into the scripts directory before running this script
"""
# Core imports
import os
import re
import sys
from pathlib import Path
# External imports
import pandas as pd
from colorama import ... | silvxlabs/fastfuels-core | scripts/create_spcd_parameters.py | .py | c0e1e09b06fd7651 | 7.42 | 6 |
"""Generate and serve the widgets.json for the OpenBB Platform API."""
import json
import os
import socket
from pathlib import Path
from fastapi.responses import JSONResponse
from openbb_core.api.rest_api import app
from .utils import (
get_data_schema_for_widget,
get_query_schema_for_widget,
data_schema_... | OpenBB-finance/openbb-platform-pro-backend | openbb_platform_pro_backend/main.py | .py | 0bc1b7624f17713f | 7.63 | 17 |
"""Utils for openbb_widgets_api."""
from datetime import datetime, timedelta
def get_query_schema_for_widget(
openapi_json: dict, command_route: str
) -> tuple[dict, bool]:
"""Extract the query schema for a widget.
Does that based on operationId, with special handling for certain parameters like
cha... | OpenBB-finance/openbb-platform-pro-backend | openbb_platform_pro_backend/utils.py | .py | 1458495ec72cf227 | 7.63 | 17 |
from llama_cpp import Llama
import os
import re
import csv
from chatformat import format_chat_prompt
from plot_compass import plot_compass
from tqdm import tqdm
import math
from transformers import pipeline
sentiment_analysis_distilbert = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-en... | andrewimpellitteri/llm_poli_compass | classic_test.py | .py | bfc86853bf61b70d | 7.04 | 11 |
from llama_cpp import Llama
import os
import re
import csv
from chatformat import format_chat_prompt
import json
from calc_8values_scores import calc_scores
from plot_eightvalues import plot_eightvalues_data, find_ideology
from tqdm import tqdm
from transformers import pipeline
sentiment_analysis_distilbert = pipeline... | andrewimpellitteri/llm_poli_compass | eightvalues_test.py | .py | ae79045ad4e26692 | 7.04 | 11 |
"""Tests for recording FTP interactions using pytest-recorder."""
import io
import ftplib
import urllib.request
import pytest
FTP_HOST = "ftp.nasdaqtrader.com"
FTP_DIR = "/symboldirectory"
FTP_FILE = "bondslist.txt"
class TestFTPRecording:
@pytest.mark.record_ftp
def test_download_via_urlopen(self):
... | OpenBB-finance/pytest_recorder | tests/test_saving_ftp.py | .py | d39ddd55eb225f10 | 7.92 | 6 |
"""Tests for saving HTTP requests using different curl libraries with VCR.py."""
import pytest
import requests
# pylint: disable=I1101
# Try importing optional curl libraries
try:
import curl_cffi.requests
HAS_CURL_CFFI = True
except ImportError:
HAS_CURL_CFFI = False
try:
from curl_cffi.requests i... | OpenBB-finance/pytest_recorder | tests/test_saving_requests.py | .py | 763821c96af9cbf7 | 7.92 | 6 |
"""OpenBB Metrics."""
import os
import json
import datetime as datetime
from utilities.helpers import (
get_discord_stats,
get_github_stats,
get_google_interest,
get_google_queries,
get_google_regions,
get_headlines_stats,
get_linkedin_stats,
get_newsletter_subscribers,
get_pipy_sta... | OpenBB-finance/openbb-metricsv2 | main.py | .py | 81e71b88ec6fb4b3 | 7.64 | 18 |
"""Helper functions for metrics."""
import logging
from datetime import datetime
import praw
import requests
from bs4 import BeautifulSoup
from pytrends.request import TrendReq
from pyyoutube import Api
from utilities.config import settings
# pylint: disable=broad-exception-caught, undefined-loop-variable
current_... | OpenBB-finance/openbb-metricsv2 | utilities/helpers.py | .py | 7d6b9b9c79c47e98 | 7.64 | 18 |
"""Synchronous TESmart API client."""
from typing import Any, TypedDict, TypeVar
from collections.abc import Callable
from homeassistant.components.media_player import MediaPlayerState
from teeheesmart import get_media_switch, MediaSwitch
from .const import (
DATA_INPUT_COUNT,
DATA_OUTPUT_COUNT,
DATA_SOU... | krohrbaugh/tesmart-homeassistant | custom_components/tesmart/api.py | .py | 481ce023b68eba4f | 7.6 | 15 |
"""Adds config flow for TESmart integration."""
from __future__ import annotations
from typing import TypedDict
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, CONF_IP_ADDRESS, CONF_PORT
from homeassistant.helpers import selector
from .api import (
Tesm... | krohrbaugh/tesmart-homeassistant | custom_components/tesmart/config_flow.py | .py | 59f747277cb1ba2c | 7.6 | 15 |
"""DataUpdateCoordinator for TESmart integration."""
from __future__ import annotations
from datetime import timedelta
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator,
UpdateFailed,
)... | krohrbaugh/tesmart-homeassistant | custom_components/tesmart/coordinator.py | .py | c3f5e29bccbf69f6 | 7.6 | 15 |
"""Base entity class."""
from __future__ import annotations
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, NAME
from .coordinator import TesmartDataUpdateCoordinator
class TesmartEntity(CoordinatorEntity):
"""... | krohrbaugh/tesmart-homeassistant | custom_components/tesmart/entity.py | .py | 03c1705c00eba7e3 | 7.6 | 15 |
"""Media Player platform entity implementation."""
from homeassistant.components.media_player import (
MediaPlayerDeviceClass,
MediaPlayerEntityDescription,
MediaPlayerEntityFeature,
MediaPlayerEntity,
MediaPlayerState,
)
from .const import (
DATA_INPUT_COUNT,
DATA_OUTPUT_COUNT,
DATA_SO... | krohrbaugh/tesmart-homeassistant | custom_components/tesmart/media_player.py | .py | 7e6ca860fd3321ed | 7.6 | 15 |
"""Button platform entity implementation."""
from homeassistant.components.select import SelectEntity, SelectEntityDescription
from homeassistant.const import EntityCategory
from .api import TesmartApiClient
from .const import (
DOMAIN,
)
from .coordinator import TesmartDataUpdateCoordinator
from .entity import T... | krohrbaugh/tesmart-homeassistant | custom_components/tesmart/select.py | .py | 5a1d22083728fbb8 | 7.6 | 15 |
"""Button platform entity implementation."""
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.const import EntityCategory
from .api import TesmartApiClient
from .const import (
DOMAIN,
)
from .coordinator import TesmartDataUpdateCoordinator
from .entity import T... | krohrbaugh/tesmart-homeassistant | custom_components/tesmart/switch.py | .py | a89948f970c99ed5 | 7.6 | 15 |
"""
Coach mode sync module for managing multiple athletes.
This module provides CLI commands for coaches to manage athletes,
trigger syncs, and download activities on behalf of their runners.
"""
import logging
from pathlib import Path
from typing import Optional
import questionary
from .strava_oauth import (
S... | Lucs1590/strava-to-trainingpeaks | src/coach_sync.py | .py | cbc04573baa30122 | 7.57 | 13 |
# pylint: disable=protected-access
import unittest
import os
import tempfile
from unittest.mock import patch, Mock
from src.coach_sync import (
CoachSyncManager,
coach_mode_main,
setup_logging
)
from src.strava_oauth import AthleteToken
class TestCoachSyncManager(unittest.TestCase):
"""Tests for Coac... | Lucs1590/strava-to-trainingpeaks | tests/test_coach_sync.py | .py | 4435a28692aeecad | 7.07 | 13 |
# pylint: disable=protected-access
import unittest
import time
import os
import tempfile
from unittest.mock import patch, Mock
from urllib.parse import urlparse, parse_qs
from src.strava_oauth import (
AthleteToken,
StravaOAuthConfig,
TokenStorage,
OAuthCallbackHandler,
StravaOAuthClient,
Stra... | Lucs1590/strava-to-trainingpeaks | tests/test_strava_oauth.py | .py | 8267f80ef8232d1b | 7.07 | 13 |
"""Set up an environment to use to contribute to this package.
This script will run through the commands listed in the CONTRIBUTING.md file.
"""
from __future__ import annotations
import glob
import os
import platform
import shlex
import subprocess
import sys
from pathlib import Path
RUNNING_ON_LINUX = platform.sy... | tektronix/TekHSI | scripts/contributor_setup.py | .py | a086c16779d38088 | 7.56 | 12 |
# pyright: reportUnnecessaryTypeIgnoreComment=none
"""Helpers for TekHSI logging."""
from __future__ import annotations
import importlib.metadata
import logging
import sys
import time
from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, Union
import colorlog
from tzlocal import get_loca... | tektronix/TekHSI | src/tekhsi/helpers/logging.py | .py | c0bf40e267f0d12a | 7.56 | 12 |
"""Test for the documentation."""
import os
import shlex
import subprocess
import sys
import time
from collections.abc import Generator
from importlib.util import find_spec
from pathlib import Path
import pytest
from conftest import PROJECT_ROOT_DIR
@pytest.fixture(name="docs_server")
def fixture_docs_server(site... | tektronix/TekHSI | tests/test_docs.py | .py | 37de3e46ba4f17dd | 8.06 | 12 |
"""Tests for the logging functionality."""
import logging
import shutil
import sys
from collections.abc import Generator
from pathlib import Path
import colorlog
import pytest
import tekhsi
from tekhsi import configure_logging, LoggingLevels, PACKAGE_NAME
from tekhsi.helpers import logging as tekhsi_logging
def ... | tektronix/TekHSI | tests/test_logging.py | .py | 4e212f6f34f8a634 | 8.06 | 12 |
import logging
import re
from collections import OrderedDict
import numpy as np
logger = logging.getLogger(__name__)
_CHROM_RE = re.compile(r"^chr?([0-9XYM]+)[:\-]", re.IGNORECASE)
def parse_chrom_groups(var_names):
"""Group feature indices by chromosome, parsed from genomic-coordinate-style
var_names (e.g... | openproblems-bio/task_predict_modality | src/methods/babel/chrom_utils.py | .py | 3833e634c2c12571 | 7.42 | 6 |
"""BABEL-style losses: negative binomial reconstruction for RNA, BCE for binarized ATAC,
combined via QuadLoss with a constant (non-warmup) cross-modality weight, matching the
weighting actually used in BABEL's shipped bin/train_model.py (cross_warmup_delay=0,
link_strength=0, i.e. no alignment term, no warmup schedule... | openproblems-bio/task_predict_modality | src/methods/babel/losses.py | .py | 9e8b6af68c3f4863 | 7.42 | 6 |
from typing import Literal
import anndata as ad
import scvi
from scipy.sparse import issparse, csr_matrix, csc_matrix
import muon
import scanpy as sc
import numpy as np
def preprocess_features(
adata: ad.AnnData,
modality: Literal["GEX", "ADT", "ATAC"],
use_hvg: bool,
min_cells_fraction: float,
... | openproblems-bio/task_predict_modality | src/methods/cellmapper_scvi/utils.py | .py | 6a53c2eee0a64650 | 7.42 | 6 |
"""Shared scButterfly setup used by both the train and predict components.
scButterfly has no transform-only preprocessing API — ``data_preprocessing`` refits
HVG/peak-filter/TF-IDF on whatever data it is given. To run inference faithfully in a
separate process, predict must rebuild the *same* paired object and re-run... | openproblems-bio/task_predict_modality | src/methods/scbutterfly/butterfly_common.py | .py | 53aec777b8baa9eb | 7.42 | 6 |
"""Chromosome / peak utilities for the scButterfly Multiome method.
scButterfly's ``construct_model`` needs a ``chrom_list`` (number of peaks per
chromosome) and reads ``ATAC_data.var.chrom`` during model construction. It also
assumes peaks are contiguous per chromosome. The predict-modality ATAC h5ads have
no ``chrom... | openproblems-bio/task_predict_modality | src/methods/scbutterfly/chrom_utils.py | .py | f5625995454445d3 | 7.42 | 6 |
"""Helpers shared by ss_opm_train and ss_opm_predict."""
import numpy as np
import pandas as pd
import scipy.sparse
# cells per block when densifying the expression matrix for per-cell statistics
ROW_BLOCK = 1000
# the cell types the original ss_opm model was trained against. only used to name the
# cell_ratio_* col... | openproblems-bio/task_predict_modality | src/methods/ss_opm/ss_opm_common.py | .py | c8ee89a07db4a44f | 7.42 | 6 |
from __future__ import annotations
from dataclasses import dataclass, field
from typing import List, Optional, Sequence, Tuple
import numpy as np
from domain.all_types import OCT_QUALITY_LABELS
@dataclass
class Measurements:
area: Optional[float] = None
circumference: Optional[float] = None
major_axis:... | AI-in-Cardiovascular-Medicine/HolOrama | src/domain/io_types.py | .py | bc58cda4b4cc67f1 | 7.65 | 19 |
from __future__ import annotations
import copy
from collections import deque
from dataclasses import dataclass
from typing import TYPE_CHECKING, Generic, TypeVar
if TYPE_CHECKING:
from domain.io_types import Contour
from domain.runtime_types import RuntimeData
T = TypeVar('T')
class UndoStack(Generic[T]):
... | AI-in-Cardiovascular-Medicine/HolOrama | src/domain/undo.py | .py | 37da4b31a5e7dedb | 7.65 | 19 |
import json
import os
from typing import Any, Callable
import numpy as np
import pydicom as dcm
import SimpleITK as sitk
from domain.io_types import MetaDataCCTA
def read_ct_volume(
folder: str,
progress_cb: Callable[[int, int], None] | None = None,
) -> tuple[np.ndarray, dict]:
"""
Read a CT DICOM ... | AI-in-Cardiovascular-Medicine/HolOrama | src/input_output/input/ccta_io.py | .py | 33b35196deddbe38 | 7.65 | 19 |
import glob
import json
import math
import os
import re
from typing import Dict, List, Optional, Tuple
from loguru import logger
from domain.all_types import OCT_QUALITY_LABELS
from domain.io_types import Contour, FrameData, Measure, Measurements, set_wire_points
from pages.intravascular.popup_windows.message_boxes i... | AI-in-Cardiovascular-Medicine/HolOrama | src/input_output/input/contours.py | .py | dbb128d68c6d653a | 7.65 | 19 |
import hashlib
import json
import os
import shutil
import tempfile
import threading
from dataclasses import asdict
import numpy as np
from loguru import logger
from pages.intravascular.popup_windows.message_boxes import ErrorMessage
from version import CONTOURS_VERSION_TAG
def write_contours(main_window, force: boo... | AI-in-Cardiovascular-Medicine/HolOrama | src/input_output/output/contours.py | .py | 78d4a6b6ddd22dc9 | 7.65 | 19 |
"""Export a combined binary mask as NIfTI or STL (ASCII default, binary available)."""
import struct
import numpy as np
import SimpleITK as sitk
from skimage.measure import marching_cubes
def export_nifti(mask: np.ndarray, voxel_spacing: tuple[float, float, float], output_path: str) -> None:
"""Write a binary m... | AI-in-Cardiovascular-Medicine/HolOrama | src/input_output/output/stl_export.py | .py | 72eed847acf4a322 | 7.65 | 19 |
"""Post-cut geometry: turn the combined LVOT/aorta-top-cut mask into an in-memory
mesh, smooth it, and locate the inlet/outlet cut-plane centroids.
Kept separate from stl_export.py (which only ever writes straight to disk) because
this module keeps the mesh in memory so it can be added as a 3D layer, smoothed,
and re-... | AI-in-Cardiovascular-Medicine/HolOrama | src/pages/ccta/cut_geometry.py | .py | 5480427e1e6a7d12 | 7.65 | 19 |
"""Background-thread runner that forwards stdout lines as Qt signals.
Duplicated from pages/fusion/progress_worker.py (identical, generic, no fusion-
specific logic) rather than imported, per CCTA-only scope. Used for Calculate
Centerlines, which shells out to WSL and can run silently for minutes at a time —
running i... | AI-in-Cardiovascular-Medicine/HolOrama | src/pages/ccta/progress_worker.py | .py | bb722ea0f596e814 | 7.65 | 19 |
from PyQt6.QtCore import Qt, pyqtSignal
from PyQt6.QtWidgets import (
QButtonGroup,
QCheckBox,
QComboBox,
QHBoxLayout,
QLabel,
QRadioButton,
QSlider,
QVBoxLayout,
QWidget,
)
from domain.ccta_display_types import LABEL_COLORS
from tools.painting import BrushGeometry
_ERASE_COLOR: tu... | AI-in-Cardiovascular-Medicine/HolOrama | src/pages/ccta/right_half/brush_panel.py | .py | 274d3bdb7a50daac | 7.65 | 19 |
# This combines aortic root, coronaries and allows to cut-off LVOT into one new combined mask, which can be exported as a STL for fluid dynamics
from PyQt6.QtCore import pyqtSignal
from PyQt6.QtWidgets import (
QButtonGroup,
QComboBox,
QFrame,
QHBoxLayout,
QLabel,
QPushButton,
QRadioButton,
... | AI-in-Cardiovascular-Medicine/HolOrama | src/pages/ccta/right_half/stl_extraction_panel.py | .py | f35d2645b3689f53 | 7.65 | 19 |
"""Drives vmtk (an external tool, installed separately by the user — never bundled
with this app) to compute aortic-root/RCA/LCA centerlines from a cut-and-smoothed
CCTA surface.
This particular vmtk install is a WSL-native Linux build: its Python venv symlinks
straight to /usr/bin/python3.10, and its vmtkcenterlines/... | AI-in-Cardiovascular-Medicine/HolOrama | src/pages/ccta/vmtk_runner.py | .py | 0ce79282bc8df608 | 7.65 | 19 |
"""
Open edX Filters needed for Aspects integration.
"""
import importlib.resources
from crum import get_current_user
from django.conf import settings
from django.template import Context, Template
from openedx_filters import PipelineStep
from web_fragments.fragment import Fragment
from platform_plugin_aspects.utils ... | openedx/platform-plugin-aspects | platform_plugin_aspects/extensions/filters.py | .py | 00a4994964bba26a | 7.92 | 6 |
"""
Tests for the filters module.
"""
from unittest.mock import Mock, patch
from django.test import TestCase
from platform_plugin_aspects.extensions.filters import (
BLOCK_CATEGORY,
AddSupersetTab,
AddSupersetTabToInstructorDashboard,
)
class TestFilters(TestCase):
"""
Test suite for the LimeSu... | openedx/platform-plugin-aspects | platform_plugin_aspects/extensions/tests/test_filters.py | .py | 9308e51c17c29936 | 7.92 | 6 |
"""
Management command for exporting the modulestore ClickHouse.
Example usages (see usage for more options):
# Dump all objects published since last dump.
# Use connection parameters from `settings.EVENT_SINK_CLICKHOUSE_BACKEND_CONFIG`:
python manage.py cms dump_objects_to_clickhouse --object user_profil... | openedx/platform-plugin-aspects | platform_plugin_aspects/management/commands/dump_data_to_clickhouse.py | .py | 24bc5031cb796419 | 7.92 | 6 |
"""
Generates tracking events by creating test users and fake activity.
This should never be run on a production server as it will generate a lot of
bad data. It is entirely for benchmarking purposes in load test environments.
It is also fragile due to reaching into the edx-platform testing internals.
"""
import csv
... | openedx/platform-plugin-aspects | platform_plugin_aspects/management/commands/load_test_tracking_events.py | .py | dcc16e6958d38423 | 7.92 | 6 |
"""
Monitors the load test tracking script and saves output for later analysis.
"""
import csv
import datetime
import io
import json
import logging
from textwrap import dedent
from time import sleep
from typing import Any, Union
import redis
import requests
from django.conf import settings
from django.core.management... | openedx/platform-plugin-aspects | platform_plugin_aspects/management/commands/monitor_load_test_tracking.py | .py | 788d04418f831394 | 7.92 | 6 |
"""
Common Django settings for eox_hooks project.
For more information on this file, see
https://docs.djangoproject.com/en/2.22/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.22/ref/settings/
"""
from platform_plugin_aspects import ROOT_DIRECTORY
# Make '_' a... | openedx/platform-plugin-aspects | platform_plugin_aspects/settings/common.py | .py | b24d485a33efb8fe | 7.92 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.