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 |
|---|---|---|---|---|---|---|
"""Check that priority groups in a pre-commit config file are monotone.
Reads a YAML configuration file (e.g. `.pre-commit-config.yaml`) and extracts
the `priority` field from each hook entry. Verifies that the sequence of
priority values is non-decreasing (monotone), meaning hooks in the same priority
group are adjac... | usethis-python/usethis-python | hooks/check-priority-monotone.py | .py | 580cfc80a3a087b1 | 7.65 | 19 |
"""Export the supported configuration files for each managed tool.
Reads all usethis tool specifications and writes the list of supported
configuration files (in priority order) to an output file. The output can be
compared against documentation to verify it is up to date.
"""
from __future__ import annotations
impo... | usethis-python/usethis-python | hooks/export-config-files.py | .py | df01999012bb1efd | 7.65 | 19 |
"""Export module-level functions with docstrings from a Python package.
Recursively scans all Python source files under a package root directory for
module-level functions with docstrings and writes a flat markdown bullet list
to an output file. Functions are listed in the order they appear in each file,
with files pr... | usethis-python/usethis-python | hooks/export-functions.py | .py | 339815ecb0ded0b6 | 7.65 | 19 |
"""Export the module structure with docstrings to a tree diagram file.
Scans a Python package directory, builds a tree of module names with first-line
module docstrings, and writes the result to an output file using Unicode
box-drawing characters.
"""
from __future__ import annotations
import argparse
import ast
imp... | usethis-python/usethis-python | hooks/export-module-tree.py | .py | e4cfdf6c1e2ed88f | 7.65 | 19 |
"""Fix sync blocks in markdown files to match their source files.
Scans markdown files for comment pairs of the form:
<!-- sync:path/to/file -->
...content...
<!-- /sync:path/to/file -->
and replaces the content between the markers with the referenced file's content,
preserving any markdown fenced code bl... | usethis-python/usethis-python | hooks/fix-doc-sync.py | .py | 3b205381a440eb8b | 7.65 | 19 |
"""Render README.md from a Jinja2 template and docs sources.
Reads a Jinja2 template, renders it by including content from the docs
directory with appropriate transformations (header demotion, link
replacement, callout wrapping), and writes the result to the output file.
Returns exit code 1 if the file was modified (i... | usethis-python/usethis-python | hooks/fix-readme.py | .py | 6acf64b55a24bb24 | 7.65 | 19 |
"""Test utilities and fixtures for the usethis test suite."""
from __future__ import annotations
import copy
import os
import shutil
import socket
import subprocess
from contextlib import contextmanager
from pathlib import Path
from typing import IO, TYPE_CHECKING
import requests
from requests.exceptions import Requ... | usethis-python/usethis-python | src/_test.py | .py | b9e64686be83093f | 7.15 | 19 |
"""Backend selection and dispatch logic."""
from __future__ import annotations
from typing import Literal
from typing_extensions import assert_never
from usethis._backend.poetry.available import is_poetry_available
from usethis._backend.poetry.call import call_poetry_subprocess
from usethis._backend.poetry.detect i... | usethis-python/usethis-python | src/usethis/_backend/dispatch.py | .py | 4511fec65823d429 | 7.65 | 19 |
"""Subprocess wrappers for invoking Poetry commands."""
from __future__ import annotations
import shutil
import tempfile
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING
from usethis._backend.poetry.errors import PoetrySubprocessFailedError
from usethis._config import u... | usethis-python/usethis-python | src/usethis/_backend/poetry/call.py | .py | ef44bd8afa92a8bc | 7.65 | 19 |
"""Dependency group operations via the Poetry backend."""
from __future__ import annotations
from typing import TYPE_CHECKING
from usethis._backend.poetry.call import call_poetry_subprocess
from usethis._backend.poetry.errors import (
PoetryDepGroupError,
PoetrySubprocessFailedError,
)
if TYPE_CHECKING:
... | usethis-python/usethis-python | src/usethis/_backend/poetry/deps.py | .py | 137f915cd5c2b133 | 7.65 | 19 |
"""Project initialization via Poetry."""
from __future__ import annotations
import sys
from usethis._backend.poetry.call import call_poetry_subprocess
from usethis._backend.poetry.errors import PoetryInitError, PoetrySubprocessFailedError
from usethis._file.dir import get_project_name_from_dir
from usethis._file.pyp... | usethis-python/usethis-python | src/usethis/_backend/poetry/init.py | .py | a6fe6cd7c50be590 | 7.65 | 19 |
"""Check whether the uv CLI is available."""
from packaging.requirements import InvalidRequirement
from usethis._backend.uv.call import call_uv_subprocess
from usethis._backend.uv.errors import UVSubprocessFailedError
from usethis._file.pyproject_toml.deps import get_dep_groups, get_project_deps
from usethis._file.py... | usethis-python/usethis-python | src/usethis/_backend/uv/available.py | .py | d7a085076ddf6be5 | 7.65 | 19 |
"""Subprocess wrappers for invoking uv commands."""
from __future__ import annotations
from usethis._backend.uv.errors import UVSubprocessFailedError
from usethis._backend.uv.link_mode import ensure_symlink_mode
from usethis._backend.uv.toml import UVTOMLManager
from usethis._config import usethis_config
from usethis... | usethis-python/usethis-python | src/usethis/_backend/uv/call.py | .py | 6f5eb3cda96f994c | 7.65 | 19 |
"""Dependency group operations via the uv backend."""
from __future__ import annotations
from typing import TYPE_CHECKING
from pydantic import TypeAdapter, ValidationError
from usethis._backend.uv.call import call_uv_subprocess
from usethis._backend.uv.errors import (
UVDepGroupError,
UVSubprocessFailedErro... | usethis-python/usethis-python | src/usethis/_backend/uv/deps.py | .py | cd35b29a85ce511e | 7.65 | 19 |
"""Project initialization via uv."""
from __future__ import annotations
from usethis._backend.uv import ( # Use this style to allow test mocking
call,
)
from usethis._backend.uv.errors import UVInitError, UVSubprocessFailedError
from usethis._config import usethis_config
from usethis._file.dir import get_project... | usethis-python/usethis-python | src/usethis/_backend/uv/init.py | .py | 23ae5a67cfd9d477 | 7.65 | 19 |
"""Manager for the uv.toml configuration file."""
from pathlib import Path
from typing_extensions import override
from usethis._file.toml.io_ import TOMLFileManager
class UVTOMLManager(TOMLFileManager):
"""Class to manage the uv.toml file."""
@property
@override
def relative_path(self) -> Path:
... | usethis-python/usethis-python | src/usethis/_backend/uv/toml.py | .py | ed826564ba30959a | 7.15 | 19 |
"""Global configuration state for usethis."""
from __future__ import annotations
from contextlib import contextmanager
from dataclasses import dataclass, fields, replace
from pathlib import Path
from typing import TYPE_CHECKING, Literal
from usethis._types.backend import BackendEnum
from usethis._types.build_backend... | usethis-python/usethis-python | src/usethis/_config.py | .py | ee585d148d1b2f1d | 7.65 | 19 |
"""README badge generation and management."""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import TYPE_CHECKING
from pydantic import BaseModel
from usethis._config import usethis_config
from usethis._console import plain_print, tick_print, warn_print
from usethis._core.... | usethis-python/usethis-python | src/usethis/_core/badge.py | .py | ce0675e1aa0b9b0a | 7.65 | 19 |
"""List tools and their usage status."""
from typing import Literal
from pydantic import BaseModel
from rich.table import Table
from typing_extensions import assert_never
from usethis._console import table_print
from usethis._detect.readme import is_readme_used
from usethis._tool.all_ import ALL_TOOLS
from usethis._... | usethis-python/usethis-python | src/usethis/_core/list.py | .py | b09343315f7dd51d | 7.65 | 19 |
"""Linter rule selection and configuration."""
from pydantic import BaseModel
from usethis._core.tool import use_deptry, use_ruff
from usethis._tool.impl.base.deptry import DeptryTool
from usethis._tool.impl.base.ruff import RuffTool
class RulesMapping(BaseModel):
ruff_rules: list[str]
deptry_rules: list[st... | usethis-python/usethis-python | src/usethis/_core/rule.py | .py | b0e2f5446b66afd2 | 7.65 | 19 |
"""Display project information."""
from __future__ import annotations
from typing import TYPE_CHECKING
from usethis._backend.dispatch import get_backend
from usethis._console import plain_print
from usethis._integrations.project.license import get_license_id
from usethis._integrations.project.name import get_project... | usethis-python/usethis-python | src/usethis/_core/show.py | .py | c2b3ba04892e485a | 7.65 | 19 |
"""The Vaillant Plus integration."""
from __future__ import annotations
import logging
import asyncio
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_STOP, Platform
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_... | daxingplay/home-assistant-vaillant-plus | custom_components/vaillant_plus/__init__.py | .py | 80854bba10a434e1 | 7.59 | 14 |
"""The Vaillant Plus climate platform."""
from __future__ import annotations
import logging
from typing import Any
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
PRESET_COMFORT,
ClimateEntityFeature,
HVACAction,
HVACMode,
)
from homeassi... | daxingplay/home-assistant-vaillant-plus | custom_components/vaillant_plus/climate.py | .py | c9fb83fc33678f73 | 7.59 | 14 |
"""Config flow for Vaillant Plus integration."""
from __future__ import annotations
import logging
from typing import Any
from homeassistant import config_entries
from homeassistant.data_entry_flow import FlowResult
from vaillant_plus_cn_api import (
Device,
Token,
VaillantApiClient,
)
import voluptuous a... | daxingplay/home-assistant-vaillant-plus | custom_components/vaillant_plus/config_flow.py | .py | b07bc2674750a929 | 7.59 | 14 |
"""Vaillant vSMART entity classes."""
import logging
from typing import Any
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity, DeviceInfo
from vaillant_plus_cn_api import Device
from .client import VaillantClie... | daxingplay/home-assistant-vaillant-plus | custom_components/vaillant_plus/entity.py | .py | 7dd70af19ca73922 | 7.59 | 14 |
"""The Vaillant Plus water heater platform."""
from __future__ import annotations
import logging
from typing import Any
from homeassistant.components.water_heater import (
WaterHeaterEntity,
WaterHeaterEntityFeature,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_T... | daxingplay/home-assistant-vaillant-plus | custom_components/vaillant_plus/water_heater.py | .py | 0a81084b6da2a5a0 | 7.59 | 14 |
"""Global fixtures for vaillant-plus integration."""
# Fixtures allow you to replace functions with a Mock object. You can perform
# many options via the Mock to reflect a particular behavior from the original
# function that you want to see without going through the function's actual logic.
# Fixtures can either be pa... | daxingplay/home-assistant-vaillant-plus | tests/conftest.py | .py | 0dab10d6bb719d27 | 8.09 | 14 |
"""Test vaillant-plus config flow."""
from unittest.mock import patch
from homeassistant import config_entries
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult, FlowResultType
import pytest
from pytest_homeassistant_custom_component.common import MockConfigEntry
from c... | daxingplay/home-assistant-vaillant-plus | tests/test_config_flow.py | .py | 9b32d55cf297185c | 7.09 | 14 |
"""Static checks for partial websocket update handling."""
from __future__ import annotations
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def test_sensor_entities_ignore_partial_updates_without_their_key():
"""Sensor update handlers should keep state when an update omits their key."""
... | daxingplay/home-assistant-vaillant-plus | tests/test_partial_update_guards.py | .py | 1084ee863b87aaf5 | 7.09 | 14 |
import requests
from fastapi import FastAPI, Query, HTTPException, Request
from fastapi.responses import StreamingResponse, HTMLResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from query_weibo import get_headers
from datetime import datetime
import threading
from typing import List, Dict, Any
app... | kirayomato/vtb_dynamic_push | image_proxy.py | .py | 8a2240cf99157373 | 7.57 | 13 |
import logging
from logging.handlers import TimedRotatingFileHandler
import sys
import os
import threading
from colorama import Fore, Style
from time import time
from collections import deque
from reprint import output
from web import output_stream
import shutil
from datetime import datetime, timedelta
import unicodeda... | kirayomato/vtb_dynamic_push | logger.py | .py | 8d3716f78710db34 | 7.57 | 13 |
from collections import defaultdict
import time
import threading
from typing import Dict, List, Optional
from push import global_config as config
from math import sqrt
class Scheduler:
def __init__(self):
self.items: Dict[Dict] = {}
self.total_weight = 0
self.access_times = defaultdict(lis... | kirayomato/vtb_dynamic_push | scheduler.py | .py | 5a1f6275c69e4009 | 7.57 | 13 |
from __future__ import annotations
import dataclasses
import re
from collections.abc import Mapping, Sequence
from packaging.requirements import Requirement
def _normalize_name(name: str) -> str:
return re.sub(r"[-_.]+", "-", name).lower()
def _normalize_group_names(
dependency_groups: Mapping[str, Sequen... | pypa/dependency-groups | src/dependency_groups/_implementation.py | .py | 4cce6817480310fb | 7.59 | 14 |
from __future__ import annotations
import typing as t
import pytest
if t.TYPE_CHECKING:
import pathlib
from conftest import CliRunner, RunnerFactory
@pytest.fixture
def invoked_pip_args(monkeypatch: pytest.MonkeyPatch) -> list[list[str]]:
calls: list[list[str]] = []
monkeypatch.setattr("dependency... | pypa/dependency-groups | tests/test_pip_wrapper_cli.py | .py | 1e69f3aaeb276e0a | 7.09 | 14 |
import os
from collections.abc import Iterable
from zlib import crc32
from .reporter import set_func_coverage
from .reporter import set_line_coverage
class ToffeeRequest:
from pytest import FixtureRequest
def __init__(self, request: FixtureRequest):
self.dut = None
self.args = None
se... | XS-MLVP/toffee-test | toffee_test/request.py | .py | 6edd2661cd4500da | 7.95 | 7 |
import numpy as np
# entries smaller than this will be clipped to 0
JOYSTICK_DEADZONE = 0.2
# max and min values for joystick
JOYSTICK_MIN = -1.0
JOYSTICK_MAX = 1.0
# separating values for bins of joystick action discretisation
JOYSTICK_BINS = [-0.99, -0.7, -0.45, -0.2, 0.2, 0.45, 0.7, 0.99]
# trigger threshold for d... | microsoft/imitation_learning_in_modern_video_games | pixelbc/data/actions.py | .py | a9e34292cd31b313 | 7.62 | 16 |
from enum import Enum
import numpy as np
class CSGO_ACTIONS(Enum):
SHOOT = 0
MOUSE_X = 1
MOUSE_Y = 2
CSGO_MOUSE_X_BIN_CENTERS = [
-1000.0,
-500.0,
-300.0,
-200.0,
-100.0,
-60.0,
-30.0,
-20.0,
-10.0,
-4.0,
-2.0,
-0.0,
2.0,
4.0,
10.0,
20.0,
... | microsoft/imitation_learning_in_modern_video_games | pixelbc/data/csgo_actions.py | .py | 083743c884a33af5 | 7.62 | 16 |
from pathlib import Path
def get_file_paths_from_split_file(path, base_path=None, relative_path=True):
"""
Get files from the given split file, relative to base_path if given.
:param path: Path to split file.
:param base_path: Base path to add to files.
:param relative_path: Whether to given path ... | microsoft/imitation_learning_in_modern_video_games | pixelbc/data/data_split.py | .py | 8dfdd4bb57080bef | 7.62 | 16 |
# Image preprocessing for np.array. This only handles resizing and cropping! Further augmentations including normalisation and image augmentations
# are handled in the encoders.
from functools import partial
import cv2
import numpy as np
from albumentations import Compose, augmentations
from pixelbc.models.encoders.p... | microsoft/imitation_learning_in_modern_video_games | pixelbc/data/image_preprocessing.py | .py | 9b150ebce7330b39 | 7.62 | 16 |
import cv2
import numpy as np
DEFAULT_FRAMESTACKING = 1
def load_image(path):
"""
Load an image from a path and return as RGB.
:param path: The path to the image.
:return: The loaded image as RGB.
"""
# load image as BGR
img = cv2.imread(str(path))
img = cv2.cvtColor(img, cv2.COLOR_BG... | microsoft/imitation_learning_in_modern_video_games | pixelbc/data/images.py | .py | 997e65ae5472f524 | 7.62 | 16 |
import numpy as np
from pixelbc.data.actions import discretise_individual_joystick_action
# map from xbox controller names to MineRL VPT buttons in JSON data.
# This is arbritraly chosen, as original MineRL VPT data is in keyboard/mouse space.
# Right joystick will be used for mouse movement.
# Left joystick will be ... | microsoft/imitation_learning_in_modern_video_games | pixelbc/data/minerl_actions.py | .py | c7508d4706ede2bf | 7.62 | 16 |
import warnings
import lightning.pytorch as pl
import torch
from lightning.pytorch.utilities import grad_norm
from torch.distributions import Bernoulli, Categorical
from pixelbc.models.encoders import get_encoder
from pixelbc.models.utils import get_model
from pixelbc.models.utils.loss_utils import compute_button_los... | microsoft/imitation_learning_in_modern_video_games | pixelbc/models/bc_model.py | .py | 8feee2bf6dd36aff | 7.62 | 16 |
# source: https://github.com/Miffyli/minecraft-bc-2020/blob/master/torch_codes/modules.py
import torch
from torch import nn
class NatureDQNCNN(nn.Module):
"""The CNN head from Nature DQN paper"""
def __init__(self, in_channels=3):
super().__init__()
self.head = nn.Sequential(
nn.C... | microsoft/imitation_learning_in_modern_video_games | pixelbc/models/encoders/dqn_cnn.py | .py | 26aa69065bc7602c | 7.62 | 16 |
# Source: https://github.com/Miffyli/minecraft-bc-2020/blob/master/torch_codes/modules.py
import math
import torch
import torch.nn.functional as F
from torch import nn
# References:
# [1] IMPALA. https://arxiv.org/pdf/1802.01561.pdf
# [2] R2D3. https://arxiv.org/pdf/1909.01387.pdf
# [3] Unixpickle's work https://git... | microsoft/imitation_learning_in_modern_video_games | pixelbc/models/encoders/impala_resnet.py | .py | 8fcaf82518d80b66 | 7.62 | 16 |
import warnings
from contextlib import nullcontext
import clip
import timm
import torch
from diffusers import AutoencoderKL
from pixelbc.models.encoders.encoders import ImageEncoder
from pixelbc.models.utils.image_augmentations import (
clip_transform,
dino_transform,
focalnet_transform,
stablediffusi... | microsoft/imitation_learning_in_modern_video_games | pixelbc/models/encoders/pretrained_encoders.py | .py | 86e95e94fda3eb66 | 7.62 | 16 |
# modelled after https://arxiv.org/abs/2201.03545
# largely from humanmodelling/models/nn/model_blocks.py
import numpy as np
from torch import nn
class ConvNextBlock(nn.Module):
"""Conv layer which keeps the dimensionality the same."""
def __init__(self, channels, activations="relu"):
super().__init_... | microsoft/imitation_learning_in_modern_video_games | pixelbc/models/encoders/resnet.py | .py | 371381d9c1c860a1 | 7.62 | 16 |
# Image augmentations for torch.Tensor. This only handles normalisation and image augmentations!
# Reshaping and cropping is handled by the data processing.
import torch
from torchvision import transforms
CLIP_NORMALISATION_MEAN = (0.48145466, 0.4578275, 0.40821073)
CLIP_NORMALISATION_STD = (0.26862954, 0.26130258, 0.... | microsoft/imitation_learning_in_modern_video_games | pixelbc/models/utils/image_augmentations.py | .py | bb5cee7c78ebda18 | 7.62 | 16 |
from abc import ABC, abstractmethod
import torch
import torch.nn.functional as F
from torch import nn
class BackboneModel(ABC):
def init_for_sequence(self, batch_size):
pass
@abstractmethod
def forward(self, x, rollout=False):
raise NotImplementedError
class MLP(nn.Module, BackboneMode... | microsoft/imitation_learning_in_modern_video_games | pixelbc/models/utils/model_utils.py | .py | 79451f285a625bdb | 7.62 | 16 |
# From humanmodelling even more barebones version of NanoGPT.py
# Original license:
# From https://github.com/karpathy/nanoGPT/blob/master/model.py - Thanks Andrej Karpathy
# MIT License
# Copyright (c) 2022 Andrej Karpathy
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... | microsoft/imitation_learning_in_modern_video_games | pixelbc/models/utils/pico_gpt.py | .py | 952a29fcaa7759e4 | 7.62 | 16 |
from typing import Dict
import torch
from torch import Tensor
def get_binary_metrics_independent(button_pred: Tensor, button_target: Tensor) -> Dict[str, float]:
"""
Compute metrics for binary classification predictions (e.g. buttons) where each class is independently
evaluated and metrics are aggreg... | microsoft/imitation_learning_in_modern_video_games | pixelbc/models/utils/train_metrics.py | .py | 367b464c2adfff23 | 7.62 | 16 |
import json
import struct
import time
from ctypes import *
from http.server import BaseHTTPRequestHandler, HTTPServer
from pymem import *
ReadProcessMemory = windll.kernel32.ReadProcessMemory
WriteProcessMemory = windll.kernel32.WriteProcessMemory
# stuff for RAM...
def update_offsets(raw):
raw = raw.replace("[... | microsoft/imitation_learning_in_modern_video_games | pixelbc/online_rollout/csgo_utils/meta_utils.py | .py | 8bfab3bc897893bd | 7.62 | 16 |
# Taken from following MIT-licensed repo:
# https://github.com/TeaPearce/Counter-Strike_Behavioural_Cloning
import time
# adapted from: https://github.com/Sentdex/pygta5/blob/master/grabscreen.py
import cv2
import numpy as np
import win32con
import win32gui
import win32ui
from pixelbc.online_rollout.csgo_utils.conf... | microsoft/imitation_learning_in_modern_video_games | pixelbc/online_rollout/csgo_utils/screen_input.py | .py | 61070072a138b141 | 7.62 | 16 |
import time
from collections import deque
import ffmpegcv
import numpy as np
from gym import Wrapper
from gym.wrappers.time_limit import TimeLimit
from minerl.herobraine.env_specs.human_survival_specs import HumanSurvival
from pixelbc.data.minerl_actions import minerl_model_output_to_minerl_action
from pixelbc.online... | microsoft/imitation_learning_in_modern_video_games | pixelbc/online_rollout/minerl_rollout.py | .py | 9050f011d10ba806 | 7.62 | 16 |
import json
import time
from abc import abstractmethod
from pathlib import Path
import numpy as np
import torch
from omegaconf import OmegaConf
from pixelbc.data.image_preprocessing import get_preprocessing_function_and_image_shape
from pixelbc.models.utils.model_utils import count_parameters
from pixelbc.utils.load_... | microsoft/imitation_learning_in_modern_video_games | pixelbc/online_rollout/online_rollout.py | .py | d0961559f5b55712 | 7.62 | 16 |
# Plot bunch of MineRL results in one plot
# Input is bunch of directories.
# We then search for all seeds (i.e. f"{directory_name}_seed_#/")
import json
from argparse import ArgumentParser
from collections import defaultdict
from pathlib import Path
import numpy as np
import seaborn as sns
import yaml
from scipy.s... | microsoft/imitation_learning_in_modern_video_games | pixelbc/plotting/csgo_report_results.py | .py | a1132c916d4b3c6b | 7.62 | 16 |
# Plot bunch of MineRL results in one plot
# Input is bunch of directories.
# We then search for all seeds (i.e. f"{directory_name}_seed_#/")
import glob
import json
import os
from argparse import ArgumentParser
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
import seaborn as... | microsoft/imitation_learning_in_modern_video_games | pixelbc/plotting/minerl_plot_treechop.py | .py | faf1a33b455022b1 | 7.62 | 16 |
#!/usr/bin/env python3
"""This is the script for generating image embeddings using a pretrained encoder.
We load images from all video files in a sequential order and save embeddings in a specified folder
Example:
>>> CUDA_VISIBLE_DEVICES=0 \
>>> scripts/generate_embeddings.py \
>>> --game csgo \
>>> ... | microsoft/imitation_learning_in_modern_video_games | pixelbc/scripts/generate_embeddings.py | .py | c8bcd97e1f3fabc8 | 7.62 | 16 |
# Script for filtering down bunch of MineRL VPT .jsonl files to find valid episodes for treechop task:
# starting from fresh world, gather a single log within specified timeframe.
import glob
import json
# This process was done on the MineRL VPT 6.13 dataset
import os
from tqdm import tqdm
RECORDING_FPS = 20
# One... | microsoft/imitation_learning_in_modern_video_games | pixelbc/scripts/minerl_filter_valid_treechop_trajectories.py | .py | 1af616d5638d0448 | 7.62 | 16 |
import psutil
from lightning.pytorch import Callback
from lightning.pytorch.callbacks import DeviceStatsMonitor, ModelCheckpoint
from lightning.pytorch.loggers import TensorBoardLogger
from lightning.pytorch.utilities import rank_zero_only
class DeviceStatsMemoryMonitor(DeviceStatsMonitor):
def _log_memory(self, ... | microsoft/imitation_learning_in_modern_video_games | pixelbc/utils/callbacks.py | .py | 1cca47d049a2924c | 7.62 | 16 |
import shutil
import warnings
from pathlib import Path
import torch
from omegaconf import OmegaConf
from pixelbc.data.data_split import get_file_paths_from_split_file
def _load_default_config(config_path):
# load default config relative to given config
default_config_path = Path(config_path).parent / "defau... | microsoft/imitation_learning_in_modern_video_games | pixelbc/utils/config_utils.py | .py | b1ba43a6e9efb07e | 7.62 | 16 |
import torch
from omegaconf import OmegaConf
from pixelbc.models.bc_model import BCModel
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def get_backwards_compatibility_kwargs(hyperparameters):
"""
From checkpoint hyperparameters dictionary, extract all hyperparameters that are needed ... | microsoft/imitation_learning_in_modern_video_games | pixelbc/utils/load_checkpoint.py | .py | 0fc13fb96520d84a | 7.62 | 16 |
import torch
import os
import torch.utils.data
import torch.nn.functional as F
import soundfile as sf
import numpy as np
import pandas as pd
import random
from glob import glob
from utils.utils import crop_or_extend, apply_RIR_delay
class AudioDatasetInfinite_VCTK_Reverb(torch.utils.data.IterableDataset):
"""
... | microsoft/GFB-audio-control | src/datasets/datasets.py | .py | 189115e0b6f89f7d | 7.45 | 7 |
import torch
import numpy as np
from tqdm import tqdm
import einops
import ot as pot
from functools import partial
def calculate_curvature(trajectory):
#as used in the paper, just for reference
base=trajectory[0]-trajectory[-1]
base=base.reshape(base.shape[0], -1)
N=len(trajectory)
dt=1.0/N
mse... | microsoft/GFB-audio-control | src/diffusion/OTCFM.py | .py | 4ecdbdf6d49aa2d8 | 7.45 | 7 |
import os
import einops
import torch.nn.functional as F
import random
import torch
import soundfile as sf
def save_audio(preds, save_path, string, sample_rate):
file_name=save_path / (string+".wav")
#save the audio
preds=einops.rearrange(preds,'b c t -> (b c t)')
sf.write(file_name, preds.squeeze().cp... | microsoft/GFB-audio-control | src/utils/utils.py | .py | dcaeeca56c73b460 | 7.45 | 7 |
"""Noxfile."""
import shutil
from pathlib import Path
import nox
nox.options.default_venv_backend = "none"
nox.options.sessions = ["lints"]
CLEANABLE_TARGETS = [
"./dist",
"./build",
"./.nox",
"./.coverage",
"./.coverage.*",
"./coverage.json",
"./**/.mypy_cache",
"./**/.pytest_cache... | letsbuilda/imsosorry | noxfile.py | .py | ad545c043353492e | 7.5 | 9 |
"""The ancient arts of Uwuification."""
from __future__ import annotations
import random
import re
from functools import partial
WORD_REPLACE = {
"small": "smol",
"cute": "kawaii~",
"fluff": "floof",
"love": "luv",
"stupid": "baka",
"idiot": "baka",
"what": "nani",
"meow": "nya~",
... | letsbuilda/imsosorry | src/imsosorry/uwuification.py | .py | a7f5672949fcad4c | 7.5 | 9 |
"""Test the arts of Uwuification."""
from __future__ import annotations
import pytest
from imsosorry.uwuification import (
EMOJIS,
char_replace,
emoji,
nyaify,
stutter,
tildify,
uwuify,
word_replace,
)
@pytest.mark.parametrize(
("in_text", "out_text"),
[
("cats are s... | letsbuilda/imsosorry | tests/test_uwuification.py | .py | 71fd5a4f1379451f | 7 | 9 |
"""One sine lifting function."""
from typing import Optional, Tuple
import numpy as np
import pykoop
class OneSineLiftingFn(pykoop.koopman_pipeline.EpisodeIndependentLiftingFn):
"""Lifting function with one sine wave with phase offset.
This class implements the ``EpisodeIndependentLiftingFn`` interface fro... | decargroup/robust_observer_koopman | onesine.py | .py | 69ca01958deacfcb | 7.56 | 12 |
"""Calculate the optimal transfer function to bound residual magnitudes.
Thanks to Jonathan Eid for providing the initial version of this function.
"""
import control
import numpy as np
import scipy.optimize
def tf_cover(
omega: np.array,
upper_bound: np.array,
degree: int,
) -> control.TransferFunction... | decargroup/robust_observer_koopman | tf_cover.py | .py | 2c64bc1e87a5bd72 | 7.56 | 12 |
import os
# import spring.linklink as link
import numpy as np
import torch
from torch.utils.data import Dataset
try:
import mc
except ImportError:
pass
# import ceph
# from petrel_client.client import Client
class BaseDataset(Dataset):
def __init__(self,
root_dir,
meta_fi... | Shwai-He/PAD-Net | dyconv/data/datasets/base_dataset.py | .py | ea1e50cbcb803d04 | 7.59 | 14 |
try:
from SpringCommonInterface import Metric as SCIMetric
except ImportError:
SCIMetric = object
class Metric(SCIMetric):
def __init__(self, metric={}, cmp_key=''):
if SCIMetric != object:
super(Metric, self).__init__(metric.get(cmp_key, -1))
self.metric = metric
self.... | Shwai-He/PAD-Net | dyconv/data/metrics/base_evaluator.py | .py | 614c43fea4bc9e31 | 7.59 | 14 |
import math
import json
import numpy as np
from sklearn import metrics
from .base_evaluator import Evaluator, Metric
from utils.misc import get_logger
class CustomMetric(Metric):
def __init__(self, metric_dict={}):
self.metric = metric_dict
super(CustomMetric, self).__init__(self.metric)
def ... | Shwai-He/PAD-Net | dyconv/data/metrics/custom_evaluator.py | .py | 579fb4530b5fa417 | 7.59 | 14 |
import torch
from torch import nn
from torch.nn import *
from typing import TypeVar
T = TypeVar('T', bound=Module)
class Conv2dWrapper(nn.Conv2d):
"""
Wrapper for pytorch Conv2d class which can take additional parameters(like temperature) and ignores them.
"""
def __init__(self, *args, **kwargs):
... | Shwai-He/PAD-Net | dyconv/model/layer/common.py | .py | b750d25ae2232056 | 7.59 | 14 |
import torch
import torch.nn as nn
from torch.nn import init
import spring.linklink as link
from prototype.utils.misc import get_bn
__all__ = ['mobilenet_v2']
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel ... | Shwai-He/PAD-Net | dyconv/model/mobilenetv2.py | .py | 3c145114548219c4 | 7.59 | 14 |
"""
Creates a MobileNetV2 Model as defined in:
Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen. (2018).
MobileNetV2: Inverted Residuals and Linear Bottlenecks
arXiv preprint arXiv:1801.04381.
import from https://github.com/tonylins/pytorch-mobilenet-v2
"""
import torch
import torch.nn as ... | Shwai-He/PAD-Net | dyconv/model/mobilenetv2_dcd.py | .py | b67b928ca9de9823 | 7.59 | 14 |
"""
Creates a MobileNetV2 Model as defined in:
Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen. (2018).
MobileNetV2: Inverted Residuals and Linear Bottlenecks
arXiv preprint arXiv:1801.04381.
import from https://github.com/tonylins/pytorch-mobilenet-v2
"""
import torch
import torch.nn as ... | Shwai-He/PAD-Net | dyconv/model/mobilenetv2_dcd_pad.py | .py | 837d1729d0f4a2f5 | 7.59 | 14 |
import torch.nn as nn
import torch
from .layer.dyconv import DynamicConvolution, Conv2d, dynamic_convolution_generator
from .layer.common import CustomSequential, TempModule
import math
__all__ = ['Dymobilenetv2', 'DyMobileNetV2']
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from... | Shwai-He/PAD-Net | dyconv/model/mobilenetv2_dyconv.py | .py | 1a8e37c686c9e210 | 7.59 | 14 |
import torch.nn as nn
import torch
from .layer.dyconv import fuse_convolution_generator, Conv2d, PAD_DynamicConvolution
from .layer.common import CustomSequential, TempModule
import math
ConvLayer = PAD_DynamicConvolution
__all__ = ['Dymobilenetv2_PAD', 'DyMobileNetV2_PAD']
def _make_divisible(v, divisor, min_value=N... | Shwai-He/PAD-Net | dyconv/model/mobilenetv2_dyconv_pad.py | .py | ab2485060140185a | 7.59 | 14 |
from tqdm import tqdm
import pruners
import numpy as np
def prune_loop(model, loss, pruner, dataloader, device, sparsity, schedule, scope, epochs,
reinitialize=False, train_mode=False, shuffle=False, invert=False):
r"""Applies score mask loop iteratively to a final sparsity level.
"""
# Set ... | Shwai-He/PAD-Net | dyconv/prune.py | .py | 0bf1ac2edf1795f8 | 7.59 | 14 |
"""
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import logging
import json
from typing import Dict
from omegaconf import OmegaConf
from lavis.com... | Shwai-He/VLM-Compression | lavis/common/config.py | .py | 3d5c68ef55fe5484 | 7.63 | 17 |
"""
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import datetime
import functools
import os
import torch
import torch.distributed as dist
import t... | Shwai-He/VLM-Compression | lavis/common/dist_utils.py | .py | 5afeea8f75108adb | 7.63 | 17 |
"""
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
__author__ = "aagrawal"
__version__ = "0.9"
# Interface for accessing the VQA dataset.
# This co... | Shwai-He/VLM-Compression | lavis/common/vqa_tools/vqa.py | .py | 8d1cc77c4afc216c | 7.63 | 17 |
import torch
import torch.nn as nn
import numpy as np
from lavis.common.registry import registry
from lavis.compression.pruners.utils import (
loss_vision_language, loss_language, loss_vision, print_time
)
from lavis.compression.pruners.layer_single_base_pruner import LayerWiseBasePruner, LayerSparsity
def get_m... | Shwai-He/VLM-Compression | lavis/compression/pruners/global_pruner.py | .py | f79aea71429b720f | 7.63 | 17 |
"""
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import logging
import os
import shutil
import warnings
import lavis.common.utils as utils
import ... | Shwai-He/VLM-Compression | lavis/datasets/builders/c4_dataset_builder.py | .py | 43faaa58cf78bbab | 7.63 | 17 |
"""
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
from lavis.common.registry import registry
from lavis.datasets.builders.base_dataset_builder impor... | Shwai-He/VLM-Compression | lavis/datasets/builders/classification_builder.py | .py | 07deb88cd820f300 | 7.63 | 17 |
"""
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import os
from lavis.common.registry import registry
from lavis.datasets.builders.base_dataset_bu... | Shwai-He/VLM-Compression | lavis/datasets/builders/image_text_pair_builder.py | .py | c626b6a8ead05fad | 7.63 | 17 |
"""
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import sys
sys.path.append('/mnt/petrelfs/dongdaize.d/workspace/sh/ECoFLaP/LAVIS')
import time
fro... | Shwai-He/VLM-Compression | lavis/datasets/download_scripts/DownloadConceptualCaptions/download_data_cc12m.py | .py | a148bb320247f251 | 7.63 | 17 |
"""
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import os
from pathlib import Path
from omegaconf import OmegaConf
import sys
sys.path.append('/... | Shwai-He/VLM-Compression | lavis/datasets/download_scripts/download_didemo.py | .py | f217e9c98af8022b | 7.63 | 17 |
"""
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import os
from pathlib import Path
from omegaconf import OmegaConf
import sys
sys.path.append('/... | Shwai-He/VLM-Compression | lavis/datasets/download_scripts/download_msrvtt.py | .py | 90bb87d1708e13e8 | 7.63 | 17 |
"""
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import os
from pathlib import Path
from omegaconf import OmegaConf
import sys
sys.path.append('/... | Shwai-He/VLM-Compression | lavis/datasets/download_scripts/download_msvd.py | .py | 5418b92744b3a6e3 | 7.63 | 17 |
"""
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import json
import logging
import os
import time
from multiprocessing import Pool
import sys
sys.... | Shwai-He/VLM-Compression | lavis/datasets/download_scripts/download_nocaps.py | .py | 6b10e6f1be623f53 | 7.63 | 17 |
from util import resource_path
from core import *
import yaml
import os
import shutil
# Directory holding the pristine, committed config presets. `default` is the
# baseline preset seeded on first run; future themed presets (e.g. `hard`,
# `easy`) are sibling folders, each a full set of per-game config files.
... | Dechrissen/dexelect | data/loader.py | .py | ee37dba563b8ae59 | 7.52 | 10 |
# needed for type hint annotation in methods, because otherwise there will be a type hint forward reference
# issue (the Pokemon class which is being referenced isn't defined yet)
from __future__ import annotations
class Pokemon:
def __init__(self,
name: str,
nat_dex_number... | Dechrissen/dexelect | models/pokemon.py | .py | 129863e98eda6145 | 7.52 | 10 |
import yaml
from pathlib import Path
import pytest
BASE = Path(__file__).resolve().parents[1] # root of project
def find_yaml_files():
"""Yields (path, category) for all YAMLs in data/ subfolders."""
for path in (BASE / "data").rglob("*.yaml"):
name = path.name.lower()
if "pokedex" i... | Dechrissen/dexelect | tests/conftest.py | .py | 1e49db561c5075e2 | 8.02 | 10 |
import yaml
from pathlib import Path
import pytest
# determine project root: one level up from tests/
ROOT = Path(__file__).resolve().parents[1]
# absolute path to mappings.yaml
MAPPINGS_PATH = ROOT / "data" / "mappings.yaml"
def load_mappings():
with MAPPINGS_PATH.open() as f:
return yaml.sa... | Dechrissen/dexelect | tests/test_mappings_filepaths_exist.py | .py | f63d8c48e3aa30ed | 8.02 | 10 |
# Copyright 2026 Derek Andersen
# https://derekandersen.net
# https://github.com/Dechrissen/
"""
Shared "Export Party" rendering for the desktop GUI and the web UI.
Turns a generated party blob into the export .txt content by filling
ui/export_template.txt ({{ placeholder }} substitution — no template-engine
dependenc... | Dechrissen/dexelect | ui/export.py | .py | ee128f210bb0d6e6 | 7.52 | 10 |
# Copyright 2026 Derek Andersen
# https://derekandersen.net
# https://github.com/Dechrissen/
"""
Flask web UI for Dexelect — a third `--ui` option `web` alongside `cli` and `gui`.
Design: stateless and multi-game. Every request carries
its own game / config / sphere_mode, so no per-user working files are seeded and
no... | Dechrissen/dexelect | ui/web/app.py | .py | d4b246924b95903e | 7.52 | 10 |
import sys, os
def resource_path(relative_path):
"""Works for both dev and PyInstaller."""
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def format_duration(seconds):
"""Formats as 'XXXms' (... | Dechrissen/dexelect | util.py | .py | 4c4179a4981802af | 7.02 | 10 |
""" this module handles the implementation of batch jobs using celery to support asynchronous
requests
"""
from datetime import datetime
from typing import Any, Dict, Iterable, List, Optional, Tuple
from openeo_driver.backend import BatchJobMetadata, BatchJobResultMetadata, BatchJobs
from openeo_driver.errors import ... | IBM/tensorlakehouse | tensorlakehouse_openeo_driver/batch_jobs.py | .py | b8c0debd0f6d758a | 7.62 | 16 |
"""Core module for salutation."""
__copyright__ = """
LICENSED INTERNAL CODE. PROPERTY OF IBM.
IBM Research Licensed Internal Code
(C) Copyright IBM Corp. 2023
ALL RIGHTS RESERVED
"""
from typing import Optional
import click
def salutation():
"""Return salutation string."""
return "Gruezi Mitenand"
# this... | IBM/tensorlakehouse | tensorlakehouse_openeo_driver/complex_module/core.py | .py | cd5a6a8443a98942 | 7.62 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.