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 asyncio from datetime import datetime, timedelta, timezone import logging import os import sqlite3 import typing import diskcache import httpx from packaging.requirements import InvalidRequirement, Requirement from packaging.utils import canonicalize_name from packaging.version import Version from simple_reposi...
simple-repository/simple-repository-browser
simple_repository_browser/crawler.py
.py
869228e0bde55224
7.63
17
import dataclasses import datetime import email.parser import email.policy import logging import os.path import pathlib import tempfile import typing import httpx from packaging.requirements import InvalidRequirement from packaging.requirements import Requirement as _PkgRequirement import pkginfo import readme_rendere...
simple-repository/simple-repository-browser
simple_repository_browser/fetch_description.py
.py
6e1206ce567c857b
7.63
17
import datetime import logging from simple_repository import SimpleRepository def create_table(connection): con = connection with con as cursor: cursor.execute( """CREATE TABLE IF NOT EXISTS projects (canonical_name text unique, preferred_name text, summary text, ...
simple-repository/simple-repository-browser
simple_repository_browser/fetch_projects.py
.py
5015e30646da9669
7.63
17
""" File enrichment repository components. This module provides base classes for enriching file metadata in project pages, with a concrete implementation for HTTP HEAD-based enrichment. """ from __future__ import annotations import abc import asyncio from dataclasses import replace import logging import httpx from ...
simple-repository/simple-repository-browser
simple_repository_browser/filesize_enrichment.py
.py
3ba763ed0bf44206
7.63
17
""" Extended MetadataInjector that supports sdist (.tar.gz) and zip (.zip) formats. This extends SimpleRepository's MetadataInjectorRepository to provide metadata extraction for package formats beyond wheels. """ from dataclasses import replace import pathlib import tarfile import typing import zipfile from simple_...
simple-repository/simple-repository-browser
simple_repository_browser/metadata_injector.py
.py
c3a10ae520e697ab
7.63
17
"""Serialize PackageInfo into the JSON shape stored in projects.metadata_json. The `dependencies_idx` triggers in `fetch_projects` expect `$.requires_dist` to be a JSON array of objects with keys `name`, `extra`, `specifier`, `marker`. """ from __future__ import annotations import json from packaging.utils import c...
simple-repository/simple-repository-browser
simple_repository_browser/metadata_serialization.py
.py
3cd1374b037371d8
7.63
17
import dataclasses import datetime import itertools import math import sqlite3 import typing import diskcache from packaging.utils import canonicalize_name from packaging.version import Version from simple_repository import SimpleRepository from simple_repository.errors import PackageNotFoundError from simple_reposito...
simple-repository/simple-repository-browser
simple_repository_browser/model.py
.py
6be34eee05eb4c17
7.63
17
import dataclasses from datetime import datetime, timezone import functools import types import typing from packaging.utils import canonicalize_name from packaging.version import InvalidVersion as InvalidVersionError from packaging.version import Version from simple_repository import model from simple_repository.packa...
simple-repository/simple-repository-browser
simple_repository_browser/short_release_info.py
.py
3cc6401d6977724e
7.63
17
from __future__ import annotations import argparse from hashlib import sha256 import json import os import pathlib import shutil import sys import typing from starlette.responses import Response from starlette.staticfiles import StaticFiles from starlette.types import Scope from typing_extensions import override #: ...
simple-repository/simple-repository-browser
simple_repository_browser/static_files.py
.py
b73eefd010fd1d02
7.63
17
import pkginfo import pytest from ..fetch_description import _enhance_author_maintainer_info @pytest.mark.parametrize( [ "author", "author_email", "maintainer", "maintainer_email", "expected_author", "expected_maintainer", ], [ # Test extracting aut...
simple-repository/simple-repository-browser
simple_repository_browser/tests/test_fetch_description.py
.py
bafba426bd4f5796
7.13
17
import typing from unittest.mock import AsyncMock, MagicMock import pytest from simple_repository import SimpleRepository, model import simple_repository.errors from .._typing_compat import override from ..filesize_enrichment import FileSizeEnrichmentRepository class FakeRepository(SimpleRepository): def __init...
simple-repository/simple-repository-browser
simple_repository_browser/tests/test_filesize_enrichment.py
.py
058a1ae65b384f50
7.13
17
import pathlib import typing import httpx import pytest from simple_repository import SimpleRepository, model import simple_repository.errors from .._typing_compat import override from ..metadata_injector import MetadataInjector class FakeRepository(SimpleRepository): """A repository which""" def __init__(...
simple-repository/simple-repository-browser
simple_repository_browser/tests/test_metadata_injector.py
.py
c8931e413a2f5224
8.13
17
"""Tests for model timezone handling.""" from datetime import datetime, timezone from pathlib import Path import sqlite3 import tempfile from simple_repository_browser import fetch_projects, model def test_SearchResultItem__from_db_row__converts_naive_to_utc(): """Verify SearchResultItem.from_db_row() converts ...
simple-repository/simple-repository-browser
simple_repository_browser/tests/test_model.py
.py
4049c9c35a9d6278
7.13
17
from datetime import datetime from pathlib import Path import sqlite3 import tempfile import diskcache import parsley import pytest from simple_repository_browser import _search, model from simple_repository_browser._search import Filter, FilterOn @pytest.mark.parametrize( ["query", "expected_expression_graph"]...
simple-repository/simple-repository-browser
simple_repository_browser/tests/test_search.py
.py
57ab572958120aa5
8.13
17
import matplotlib matplotlib.use('Agg') # Use a non-GUI backend import pytest from uadapy.dr import uapca import uadapy.data as data from uadapy.plotting import plots_2d @pytest.fixture def sample_distributions(): """Fixture to create sample distributions.""" distribs_hi = data.load_iris_normal() distrib...
UniStuttgart-VISUS/uadapy
tests/test_plots_2d.py
.py
a949cbe5397d4970
7.98
8
import matplotlib matplotlib.use('Agg') # Use a non-GUI backend import pytest from uadapy.dr import uapca import uadapy.data as data from uadapy.plotting import plots_nd @pytest.fixture def sample_distributions(): """Fixture to create sample distributions.""" distribs_hi = data.load_iris_normal() distrib...
UniStuttgart-VISUS/uadapy
tests/test_plots_nd.py
.py
c4816f295c04db2f
7.98
8
import matplotlib matplotlib.use('Agg') # Use a non-GUI backend import pytest from uadapy.temporal.uastl import uastl from uadapy.plotting.plots_timeseries import plot_timeseries, plot_correlated_timeseries, plot_correlation_matrix, plot_corr_length, plot_correlated_corr_length from uadapy.data import generate_synthe...
UniStuttgart-VISUS/uadapy
tests/test_plots_timeseries.py
.py
70d1fa6045f503be
7.98
8
import numpy as np import scipy.stats as stats from collections import namedtuple from uadapy.distributions import DiracDelta, IndependentJoint def _trapezoid_abcd2cdls(a,b,c,d): """ convert trapezoidal parameters a,b,c,d to c',d',location, scale as expected by scipy.stats.trapezoid a = loc d = loc + s...
UniStuttgart-VISUS/uadapy
uadapy/data/student_grades.py
.py
76701da50398ba30
7.48
8
import numpy as np import scipy as sp from scipy import stats from scipy.stats import _multivariate as mv class Distribution: """ The Distribution class provides a consistent interface to a variety of distributions. Attributes ---------- model The underlying concrete distribution mode...
UniStuttgart-VISUS/uadapy
uadapy/distribution.py
.py
abc38742d6b23923
7.48
8
from uadapy import Distribution import numpy as np class ChiSquareComb: """ The ChiSquareComb class provides a consistent interface to a combination of chi-square distribution. Currently, we only support the distribution created by summing up two squares of complex normal distributions. Attri...
UniStuttgart-VISUS/uadapy
uadapy/distributions/chi_square_comb.py
.py
a7024603af579abe
7.48
8
import scipy.stats as stats import numpy as np class DiracDelta: """ Dirac Delta distribution class. To actually be able to work with this distribution, a very small tolerance can be specified and the distribution will then mimick a tiny uniform distribution. This class is intended to be used when ...
UniStuttgart-VISUS/uadapy
uadapy/distributions/dirac_delta.py
.py
6376d4f321da48a8
7.48
8
import numpy as np import scipy.stats as stats from uadapy import Distribution class IndependentJoint: """ Joint Distribution of independent continuous distributions. This class allows to combine multiple independent distributions into a single multivariate joint distribution. Univariate as well as mu...
UniStuttgart-VISUS/uadapy
uadapy/distributions/independent_joint.py
.py
c8b2cead5243c893
7.48
8
import numpy as np from sklearn.mixture import GaussianMixture from scipy.stats import gaussian_kde, Mixture, Normal from sklearn.mixture._gaussian_mixture import _compute_precision_cholesky class MultivariateGMM: """ Wrapper around sklearn's GaussianMixture providing a consistent interface for use with t...
UniStuttgart-VISUS/uadapy
uadapy/distributions/multivariate_gmm.py
.py
78ab16073ad50922
7.48
8
import numpy as np from uadapy import Distribution from scipy.stats import multivariate_normal def uapca(distributions, n_dims: int = 2, weights: np.ndarray = None): """ Applies UAPCA algorithm to the distribution and returns the distribution in lower-dimensional space. It assumes a normal distribution. If...
UniStuttgart-VISUS/uadapy
uadapy/dr/uapca.py
.py
db2057816d86213b
7.48
8
import numpy as np from sklearn.mixture import GaussianMixture from uadapy import Distribution from uadapy.distributions import MultivariateGMM from uadapy.dr.uapca import compute_uapca def wgmm_uapca(distributions: list, weights: np.ndarray = None, n_dims: int = 2) -> list: """ Applies weighted GMM UAPCA to...
UniStuttgart-VISUS/uadapy
uadapy/dr/wgmm_uapca.py
.py
edff442c02ffe8ed
7.48
8
import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Ellipse import matplotlib.transforms as transforms def confidence_ellipse(mean: np.ndarray, cov: np.ndarray, ax: plt.Axes, n_std: float = 3.0, facecolor='blue', **kwargs): """ Create a plot of the covarian...
UniStuttgart-VISUS/uadapy
uadapy/plotting/distribution_plot.py
.py
845bf50b4f64efb0
7.48
8
import numpy as np import matplotlib.pyplot as plt import glasbey as gb from matplotlib.colors import ListedColormap def generate_random_colors(n): return ["#" +''.join([np.random.choice('0123456789ABCDEF') for j in range(6)]) for _ in range(n)] def generate_spectrum_colors(n): cmap = plt.cm.get_cmap('viridis...
UniStuttgart-VISUS/uadapy
uadapy/plotting/utils.py
.py
814ae8f34d7df83e
7.48
8
from uadapy import TimeSeries import numpy as np import math import uadapy.distributions.chi_square_comb as chi_square_comb import os import scipy.optimize as optimize from array import array import platform from cffi import FFI ffibuilder = FFI() # Get the directory where this module is located current_dir = os.path...
UniStuttgart-VISUS/uadapy
uadapy/temporal/spectralAnalysis.py
.py
4f00a1fd93af3bb0
7.98
8
import numpy as np from uadapy import TimeSeries, CorrelatedDistributions from scipy.stats import multivariate_normal def _convmtx(h, n): h = np.array(h) m = len(h) H = np.zeros((m + n - 1, n)) # Fill the transposed convolution matrix for i in range(m + n - 1): for j in range(n): ...
UniStuttgart-VISUS/uadapy
uadapy/temporal/uastl.py
.py
89dada5f6b1a8ae1
7.48
8
from nomad.parsing.file_parser import TextParser, Quantity from nomad_simulations.schema_packages.general import Program, Simulation class SUPERCODEParser: """ Class responsible to populate the NOMAD `archive` from the files given by a SUPERCODE simulation. """ def parse(self, filepath, archive, ...
FAIRmat-NFDI/nomad-simulations
docs/snippets/explanation/general/block_01.py
.py
26a3cf11201771bf
7.45
7
import os import numpy as np import pandas as pd from utils import normalize_sparse_graph, sparse_to_tuple from sklearn.neighbors import kneighbors_graph from sklearn.preprocessing import normalize class Dataset: """ This class contains functions to prepare the data in the required format for consumption. ...
microsoft/HeteGCN
dataset.py
.py
c42a687227f943b1
7.5
9
import tensorflow as tf def dropout(x, dropout, seed=0): """ This function takes a tensor (dense/sparse) as input, applies dropout. """ if isinstance(x, tf.SparseTensor): values = x.values values = tf.nn.dropout(values, keep_prob=1-dropout, seed=seed) res = tf.SparseTensor(x....
microsoft/HeteGCN
layers.py
.py
9200df0b70db5b5b
7.5
9
import os import random import numpy as np import tensorflow as tf import scipy.sparse as sp from sklearn.metrics import accuracy_score, f1_score def sparse_to_tuple(sparse_mx): """Convert sparse matrix to tuple representation.""" # Borrowed From https://github.com/tkipf/gcn def to_tuple(mx): if ...
microsoft/HeteGCN
utils.py
.py
391964a2a9f608c0
7.5
9
"""Supervised training of the logreg model.""" import torch import torch.nn as nn import numpy as np from dataset import load def create_random_fourier_features(X, n_components=1024, sigma=1, gamma=0.1): """Create random fourier features from the input data.""" np.random.seed(0) n_samples, n_fea...
microsoft/figure
train/supervised.py
.py
04cd23df42dd16b8
7.57
13
"""This file contains the code for training the unsupervised model.""" import numpy as np import scipy.sparse as sp import torch import torch.nn as nn from utils import sparse_mx_to_torch_sparse_tensor from dataset import load from scipy.sparse import issparse # Borrowed from https://github.com/PetarV-/DGI ...
microsoft/figure
train/unsupervised.py
.py
debc69e89cec32c4
7.57
13
import numpy as np import networkx as nx import torch from scipy.linalg import fractional_matrix_power, inv import scipy.sparse as sp import random def compute_ppr(graph: nx.Graph, alpha=0.2, self_loop=True): try: a = nx.convert_matrix.to_numpy_array(graph) except: a = graph i...
microsoft/figure
utils.py
.py
b8024f1f25fd597e
7.57
13
"""This module is a copy from ayon-resolve""" import os import sys from qtpy import QtCore class PulseThread(QtCore.QThread): """A Timer that checks whether host app is still alive. This checks whether the Resolve process is still active at a certain interval. This is useful due to how Resolve runs its...
ynput/ayon-resolve
client/ayon_resolve/api/pulse.py
.py
d5ef29e84c011fa3
7.57
13
""" Rendering API wrapper for Blackmagic Design DaVinci Resolve. """ from __future__ import annotations import contextlib import io import time from pathlib import Path from pprint import pformat from typing import TYPE_CHECKING from xml.etree import ElementTree as ET from ayon_core.lib import Logger from .lib impor...
ynput/ayon-resolve
client/ayon_resolve/api/rendering.py
.py
922181a57337eb81
7.57
13
#! python3 """ Resolve's tools for setting environment """ import os import sys from ayon_core.lib import Logger log = Logger.get_logger(__name__) def get_resolve_module(): from ayon_resolve import api # dont run if already loaded if api.bmdvr: log.info(("resolve module is assigned to " ...
ynput/ayon-resolve
client/ayon_resolve/api/utils.py
.py
c2a0682b930dce90
7.57
13
"""Host API required Work Files tool""" import os import sys import time import hashlib from pathlib import Path from qtpy import QtWidgets from ayon_core.lib import Logger from ayon_core.settings import get_project_settings from ayon_core.pipeline.context_tools import get_current_project_name from .lib import ( ...
ynput/ayon-resolve
client/ayon_resolve/api/workio.py
.py
45b07058c0663103
7.57
13
import os from ayon_applications import PreLaunchHook, LaunchTypes class PreLaunchResolveLastWorkfile(PreLaunchHook): """Special hook to open last workfile for Resolve. Checks 'start_last_workfile', if set to False, it will not open last workfile. This property is set explicitly in Launcher. """ ...
ynput/ayon-resolve
client/ayon_resolve/hooks/pre_resolve_last_workfile.py
.py
53784350168f9975
7.57
13
import os from pathlib import Path import platform from ayon_applications import PreLaunchHook, LaunchTypes from ayon_resolve.utils import setup class PreLaunchResolveSetup(PreLaunchHook): """ This hook will set up the Resolve scripting environment as described in Resolve's documentation found with the in...
ynput/ayon-resolve
client/ayon_resolve/hooks/pre_resolve_setup.py
.py
74e11476b77c5172
7.57
13
import os from ayon_applications import PreLaunchHook, LaunchTypes from ayon_resolve import RESOLVE_ADDON_ROOT class PreLaunchResolveStartup(PreLaunchHook): """Special hook to configure startup script. """ order = 11 app_groups = {"resolve"} launch_types = {LaunchTypes.local} def execute(se...
ynput/ayon-resolve
client/ayon_resolve/hooks/pre_resolve_startup.py
.py
fc6d44fe6e151d4a
7.57
13
import sys import json import DaVinciResolveScript import opentimelineio as otio self = sys.modules[__name__] self.resolve = DaVinciResolveScript.scriptapp('Resolve') self.fusion = DaVinciResolveScript.scriptapp('Fusion') self.project_manager = self.resolve.GetProjectManager() self.current_project = self.project_mana...
ynput/ayon-resolve
client/ayon_resolve/otio/davinci_import.py
.py
5ed826161af1213e
7.57
13
import json import re import opentimelineio as otio import logging log = logging.getLogger(__name__) def timecode_to_frames(timecode, framerate): rt = otio.opentime.from_timecode(timecode, 24) return int(otio.opentime.to_frames(rt)) def frames_to_timecode(frames, framerate): rt = otio.opentime.from_fra...
ynput/ayon-resolve
client/ayon_resolve/otio/utils.py
.py
541023ae8f1e8aea
7.57
13
import json from copy import deepcopy from ayon_core.pipeline.create import CreatorError, CreatedInstance from ayon_core.lib import BoolDef from ayon_resolve.api import lib, constants from ayon_resolve.api.plugin import ResolveCreator, get_editorial_publish_data _CREATE_ATTR_DEFS = [ BoolDef( "review", ...
ynput/ayon-resolve
client/ayon_resolve/plugins/create/create_editorial_package.py
.py
40550e3b1c784568
7.57
13
# -*- coding: utf-8 -*- """Creator plugin for creating workfiles.""" import json from ayon_core.pipeline import ( AutoCreator, CreatedInstance, ) from ayon_resolve.api import lib class CreateWorkfile(AutoCreator): """Workfile auto-creator.""" settings_category = "resolve" identifier = "io.ayon....
ynput/ayon-resolve
client/ayon_resolve/plugins/create/create_workfile.py
.py
304817cb16596f7b
7.57
13
import ayon_api from ayon_resolve.api import lib, plugin from ayon_resolve.api.pipeline import ( containerise, update_container, ) from ayon_core.lib.transcoding import ( VIDEO_EXTENSIONS, IMAGE_EXTENSIONS ) class LoadClip(plugin.TimelineItemLoader): """Load a product to timeline as clip Pla...
ynput/ayon-resolve
client/ayon_resolve/plugins/load/load_clip.py
.py
7dbabdd3f9afff91
7.57
13
import json from pathlib import Path import random from ayon_core.pipeline import ( AVALON_CONTAINER_ID, load, get_representation_path, ) from ayon_resolve.api import lib, constants from ayon_resolve.api.plugin import get_editorial_publish_data class LoadEditorialPackage(load.LoaderPlugin): """Load ...
ynput/ayon-resolve
client/ayon_resolve/plugins/load/load_editorial_package.py
.py
a68c3f60ca5a50d0
7.57
13
import pprint import pyblish from ayon_core.pipeline import PublishError from ayon_resolve.otio import utils class CollectShotAudio(pyblish.api.InstancePlugin): """Collect new audio for shot.""" order = pyblish.api.CollectorOrder - 0.48 label = "Collect Shot Audio" hosts = ["resolve"] families =...
ynput/ayon-resolve
client/ayon_resolve/plugins/publish/collect_audio.py
.py
77fca7ca1ef7df35
7.57
13
import pyblish.api from ayon_core.pipeline import registered_host from ayon_resolve import api class CollectResolveProject(pyblish.api.ContextPlugin): """Collect the current Resolve project and current timeline data""" label = "Collect Project and Current Timeline" order = pyblish.api.CollectorOrder - ...
ynput/ayon-resolve
client/ayon_resolve/plugins/publish/collect_current_project.py
.py
a68e4ec9ca89f9c9
7.57
13
import pyblish.api import ayon_api from ayon_resolve.api.lib import maintain_current_timeline class EditorialPackageInstances(pyblish.api.InstancePlugin): """Collect all Track items selection.""" order = pyblish.api.CollectorOrder - 0.49 label = "Collect Editorial Package Instances" families = ["ed...
ynput/ayon-resolve
client/ayon_resolve/plugins/publish/collect_editorial_package.py
.py
7d12fd87d68f7e13
7.57
13
import pyblish.api from ayon_core.pipeline import PublishError from ayon_resolve.otio import utils class CollectPlate(pyblish.api.InstancePlugin): """Collect new plates.""" order = pyblish.api.CollectorOrder - 0.48 label = "Collect Plate" hosts = ["resolve"] families = ["plate"] def proces...
ynput/ayon-resolve
client/ayon_resolve/plugins/publish/collect_plates.py
.py
cca0045d0ce93570
7.57
13
import pyblish from ayon_core.pipeline import PublishError from ayon_resolve.api import lib from ayon_resolve.otio import utils class CollectShot(pyblish.api.InstancePlugin): """Collect new shots.""" order = pyblish.api.CollectorOrder - 0.49 label = "Collect Shots" hosts = ["resolve"] families ...
ynput/ayon-resolve
client/ayon_resolve/plugins/publish/collect_shots.py
.py
70af0a0605cad5a1
7.57
13
import pyblish.api class CollectWorkfile(pyblish.api.InstancePlugin): """Collect additional metadata for workfile instance.""" label = "Collect Workfile" order = pyblish.api.CollectorOrder - 0.49 hosts = ["resolve"] families = ["workfile"] def process(self, instance): # Mark instance...
ynput/ayon-resolve
client/ayon_resolve/plugins/publish/collect_workfile.py
.py
bf72da077806836e
7.07
13
import os import pyblish.api from ayon_core.pipeline import publish from ayon_resolve.api.lib import get_project_manager class ExtractWorkfile(publish.Extractor): """ Extractor export DRP workfile file representation """ label = "Extract Workfile" order = pyblish.api.ExtractorOrder families...
ynput/ayon-resolve
client/ayon_resolve/plugins/publish/extract_workfile.py
.py
d6a80eb70bd8579d
7.57
13
"""This script is used as a startup script in Resolve through a .scriptlib file It triggers directly after the launch of Resolve and it's recommended to keep it optimized for fast performance since the Resolve UI is actually interactive while this is running. As such, there's nothing ensuring the user isn't continuing...
ynput/ayon-resolve
client/ayon_resolve/startup.py
.py
57cca6d4e278b672
7.57
13
#!/usr/bin/env python """Prepares server package from addon repo to upload to server. Requires Python 3.9. (Or at least 3.8+). This script should be called from cloned addon repo. It will produce 'package' subdirectory which could be pasted into server addon directory directly (eg. into `ayon-backend/addons`). For...
ynput/ayon-resolve
create_package.py
.py
a499161f7f1a2397
7.57
13
import os import time import json import logging import math import statistics from datetime import datetime, timezone from typing import Dict from language_config import BENCHMARK_LANGUAGES, LANGUAGE_WEIGHTS, REFERENCE_LANGUAGE # Constants BENCHMARK_FILE = 'benchmark.json' BENCHMARK_FILE_STOP = 'benchmark.json.stop'...
Orbiter/project-euler-llm-benchmark
benchmark.py
.py
91d12a13beda8c4f
7.6
15
"""Shared language configuration for the benchmark pipeline.""" from types import MappingProxyType from typing import Final, Mapping REFERENCE_LANGUAGE: Final = "python" LANGUAGE_WEIGHTS: Final[Mapping[str, float]] = MappingProxyType({ "python": 5.0, "javascript": 4.0, "java": 3.0, "rust": 2.0, ...
Orbiter/project-euler-llm-benchmark
language_config.py
.py
1e18380ed2aa7e69
7.6
15
#!/usr/bin/env python3 import argparse import json import os import re import tempfile from datetime import datetime, timezone from pathlib import Path SCRIPT_DIR = Path(__file__).resolve().parent DEFAULT_BENCHMARK_PATH = SCRIPT_DIR / "benchmark.json" DEFAULT_SOLUTIONS_PATH = SCRIPT_DIR / "solutions" TIMESTAMP_FIELD...
Orbiter/project-euler-llm-benchmark
retrotime.py
.py
cafe99649045c49e
7.6
15
import os import json import shlex import shutil import subprocess import sys from argparse import ArgumentParser from benchmark import read_benchmark, score_key, write_benchmark from language_config import DEFAULT_LANGUAGES from llm_client import openai_api_list, load_endpoint_file, Endpoint _base_dir = os.path.dirna...
Orbiter/project-euler-llm-benchmark
test.py
.py
091e9601b8614d62
7.1
15
from abc import ABC, abstractmethod from unsync import unsync from src.providers.alertmanager.typings import AlertBody from src.providers.consensus.typings import FullBlockInfo # Enough count for different handlers to store in memory KEEP_MAX_SENT_ALERTS = 10 class WatcherHandler(ABC): sent_alerts: list[AlertB...
lidofinance/ethereum-head-watcher
src/handlers/handler.py
.py
fc1a28bb6606d473
7.5
9
import logging import os import yaml from src import variables from src.keys_source.base_source import BaseSource, NamedKey logger = logging.getLogger() class FileSource(BaseSource): def __init__(self): self.keys_file_modification_time = 0 def update_keys(self): """ Returns True if...
lidofinance/ethereum-head-watcher
src/keys_source/file_source.py
.py
48d81396c1cbda9e
7.5
9
import logging import json_stream.requests from src import variables from src.keys_source.base_source import BaseSource from src.providers.keys_api.client import KeysAPIClient from src.providers.keys_api.typings import KeysApiStatus logger = logging.getLogger() class KeysApiSource(BaseSource): def __init__(sel...
lidofinance/ethereum-head-watcher
src/keys_source/keys_api_source.py
.py
6d977cb1c07d3d35
7.5
9
import signal from prometheus_client import start_http_server from web3.middleware import simple_cache_middleware from src import variables from src.handlers.consolidation import ConsolidationHandler from src.handlers.el_triggered_exit import ElTriggeredExitHandler from src.handlers.exit import ExitsHandler from src....
lidofinance/ethereum-head-watcher
src/main.py
.py
05479f8b72f05133
7.5
9
import logging import threading from datetime import datetime, timedelta from http import HTTPStatus from http.server import HTTPServer, SimpleHTTPRequestHandler import requests from src import variables from src.variables import MAX_CYCLE_LIFETIME_IN_SECONDS logger = logging.getLogger() PULSE_PATH = '/pulse/' # Ku...
lidofinance/ethereum-head-watcher
src/metrics/healthcheck_server.py
.py
93ea95d4da22c083
7.5
9
from http import HTTPStatus from typing import Callable, Literal, Union from json_stream.base import TransientStreamingJSONList from requests import Response from urllib3 import Retry from src.metrics.logging import logging from src.metrics.prometheus.basic import CL_REQUESTS_DURATION from src.providers.consensus.typ...
lidofinance/ethereum-head-watcher
src/providers/consensus/client.py
.py
a034a18227fee118
7.5
9
from abc import ABC, abstractmethod from typing import Any, Optional class InconsistentProviders(Exception): pass class NotHealthyProvider(Exception): pass class ProviderConsistencyModule(ABC): """ A class that provides HTTP provider ability to check that provided hosts are alive and chain ids...
lidofinance/ethereum-head-watcher
src/providers/consistency.py
.py
d2cb8436d396091d
7.5
9
from typing import cast from json_stream.base import TransientStreamingJSONList from requests import Response from src.metrics.prometheus.basic import KEYS_API_REQUESTS_DURATION from src.providers.http_provider import HTTPProvider from src.providers.keys_api.typings import KeysApiStatus, LidoNamedKey from src.variabl...
lidofinance/ethereum-head-watcher
src/providers/keys_api/client.py
.py
d46bfbd945dd870d
7.5
9
""" Secrets that arrive as a file, and how a change to it is noticed. Node endpoints carry provider credentials and are delivered as a JSON file, because a process cannot be handed new environment variables from outside: env-based delivery costs a restart per rotation. The file is replaced by a rename, which gives it ...
lidofinance/ethereum-head-watcher
src/secrets.py
.py
9fda3f3f5e54fe84
7.5
9
import functools from dataclasses import dataclass, fields, is_dataclass from types import GenericAlias from typing import Callable, Self, Sequence, TypeVar, Union, get_args, get_origin class DecodeToDataclassException(Exception): pass def try_extract_underlying_type_from_optional(field): args = get_args(fi...
lidofinance/ethereum-head-watcher
src/utils/dataclass.py
.py
969b7ab9e3b36fe8
7.5
9
import logging from dataclasses import dataclass from web3 import Web3 from src.keys_source.keys_api_source import KeysApiSource from src.providers.consensus.typings import BlockDetailsResponse from src.typings import BlockNumber from src.utils.events import get_events_in_range logger = logging.getLogger() @datacl...
lidofinance/ethereum-head-watcher
src/utils/exit.py
.py
06aba959b3868667
7.5
9
import json import os from src.secrets import DEFAULT_POLL_INTERVAL_IN_SECONDS, read_secrets_file # Where the OpenBao agent writes the secrets file, and how often it is re-read. Absent file means every setting comes # from the environment. See src/secrets.py. SECRETS_FILE_PATH = os.getenv('SECRETS_FILE_PATH', '/vault...
lidofinance/ethereum-head-watcher
src/variables.py
.py
62ec2667b9f5087c
7.5
9
import json import logging import threading import time from dataclasses import asdict from functools import cached_property from typing import Optional import json_stream.requests import sseclient from unsync import Unfuture, unsync from src import variables from src.constants import SECONDS_PER_SLOT, SLOTS_PER_EPOC...
lidofinance/ethereum-head-watcher
src/watcher.py
.py
7809f96d11e4f66f
7.5
9
import sys import cv2 import numpy as np from tqdm import tqdm # Workaround for https://github.com/opencv/opencv/issues/21952 cv2.imshow("cv/av bug", np.zeros(1)) cv2.destroyAllWindows() import pupil_labs.neon_recording as nr # noqa: E402 from pupil_labs.neon_recording.timeseries.av.video import ( # noqa: E402 ...
pupil-labs/pl-neon-recording
examples/eye_overlay.py
.py
2667b20019111c7c
7.45
7
"""Neon Recording""" import gc import json import logging import pathlib from functools import cached_property from typing import TypeVar, cast from upath import UPath from pupil_labs.neon_recording.timeseries import ( AudioTimeseries, BlinkTimeseries, EventTimeseries, EyeballTimeseries, EyelidTi...
pupil-labs/pl-neon-recording
src/pupil_labs/neon_recording/neon_recording.py
.py
73ddb917e5ae2804
7.45
7
from functools import cached_property import numpy as np import numpy.typing as npt from .base_av import AVTimeseriesKind, BaseAVTimeseries # TODO: This is not used # class VideoFrame(BaseAVFrame): # _frame: plv.VideoFrame # @property # def bgr(self): # return self._frame.bgr # @property # ...
pupil-labs/pl-neon-recording
src/pupil_labs/neon_recording/timeseries/av/video.py
.py
96db2eb3f57c3fc3
7.45
7
from logging.config import fileConfig from sqlalchemy import engine_from_config from sqlalchemy import pool from alembic import context from acidwatch_api.settings import SETTINGS from acidwatch_api.database import Base # this is the Alembic Config object, which provides # access to the values within the .ini file i...
equinor/acidwatch
backend/alembic/env.py
.py
f110301f02c2b20c
7.57
13
"""refactor simulation to use model_inputs table Revision ID: 01aaa143d690 Revises: c35588effcc4 Create Date: 2026-01-21 16:50:46.128272 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision...
equinor/acidwatch
backend/alembic/versions/01aaa143d690_refactor_simulation_to_use_model_inputs_.py
.py
20104760b4edc11c
7.57
13
"""drop results.python_exception (PickleType) Revision ID: 7c2e1f4b8a90 Revises: 9b4e2c1a7d50 Create Date: 2026-05-19 00:00:00.000000 Removes the ``python_exception`` column on ``results``, which used SQLAlchemy ``PickleType``. Loading that column unpickled arbitrary bytes from the database on every result read, whic...
equinor/acidwatch
backend/alembic/versions/7c2e1f4b8a90_drop_pickle_exception.py
.py
8207f3d63c8c6331
7.57
13
"""add conditions to simulation Revision ID: 9b4e2c1a7d50 Revises: 01aaa143d690 Create Date: 2026-05-06 00:00:00.000000 """ import json from typing import Any, Sequence, Union import sqlalchemy as sa from alembic import op revision: str = "9b4e2c1a7d50" down_revision: Union[str, Sequence[str], None] = "01aaa143d6...
equinor/acidwatch
backend/alembic/versions/9b4e2c1a7d50_add_conditions_to_simulation.py
.py
5ce9abdd90ee0135
7.57
13
"""add unique constraint on results.model_input_id Revision ID: a3f8b2c91d40 Revises: 7c2e1f4b8a90 Create Date: 2026-06-16 00:00:00.000000 Enforces the intended one-to-one relationship between model_inputs and results at the database level. The ORM already declares this as a singular ``Mapped[ModelResult | None]`` re...
equinor/acidwatch
backend/alembic/versions/a3f8b2c91d40_add_unique_constraint_on_results_model_.py
.py
89fe8dae98648600
7.57
13
"""add grid simulations Revision ID: a7f3c9d21b84 Revises: b5d2e3f14a70 Create Date: 2026-06-12 00:00:00.000000 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op revision: str = "a7f3c9d21b84" down_revision: Union[str, Sequence[str], None] = "b5d2e3f14a70" branch_labels: Union[...
equinor/acidwatch
backend/alembic/versions/a7f3c9d21b84_add_sweeps.py
.py
7e11fed430b55a1e
7.57
13
"""replace concentrations with phases Revision ID: b5d2e3f14a70 Revises: a3f8b2c91d40 Create Date: 2026-06-17 00:00:00.000000 Renames the ``concentrations`` JSON column to ``phases`` on both ``simulations`` and ``results``, and transforms existing flat concentration dicts into the new phase-list structure: {"H2O...
equinor/acidwatch
backend/alembic/versions/b5d2e3f14a70_replace_concentrations_with_phases.py
.py
f3073a6b8af796b6
7.57
13
"""initial schema Revision ID: c35588effcc4 Revises: Create Date: 2025-10-21 19:57:33.614284 """ from typing import Sequence, Union from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision: str = "c35588effcc4" down_revision: Union[str, Sequence[str], None] = None branch_la...
equinor/acidwatch
backend/alembic/versions/c35588effcc4_initial_schema.py
.py
52548f52555cfe18
7.57
13
from __future__ import annotations from functools import lru_cache import nh3 from markdown import markdown import textwrap import typing from collections import defaultdict from enum import Enum, StrEnum from typing import ( Annotated, Any, Iterable, Literal, TypeAlias, TypedDict, TypeVar,...
equinor/acidwatch
backend/packages/acidwatch-models/src/acidwatch_models/base.py
.py
f5f0b4d7402ad36b
7.57
13
"""Implementation of the AxesImpl abstract base class.""" import math from .base import Impl __all__ = ['AxesImpl', 'Axis'] type Axis = int | str class AxesImpl[R](Impl[R]): """ Base class for axis metadata containers. AxesImpl is a lightweight container for axis metadata (names, bounds, periodici...
KTH-SML/pyspect
src/pyspect/impls/dev/axes.py
.py
814d906a83c4d73c
8.02
10
""" Base interfaces and metaclasses for implementation plug-ins. This module defines: - Impl: Marker base for concrete implementation backends. - ImplClientMeta: Metaclass that aggregates and propagates required operation names. - ImplClient: Mixin for objects using implementations to declare/query require...
KTH-SML/pyspect
src/pyspect/impls/dev/base.py
.py
e7ad207f03db0892
8.02
10
"""String-based AxesImpl for demonstration and debugging. This module provides StrImpl, an AxesImpl[str] implementation that represents sets and set operations as human-readable strings. It is meant to illustrate that concrete implementations can use any set representation (even plain text), and it doubles as a lightw...
KTH-SML/pyspect
src/pyspect/impls/str.py
.py
14d971587c791408
8.02
10
"""ZonoOpt backend implementations. This module integrates the external ``zonoopt`` library with ``pyspect`` by providing a concrete backend for set operations and reachability queries used during TLT realization. Provided classes: - ``ZonoOptImpl``: Main backend operating on ``zono.HybZono`` sets. - ``Double...
KTH-SML/pyspect
src/pyspect/impls/zonoopt.py
.py
82030c2fc38241c8
8.02
10
from dataclasses import dataclass import numpy as np from hj_reachability import Grid # If @ actually made sense for higher-order tensors tmul = lambda x1, x2: np.tensordot(x1, x2, ([-1], [0])) def complement(shape): """ Calculates the complement of a shape Args: shape (np.ndarray): implicit surface...
KTH-SML/pyspect
src/pyspect/plotting/levelset_shapes.py
.py
ef8fc44883d3c9fc
8.02
10
"""Primitives for temporal logic trees (TLTs). This module defines: - primitive: a decorator class to register TLT primitives tied to tuple-form formulas - Derived connectives built from equivalences (e.g., Minus, Implies, Eventually) - Different sets of primitive TLTs for propositional and temporal operators Concept...
KTH-SML/pyspect
src/pyspect/primitives.py
.py
c93d6516d48e73a9
8.02
10
"""Temporal Logic Trees (TLTs). This module wires tuple-encoded temporal logic formulas (see pyspect.logics) to implementation-agnostic set builders (see pyspect.set_builder) and provides a small runtime for constructing, combining, and realizing TLTs against a concrete implementation Impl[R] (see pyspect.impls.*). K...
KTH-SML/pyspect
src/pyspect/tlt.py
.py
cc5e211c9230f1e7
7.02
10
"""Common utility helpers used across pyspect. This module provides small dictionary and sequence utilities: - iterwin: windowed iteration over indexable sequences - setdefaults: set default values on a dict using several calling styles - collect_keys: pick selected keys (optionally filling a default) - collect_prefix...
KTH-SML/pyspect
src/pyspect/utils/__init__.py
.py
f6b889cad65f98be
8.02
10
import functools import os import ruamel.yaml import subprocess from identify.identify import tags_from_path class NotAGitRepositoryError(Exception): """Raised when the current directory is not a Git repository.""" def get_all_files(): """Yield tracked + untracked-but-unignored files in a Git repo.""" ...
ssciwr/precommend
precommend/core.py
.py
8e7267970cd51e0d
7.42
6
# Copyright (c) 2023 Aditya Kamath # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
adityakamath/tof_imager_ros
tof_imager_ros/tof_imager_publisher.py
.py
29db76a714548771
7.64
18
import pandas as pd import numpy as np from pathlib import Path from typing import Dict, List, Optional, Tuple from dataclasses import dataclass try: from ..core.utils import get_state_code except ImportError: from policyengine_taxsim.core.utils import get_state_code @dataclass class ComparisonConfig: ""...
PolicyEngine/policyengine-taxsim
policyengine_taxsim/comparison/comparator.py
.py
f05cd1cc5f31a77c
7.63
17
from typing import Dict, Any import pandas as pd from .comparator import ComparisonResults from ..core.utils import get_state_code class ComparisonStatistics: """Generate statistics and reports from comparison results""" def __init__(self, results: ComparisonResults, input_data: pd.DataFrame = None): ...
PolicyEngine/policyengine-taxsim
policyengine_taxsim/comparison/statistics.py
.py
32d6e8fe39fd6ee7
7.63
17
from .utils import ( load_variable_mappings, get_state_code, get_ordinal, convert_taxsim32_dependents, ) import copy def add_additional_units(state, year, situation, taxsim_vars): additional_tax_units_config = load_variable_mappings()["taxsim_to_policyengine"][ "household_situation" ][...
PolicyEngine/policyengine-taxsim
policyengine_taxsim/core/input_mapper.py
.py
7754c33c4ffa073d
7.63
17