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
"""Button entities for Acaia scales.""" from collections.abc import Callable, Coroutine from dataclasses import dataclass from typing import Any, override from aioacaia import AcaiaScale from homeassistant.components.button import ButtonEntity, ButtonEntityDescription from homeassistant.core import HomeAssistant fro...
Teslemetry/hass-teslemetry
homeassistant/components/acaia/button.py
.py
4e0ed8f6119e4aff
7.64
18
import requests import xml.etree.ElementTree as ET from datetime import datetime, UTC from collections import defaultdict from pathlib import Path import json import os import logging # 配置日志 logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(message)s", datefmt="%H:%M:%S" ) logger = logging.getLogger...
labex-labs/labex-sitemap
update_sitemap.py
.py
223cfb27bebfa804
7.45
7
#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = [] # /// """Analyze the counterweight JSON devlog and print timing statistics.""" import argparse import json import statistics import subprocess from collections import defaultdict def fetch(last: int) -> list[dict]: re...
JoshKarpel/counterweight
.claude/skills/cw-profile/scripts/analyze_devlog.py
.py
b45a2025f500d9f6
7.64
18
from __future__ import annotations import dataclasses from asyncio import CancelledError, Queue, QueueEmpty, Task, current_task, get_event_loop from functools import lru_cache from inspect import isawaitable from math import ceil, floor from typing import Any, Awaitable, Callable async def drain_queue[T](queue: Queu...
JoshKarpel/counterweight
src/counterweight/_utils.py
.py
5a992dec21c53f6e
7.64
18
from __future__ import annotations import sys from asyncio import Queue, get_running_loop, run from textwrap import dedent from threading import Event, Thread from typer import Option, Typer from counterweight._context_vars import current_event_queue from counterweight.constants import PACKAGE_NAME, __version__ from...
JoshKarpel/counterweight
src/counterweight/cli.py
.py
2e7cfb8f1fda5b90
7.64
18
from __future__ import annotations from dataclasses import dataclass, replace from functools import wraps from typing import Callable, ParamSpec from counterweight.elements import AnyElement P = ParamSpec("P") def component(func: Callable[P, AnyElement]) -> Callable[P, Component]: """ A decorator that mark...
JoshKarpel/counterweight
src/counterweight/components.py
.py
4884c5f0ae5eebdf
7.64
18
from __future__ import annotations from dataclasses import dataclass from typing import overload import waxy from structlog import get_logger from counterweight._context_vars import current_hook_state, current_use_mouse_listeners from counterweight._utils import forever from counterweight.geometry import Position fr...
JoshKarpel/counterweight
src/counterweight/hooks/hooks.py
.py
e14008fdd78b9e63
7.64
18
from __future__ import annotations import math from collections.abc import Iterable from dataclasses import dataclass from typing import TYPE_CHECKING, assert_never import waxy from counterweight.elements import AnyElement, CellPaint, Div, Text from counterweight.styles.styles import TextWrap if TYPE_CHECKING: ...
JoshKarpel/counterweight
src/counterweight/layout.py
.py
2139a9bee8771f47
7.64
18
from __future__ import annotations from typing import TYPE_CHECKING, TextIO from structlog import get_logger from counterweight.geometry import Position from counterweight.paint import Paint from counterweight.styles.styles import CellStyle if TYPE_CHECKING: pass # https://www.xfree86.org/current/ctlseqs.html #...
JoshKarpel/counterweight
src/counterweight/output.py
.py
799b02fe98ae101d
7.64
18
"""Nexxtmove integration.""" from __future__ import annotations from datetime import datetime import logging from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry...
geertmeersman/nexxtmove
custom_components/nexxtmove/__init__.py
.py
27fa9087b5df7666
7.62
16
"""Config flow to configure the Nexxtmove integration.""" from abc import ABC, abstractmethod import logging from typing import Any from homeassistant.config_entries import ConfigEntry, ConfigFlow, OptionsFlow from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import callback from ho...
geertmeersman/nexxtmove
custom_components/nexxtmove/config_flow.py
.py
fc4e9c580cf4cc3a
7.62
16
"""Diagnostics support for Nexxtmove.""" from __future__ import annotations from typing import Any from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from .const import DOMAIN # ------------------------ # Helpers # ------------------------ def _redact(data: dict[str,...
geertmeersman/nexxtmove
custom_components/nexxtmove/diagnostics.py
.py
d5f328453cd3a6f0
7.62
16
"""Base Nexxtmove entity.""" from __future__ import annotations import logging from homeassistant.helpers.device_registry import DeviceEntryType from homeassistant.helpers.entity import DeviceInfo, EntityDescription from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import NexxtmoveDataUp...
geertmeersman/nexxtmove
custom_components/nexxtmove/entity.py
.py
6f7cc277d530990e
7.62
16
"""Models used by Nexxtmove.""" from __future__ import annotations from dataclasses import dataclass, field from typing import TypedDict class NexxtmoveConfigEntryData(TypedDict): """Config entry for the Nexxtmove integration.""" username: str | None password: str | None @dataclass cl...
geertmeersman/nexxtmove
custom_components/nexxtmove/models.py
.py
e63ab2652021ee25
7.62
16
"""Nexxtmove sensor platform.""" from __future__ import annotations from collections.abc import Callable import copy from dataclasses import dataclass import logging from typing import Any from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorSt...
geertmeersman/nexxtmove
custom_components/nexxtmove/sensor.py
.py
c7b3f27009e43bcd
7.62
16
"""Nexxtmove switch platform.""" from __future__ import annotations from collections.abc import Callable import copy from dataclasses import dataclass import logging from typing import Any from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription from homeassistant.config_entries import Confi...
geertmeersman/nexxtmove
custom_components/nexxtmove/switch.py
.py
ce74a21479923173
7.62
16
"""Nexxtmove utils.""" from __future__ import annotations import re def str_to_float(input) -> float: """Transform float to string.""" return float(input.replace(",", ".")) def float_to_timestring(float_time, unit_type) -> str: """Transform float to timestring.""" float_time = str_to_float(float_t...
geertmeersman/nexxtmove
custom_components/nexxtmove/utils.py
.py
6f2ae275e8a8c463
7.62
16
"""MobileVikings/JimMobile integration.""" from __future__ import annotations import logging from pathlib import Path from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant, callback from homeassistant.helpers imp...
geertmeersman/mobile_vikings
custom_components/mobile_vikings/__init__.py
.py
edcfdcbab766bc89
7.57
13
"""Module containing the MobileVikingsClient class for interacting with the Mobile Vikings API.""" from datetime import datetime, timedelta, timezone import logging from homeassistant.helpers.httpx_client import get_async_client from .const import ( BASE_URL, BASE_URL_JIMMOBILE, CLIENT_ID, ...
geertmeersman/mobile_vikings
custom_components/mobile_vikings/client.py
.py
1e1adc3172224681
7.57
13
"""Config flow to configure the MobileVikings integration.""" from abc import ABC, abstractmethod import logging from typing import Any from homeassistant.config_entries import ConfigEntry, ConfigFlow, OptionsFlow from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import callback fro...
geertmeersman/mobile_vikings
custom_components/mobile_vikings/config_flow.py
.py
b123cd785ce0c9ed
7.57
13
"""Base MobileVikings entity.""" from __future__ import annotations from datetime import datetime import logging from homeassistant.core import callback from homeassistant.helpers.device_registry import DeviceEntryType from homeassistant.helpers.entity import DeviceInfo, EntityDescription from homeassistant.helpers....
geertmeersman/mobile_vikings
custom_components/mobile_vikings/entity.py
.py
a164b9115fb95c31
7.57
13
"""Models used by MobileVikings.""" from __future__ import annotations from dataclasses import dataclass, field from typing import TypedDict class MobileVikingsConfigEntryData(TypedDict): """Config entry for the MobileVikings integration.""" username: str | None password: str | None mo...
geertmeersman/mobile_vikings
custom_components/mobile_vikings/models.py
.py
d3105a1fa30c0eee
7.57
13
"""MobileVikings utils.""" from __future__ import annotations import re def str_to_float(input) -> float: """Transform float to string.""" return float(input.replace(",", ".")) def to_title_case_with_spaces(input_string: str) -> str: """Convert a string to title case (each word starts with a capital l...
geertmeersman/mobile_vikings
custom_components/mobile_vikings/utils.py
.py
062e3929d2df365e
7.57
13
# Copyright (C) 2023 - 2026 ANSYS, Inc. and/or its affiliates. # SPDX-FileCopyrightText: 2023 ANSYS, Inc. All rights reserved # SPDX-License-Identifier: MIT # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal ...
ansys/pyturbogrid
src/ansys/turbogrid/core/launcher/launcher.py
.py
7b01b8f9632db096
7.57
13
# Copyright (C) 2023 - 2026 ANSYS, Inc. and/or its affiliates. # SPDX-FileCopyrightText: 2023 ANSYS, Inc. All rights reserved # SPDX-License-Identifier: MIT # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal ...
ansys/pyturbogrid
src/ansys/turbogrid/core/mesh_statistics/mesh_statistics.py
.py
659cb6f22baa1d29
7.57
13
# Copyright (C) 2023 - 2026 ANSYS, Inc. and/or its affiliates. # SPDX-FileCopyrightText: 2023 ANSYS, Inc. All rights reserved # SPDX-License-Identifier: MIT # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal ...
ansys/pyturbogrid
src/ansys/turbogrid/core/ndf_parser/ndf_parser.py
.py
b330d3d8fff03e96
7.57
13
# Copyright (C) 2023 - 2026 ANSYS, Inc. and/or its affiliates. # SPDX-FileCopyrightText: 2024 ANSYS, Inc. All rights reserved # SPDX-License-Identifier: MIT # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal ...
ansys/pyturbogrid
tests/conftest.py
.py
8a5677ef459344cf
7.07
13
# Copyright (C) 2023 - 2026 ANSYS, Inc. and/or its affiliates. # SPDX-FileCopyrightText: 2023 ANSYS, Inc. All rights reserved # SPDX-License-Identifier: MIT # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal ...
ansys/pyturbogrid
tests/test_launcher.py
.py
3d1457ffa9ae7665
7.07
13
from ibis.backends.tests.test_client import * # noqa: F401,F403 def test_list_catalogs(con): """Override: add gizmosql entry (same as duckdb).""" result = set(con.list_catalogs()) assert {"memory"} <= result def test_list_database_contents(con): """Override: add gizmosql entry (same as duckdb).""" ...
gizmodata/ibis-gizmosql
tests/test_client.py
.py
cb07e4e68adfb74b
7.63
17
"""Tests for local file reading via batched ADBC bulk ingest. These tests verify that read_csv, read_parquet, and read_json read files locally using DuckDB and upload them to GizmoSQL via ADBC bulk ingest, rather than sending file paths to the server. """ from __future__ import annotations import json import tempfil...
gizmodata/ibis-gizmosql
tests/test_local_ingest.py
.py
97b70647638fe689
8.13
17
""" Abstract Hardware API: Balance This is an example of a hardware Python API. docstring [optional]: if given, docstring will be attached to the prompt when using LLM _helper_function: function names start with "_" will not be displayed types and default: Types (str, float, bool) and default values are re...
ivoryos-ai/IvoryOS
community/examples/abstract_sdl_example/abstract_balance.py
.py
1010557ac9d5fb09
7.66
20
""" Abstract Hardware API: Pump This is an example of a hardware Python API. docstring [optional]: if given, docstring will be attached to the prompt when using LLM _helper_function: function names start with "_" will not be displayed types and default: Types (str, float, bool) and default values are recom...
ivoryos-ai/IvoryOS
community/examples/abstract_sdl_example/abstract_pump.py
.py
766ebf91ad99f195
7.66
20
""" Abstract Self-driving Lab (SDL) API This is an example of an SDL API - a collection of multiple hardware docstring [optional]: if given, docstring will be attached to the prompt when using LLM _helper_function: function names start with "_" will not be displayed types and default: Types (str, float, bo...
ivoryos-ai/IvoryOS
community/examples/abstract_sdl_example/abstract_sdl.py
.py
4cdb59d1eeec1936
7.66
20
import logging import time from enum import Enum from typing import Optional, Union, List, Literal class Color(Enum): RED = "Red" GREEN = "Green" BLUE = "Blue" class InputTypeShowcase: """ A showcase of all the input types supported by IvoryOS's dynamic forms. This class can be used as a 'deck...
ivoryos-ai/IvoryOS
community/examples/abstract_sdl_example/showcase_input_types.py
.py
29c96940f8322f09
7.66
20
import os import uuid from dotenv import load_dotenv load_dotenv() import bcrypt from flask import Flask, session, g, redirect, url_for from flask_login import AnonymousUserMixin from sqlalchemy import inspect, text from ivoryos.utils.logger import start_logger from ivoryos.models import db, User from ivoryos.socket...
ivoryos-ai/IvoryOS
ivoryos/app.py
.py
dcde5e94323d93b3
7.66
20
from datetime import datetime from sqlalchemy_utils import JSONType from ivoryos.models.base import db class WorkflowRun(db.Model): """Represents the entire experiment""" __tablename__ = 'workflow_runs' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128), nullable=False) ...
ivoryos-ai/IvoryOS
ivoryos/models/workflow.py
.py
43654230da1577ec
7.66
20
from pandas import DataFrame from ivoryos.optimizer.base_optimizer import OptimizerBase # hardcoded blacklist for Ax objective names from SymPy AX_OBJ_BLACKLIST = ["test", "factor", "range", "product", "prod", "sum", "type", "yield"] class AxOptimizer(OptimizerBase): def __init__(self, experiment_name, parameter...
ivoryos-ai/IvoryOS
ivoryos/optimizer/ax_optimizer.py
.py
0492d440810c1d09
7.66
20
### ivoryos/optimizers/base.py from abc import ABC, abstractmethod class OptimizerBase(ABC): def __init__(self, experiment_name:str, parameter_space: list, objective_config: dict, optimizer_config: dict, parameter_constraints:list=None, datapath:str=None, additional_params:dict=None): "...
ivoryos-ai/IvoryOS
ivoryos/optimizer/base_optimizer.py
.py
e28c1d43eecdfb2c
7.66
20
from pandas import DataFrame from ivoryos.optimizer.base_optimizer import OptimizerBase class BaybeOptimizer(OptimizerBase): def __init__(self, experiment_name, parameter_space, objective_config, optimizer_config, parameter_constraints:list=None, datapath=None, additional_params:dict=None): ...
ivoryos-ai/IvoryOS
ivoryos/optimizer/baybe_optimizer.py
.py
da1ee26476fc6db6
7.66
20
import json def sanitize_for_json(obj): """ Recursively converts sets and other non-JSON-serializable objects to JSON-friendly types. """ from datetime import datetime, date from enum import Enum if isinstance(obj, dict): return {k: sanitize_for_json(v) for k, v in obj.items()} ...
ivoryos-ai/IvoryOS
ivoryos/parsers/serialize.py
.py
02ac17ee2330be0a
7.66
20
import ast import importlib from collections import Counter from ivoryos.script.editor import ScriptEditor def _convert_by_str(args, arg_types): """ Converts a value to type through eval(f'{type}("{args}")') """ if not isinstance(arg_types, list): arg_types = [arg_types] can_be_str = False...
ivoryos-ai/IvoryOS
ivoryos/parsers/type_conversions.py
.py
8dec361fcf44cdcb
7.66
20
from flask import Blueprint, redirect, url_for, flash, request, render_template, session from flask_login import login_required, login_user, logout_user, LoginManager, current_user import bcrypt from ivoryos.models import User, db from ivoryos.script import Script from ivoryos.services.draft_service import post_script...
ivoryos-ai/IvoryOS
ivoryos/routes/auth/auth.py
.py
5123d27113e4cd84
7.66
20
import copy from flask import Blueprint, flash, request, render_template, session, current_app, jsonify from flask_login import login_required from ivoryos.routes.control.control_file import control_file from ivoryos.routes.control.control_new_device import control_temp from ivoryos.routes.control.utils import post_s...
ivoryos-ai/IvoryOS
ivoryos/routes/control/control.py
.py
542f85de7a63fd8b
7.66
20
import inspect import importlib import os from flask import Blueprint, request, current_app, flash, redirect, url_for, session, render_template from flask_login import login_required from ivoryos.services.connection_history import save_to_history from ivoryos.services.draft_service import get_script_file from ivoryos....
ivoryos-ai/IvoryOS
ivoryos/routes/control/control_new_device.py
.py
46f7d4e0044fe9d7
7.66
20
import importlib.util from flask import session from ivoryos.runtime.state import GlobalState global_state = GlobalState() def import_module_by_filepath(filepath: str, name: str): """ Import a deck/API module by file path for manual controller connection. """ spec = importlib.util.spec_from_file_l...
ivoryos-ai/IvoryOS
ivoryos/routes/control/utils.py
.py
083458339d69cbe8
7.66
20
import json import os from flask import Blueprint, send_file, request, flash, redirect, url_for, current_app from ivoryos.services.draft_service import get_script_file, post_script_file from ivoryos.script import ScriptEditor files = Blueprint('design_files', __name__) @files.route('/files/script-json', methods=['...
ivoryos-ai/IvoryOS
ivoryos/routes/design/design_file.py
.py
e09d5ddc64e41b5f
7.66
20
#!/usr/bin/env python # RefSeq Gene Summary Extraction # This script obtains the summary description for genes stored in NCBI Gene. The script: # 1. Uses the NCBI eUtils REST API to obtain RefSeq summaries for genes, based on Entrez ID: # a. Calls eSearch to obtain subsets of Entrez UIDs, with a subset size (chunk...
x-atlas-consortia/ubkg-etl
generation_framework/refseq/refseq.py
.py
33d0e0cd8b3cbd90
7.45
7
#!/usr/bin/env python # coding: utf-8 # UBKG tools for extracting, expanding, and processing source files from online sources, such as GZIP archives. # Displays progress indicators of activities. import requests import os import gzip from tqdm import tqdm import pandas as pd import numpy as np import gdown import fil...
x-atlas-consortia/ubkg-etl
generation_framework/ubkg_utilities/ubkg_extract.py
.py
f70c07f5dc78ce93
7.45
7
from dataclasses import dataclass from Options import (Choice, OptionList, NamedRange, StartInventoryPool, PerGameCommonOptions, DeathLinkMixin, OptionGroup) class Character(Choice): """Leon: Expected, can video game. Claire: Optimal choice, but more lickers.""" display_name = "Character t...
FuzzyGamesOn/RE2R_AP_World
residentevil2remake/Options.py
.py
80eb31ccda81d3f1
7.62
16
"""Handle Auth related endpoints for Music Assistant.""" from __future__ import annotations from typing import TYPE_CHECKING, Any from music_assistant_models.auth import AuthToken, User, UserAuthProvider if TYPE_CHECKING: from .client import MusicAssistantClient class Auth: """Auth related endpoints/data ...
music-assistant/client
music_assistant_client/auth.py
.py
82909dcf5dbc9b2d
7.59
14
"""Connect to a remote Music Assistant Server using the Websocket API.""" from __future__ import annotations import logging import pprint import ssl from typing import TYPE_CHECKING, Any, cast from aiohttp import ClientSession, ClientWebSocketResponse, WSMsgType, client_exceptions from .exceptions import ( Cann...
music-assistant/client
music_assistant_client/connection.py
.py
fa79df2327273ea2
7.59
14
"""Handle Dashboard related endpoints for Music Assistant.""" from __future__ import annotations import inspect from collections.abc import Awaitable, Callable from typing import TYPE_CHECKING, cast from music_assistant_models.dashboard import DashboardDevice, DashboardSession from music_assistant_models.enums impor...
music-assistant/client
music_assistant_client/dashboard.py
.py
ad0a956bd6f632e2
7.59
14
"""Several generic/basic helpers and utilities complementing the Music Assistant Client.""" from __future__ import annotations import asyncio import base64 from _collections_abc import dict_keys, dict_values from types import MethodType from typing import TYPE_CHECKING, Any, NotRequired, TypedDict import orjson from...
music-assistant/client
music_assistant_client/helpers.py
.py
fb037ae75fb5de3f
7.59
14
"""Handle Metadata related endpoints for Music Assistant.""" from __future__ import annotations from typing import TYPE_CHECKING, cast from music_assistant_models.media_items import MediaItemPalette, media_from_dict if TYPE_CHECKING: from music_assistant_models.media_items import MediaItemImage, MediaItemType ...
music-assistant/client
music_assistant_client/metadata.py
.py
e439b0028cc2c842
7.59
14
"""Handle PlayerQueues related endpoints for Music Assistant.""" from __future__ import annotations import time from typing import TYPE_CHECKING from music_assistant_models.enums import EventType, QueueOption, RepeatMode from music_assistant_models.player_queue import PlayerQueue from music_assistant_models.queue_it...
music-assistant/client
music_assistant_client/player_queues.py
.py
9b238f14aed9c9e2
7.59
14
"""Handle player related endpoints for Music Assistant.""" from __future__ import annotations from contextlib import suppress from typing import TYPE_CHECKING from music_assistant_models.enums import EventType, MediaType from music_assistant_models.errors import ( MusicAssistantError, PlayerCommandFailed, ...
music-assistant/client
music_assistant_client/players.py
.py
7f6b8ce4ebf2db78
7.59
14
"""Choose the fastest available asyncio event loop for the current platform.""" from __future__ import annotations import sys from importlib import import_module, metadata from platform import python_implementation from types import ModuleType from typing import Any def backend_name() -> str: """Return the even...
aviadr1/winuvloop
src/winuvloop/__init__.py
.py
9bca73ef8f848f9b
7.5
9
import torch def linear_regression(x, y): """ Performs linear regression. Parameters ----------- x : torch.Tensor Design matrix of shape (m, n), where m is the number of samples and n is the number of features. y : torch.Tensor Target vector of shape (m, o), where m is the numb...
joakimwallmark/irtorch
irtorch/_internal_utils.py
.py
ca39a0376379ab80
7.6
15
import logging import torch logger = logging.getLogger("irtorch") class BoundedELU(torch.autograd.Function): # Set generate_vmap_rule to True to ask PyTorch to automatically generate a vmap rule. generate_vmap_rule = True @staticmethod def forward(input_tensor: torch.Tensor, alpha=1.0): """ ...
joakimwallmark/irtorch
irtorch/activation_functions.py
.py
396684896e89fb4d
7.6
15
import logging import copy import math import torch from irtorch.models import BaseIRTModel from irtorch.estimation_algorithms import BaseIRTAlgorithm from irtorch.estimation_algorithms.encoders import StandardEncoder from irtorch._internal_utils import dynamic_print from irtorch.irt_dataset import PytorchIRTDataset l...
joakimwallmark/irtorch
irtorch/estimation_algorithms/ae.py
.py
e8401c68d0456b42
7.6
15
from __future__ import annotations from typing import TYPE_CHECKING from abc import ABC, abstractmethod import torch if TYPE_CHECKING: from irtorch.models import BaseIRTModel class BaseIRTAlgorithm(ABC): """ Abstract base class for IRT algorithms. All IRT algorithms should inherit from this class. """...
joakimwallmark/irtorch
irtorch/estimation_algorithms/base_irt_algorithm.py
.py
3f098f40e361c037
7.6
15
import logging from abc import ABC, abstractmethod from torch import nn logger = logging.getLogger("irtorch") class BaseEncoder(ABC, nn.Module): """ Abstract base class for IRT encoders. """ def __init__( self, input_dim: int, latent_variables: int, ): super().__in...
joakimwallmark/irtorch
irtorch/estimation_algorithms/encoders/base_encoder.py
.py
9ff3f8762fbcc658
7.6
15
import logging import copy import torch from torch.distributions import MultivariateNormal from irtorch.models import BaseIRTModel, MonotoneBSpline, NestedLogit from irtorch.utils import gauss_hermite from irtorch._internal_utils import dynamic_print from irtorch.irt_dataset import PytorchIRTDataset from irtorch.estima...
joakimwallmark/irtorch
irtorch/estimation_algorithms/mml.py
.py
9e226a4f945c5ac2
7.6
15
import logging import math import torch from torch.distributions import Normal from irtorch.models import BaseIRTModel from irtorch.estimation_algorithms.ae import AE from irtorch.estimation_algorithms.encoders import VariationalEncoder from irtorch.irt_dataset import PytorchIRTDataset logger = logging.getLogger("irto...
joakimwallmark/irtorch
irtorch/estimation_algorithms/vae.py
.py
af0e12b2047c93c4
7.6
15
import torch from irtorch._internal_utils import one_hot_encode_test_data from irtorch._internal_utils import impute_missing_internal class PytorchIRTDataset(torch.utils.data.Dataset): """ PyTorch dataset for IRT data. Parameters ---------- data : torch.Tensor A 2D tensor with the data. Ro...
joakimwallmark/irtorch
irtorch/irt_dataset.py
.py
c2b43e8b1ea5f07f
7.6
15
import logging import torch logger = logging.getLogger("irtorch") def interp(x_new, x, y): """ Linear interpolation function with simple linear extrapolation at edges Parameters ---------- x_new : torch.Tensor The x-coordinates at which to evaluate the interpolated values. x : torch.T...
joakimwallmark/irtorch
irtorch/latent_variable_functions.py
.py
8986eb2e978001e7
7.6
15
import os import logging from importlib import resources import urllib.request import shutil import tempfile import pickle import torch import pandas as pd logger = logging.getLogger("irtorch") def swedish_national_mathematics_2() -> torch.Tensor: """ Load the second Swedish National Mathematics dataset. ...
joakimwallmark/irtorch
irtorch/load_dataset.py
.py
6ea596fc3d4f5ce3
7.6
15
import pandas as pd import torch from torch import nn from irtorch.models.base_irt_model import BaseIRTModel class GradedResponse(BaseIRTModel): r""" Graded response IRT model :cite:p:`Samejima1968`. Parameters ---------- data: torch.Tensor, optional A 2D torch tensor with test data. Used ...
joakimwallmark/irtorch
irtorch/models/graded_response.py
.py
9edff6f9054a0d09
7.6
15
import torch from torch import nn import torch.nn.functional as F from irtorch.models.base_irt_model import BaseIRTModel class ModelMix(BaseIRTModel): r""" A mix of models tied together by a single set of latent variables. This allows for a mix of different IRT models to be used when items have different ...
joakimwallmark/irtorch
irtorch/models/model_mix.py
.py
46084427c55ad6ef
7.6
15
import torch from torch import nn from irtorch.models.base_irt_model import BaseIRTModel from irtorch.torch_modules import BSplineBasisFunction class MonotoneBSpline(BaseIRTModel): r""" Monotone B-Spline IRT model for polytomously scored items with ordered responses. Parameters ---------- data: to...
joakimwallmark/irtorch
irtorch/models/monotone_b_spline.py
.py
206ad3d1bdf2f573
7.6
15
import torch from irtorch.models import BaseIRTModel from irtorch.torch_modules import BSplineBasisFunction class NestedLogit(BaseIRTModel): r""" Nested logit IRT model for multiple choice items :cite:p:`Suh2010`. The original paper uses a 3PL model :class:`irtorch.models.ThreeParameterLogistic` nested with a ...
joakimwallmark/irtorch
irtorch/models/nested_logit.py
.py
1d83fa04f76c5186
7.6
15
import pandas as pd import torch from torch import nn from irtorch.models.base_irt_model import BaseIRTModel class NominalResponse(BaseIRTModel): r""" Nominal response IRT model :cite:p:`Bock1972`. Parameters ---------- data: torch.Tensor, optional A 2D torch tensor with test data. Used to...
joakimwallmark/irtorch
irtorch/models/nominal_response.py
.py
1fc95a36ccad7350
7.6
15
import pandas as pd import torch from torch import nn from irtorch.models.base_irt_model import BaseIRTModel class OneParameterLogistic(BaseIRTModel): r""" One parametric logistic (1PL) IRT model, also known as the Rasch model :cite:p:`Rasch1960`. This model is only available for unidimensional latent variable...
joakimwallmark/irtorch
irtorch/models/one_parameter_logistic.py
.py
497c9dc5f2019b64
7.6
15
import torch from irtorch.models import BaseIRTModel from irtorch.torch_modules import BSplineBasisFunction class SurprisalSpline(BaseIRTModel): r""" Surprisals (negative logarithm of probabilities) are modeled using monotone cubic B-splines, hence the name. Note that this model requires each latent variab...
joakimwallmark/irtorch
irtorch/models/surprisal_spline.py
.py
33f17e9823ab9770
7.6
15
import pandas as pd import torch from torch import nn from irtorch.models.base_irt_model import BaseIRTModel class ThreeParameterLogistic(BaseIRTModel): r""" Three parametric logistic (3PL) IRT model :cite:p:`Birnbaum1968`. *Note that parameter estimation for this model is currently very unstable.* Parame...
joakimwallmark/irtorch
irtorch/models/three_parameter_logistic.py
.py
4d9921a7ad4282e1
7.6
15
import logging import torch from torch.distributions.multivariate_normal import MultivariateNormal from irtorch.latent_variable_functions import ( quantile_transform, interp, ) logger = logging.getLogger("irtorch") class QuantileMVNormal: """ Quantile multivariate normal approximation of a multivariat...
joakimwallmark/irtorch
irtorch/quantile_mv_normal.py
.py
e819653080984213
7.6
15
import logging import numpy as np import torch from torch.utils.data import DataLoader, TensorDataset from torch.distributions import Distribution, Normal from irtorch.rescale import Scale from irtorch.torch_modules import NeuralSplineFlow from irtorch.torch_modules import RationalQuadraticSpline logger = logging.getL...
joakimwallmark/irtorch
irtorch/rescale/flow.py
.py
ddf91545a2219e4f
7.6
15
import torch from irtorch.rescale import Scale class RankCDF(Scale): """ Rank-based inverse CDF transformation of IRT theta scales. For each latent variable, finds the rank of each theta score in the population. For new data, finds the closest matching population ranks and uses the inverse CDF to ...
joakimwallmark/irtorch
irtorch/rescale/rank_cdf.py
.py
03e50d85cd8fc579
7.6
15
import logging import torch from irtorch.rescale import Scale logger = logging.getLogger("irtorch") class Reverse(Scale): """ Reverses the chosen theta scales using. Parameters ---------- reversed_latent_variables : list[bool] A list of booleans indicating which latent variables to re...
joakimwallmark/irtorch
irtorch/rescale/reverse.py
.py
615c0ca1a0a2947c
7.6
15
from __future__ import annotations from typing import TYPE_CHECKING import logging from factor_analyzer import Rotator import torch from irtorch.rescale import Scale if TYPE_CHECKING: from irtorch.models.base_irt_model import BaseIRTModel logger = logging.getLogger("irtorch") class Rotate(Scale): """ Rot...
joakimwallmark/irtorch
irtorch/rescale/rotate.py
.py
07fb1110caddb302
7.6
15
import logging import torch import torch.distributions as dist logger = logging.getLogger("irtorch") class GaussianMixtureModel(torch.nn.Module): """ Gaussian mixture model for approximating a multivariate joint density function. Parameters ---------- n_components : int The number of mixt...
joakimwallmark/irtorch
irtorch/torch_modules/gaussian_mixture_model.py
.py
5b9e1cb01a22553d
7.6
15
import torch from torch import nn import torch.nn.functional as F class MonotonePolynomialModule(nn.Module): """ A polynomial with monotonicity constraints. Parameters ---------- degree: int Degree of the polynomial. Needs to be an uneven number. in_features: int Number of inpu...
joakimwallmark/irtorch
irtorch/torch_modules/monotone_polynomial.py
.py
b93253cd36339f1f
7.6
15
import torch from torch import nn class NegationLayer(nn.Module): def __init__(self, item_theta_relationships: torch.Tensor, inputs_per_item: int, zero_outputs: torch.Tensor): """ Parameters ---------- item_theta_relationships : torch.Tensor An integer tensor of shape (i...
joakimwallmark/irtorch
irtorch/torch_modules/negation_layer.py
.py
0a6288d0cea9c05c
7.6
15
"""Main entry point for datoso.""" import logging import os import sys from argparse import ArgumentParser, Namespace from datoso import __version__ from datoso.commands.argparser import ( add_all_seed_parser, add_config_parser, add_dat_parser, add_deduper_parser, add_doctor_parser, add_import_...
laromicas/datoso
src/datoso/__main__.py
.py
899a1a8616c0285b
7.52
10
"""Process actions.""" from abc import ABC, abstractmethod from collections.abc import Iterator from pathlib import Path from datoso.configuration import config, logger from datoso.database.models.dat import Dat from datoso.helpers import compare_dates from datoso.helpers.file_utils import copy_path, get_ext, remove_p...
laromicas/datoso
src/datoso/actions/processor.py
.py
03efba21626e3a2d
7.52
10
"""Commands for datoso after parsing arguments.""" import configparser import json import logging import os import re import sys from argparse import Namespace from pathlib import Path from venv import logger from datoso import __app_name__ from datoso.commands.doctor import check_module, check_seed from datoso.comman...
laromicas/datoso
src/datoso/commands/commands.py
.py
1cd049fcf887d01f
7.52
10
"""Check if all dependencies are installed.""" from pydoc import locate from shutil import which from packaging.version import parse from datoso import __app_name__ from datoso.helpers import Bcolors from datoso.helpers.plugins import installed_seeds def check_seed(seed: str) -> bool: """Check if seed is instal...
laromicas/datoso
src/datoso/commands/doctor.py
.py
fb7f9583442934c9
7.52
10
"""Helper functions for the seed command.""" import re import sys from argparse import Namespace from collections.abc import Callable from datoso.commands.seed import Seed from datoso.configuration import config from datoso.configuration.configuration import get_seed_name from datoso.helpers import Bcolors from datoso...
laromicas/datoso
src/datoso/commands/helpers/seed.py
.py
5b275e144e8109a4
7.52
10
"""Fetch and Process Commands for Seeds.""" # ruff: noqa: ERA001 import re from argparse import ArgumentParser from collections.abc import Iterator from pathlib import Path from datoso import __app_name__ from datoso.actions.processor import Processor from datoso.configuration import config from datoso.helpers import ...
laromicas/datoso
src/datoso/commands/seed.py
.py
9e6dd087a2d948ee
7.52
10
"""Configuration module.""" import configparser import os from pathlib import Path from datoso import ROOT_FOLDER, __app_name__ HOME = Path.home() XDG_CONFIG_HOME = Path(os.environ.get('XDG_CONFIG_HOME', '~/.config')).expanduser() (XDG_CONFIG_HOME / 'datoso').mkdir(parents=True, exist_ok=True) def get_seed_name(see...
laromicas/datoso
src/datoso/configuration/configuration.py
.py
f19b2eb7cff0b88f
7.52
10
"""Helper class to manage the folders of the project.""" from pathlib import Path from datoso.configuration import config from datoso.helpers.file_utils import parse_path, remove_path class Folders: """Folders class.""" base: Path = None download: Path = None dats: Path = None backup: Path = Non...
laromicas/datoso
src/datoso/configuration/folder_helper.py
.py
a06f1819d47fdc5b
7.52
10
"""Logging configuration for datoso.""" import logging from datoso.helpers import Bcolors from datoso.helpers.file_utils import parse_path from .configuration import config log_level = config['LOG'].get('LogLevel', logging.DEBUG) formatter = logging.Formatter('[%(asctime)s - %(levelname)s] - %(message)s', '%Y-%m-%d ...
laromicas/datoso
src/datoso/configuration/logger.py
.py
983348ac3f321fd5
7.52
10
"""Database module.""" import os from pathlib import Path, PosixPath from threading import Lock from typing import Any from tinydb import JSONStorage, TinyDB from tinydb.middlewares import CachingMiddleware from datoso.configuration import config from datoso.helpers.file_utils import copy_path, parse_path XDG_DATA_H...
laromicas/datoso
src/datoso/database/__init__.py
.py
d03aabab129cd476
7.52
10
"""Database models for the datfile.""" from dataclasses import dataclass from pathlib import PosixPath from typing import Any from dataclasses_json import dataclass_json from tinydb import Query, TinyDB from tinydb.queries import QueryInstance from tinydb.table import Document, Table from datoso.database import Datab...
laromicas/datoso
src/datoso/database/models/dat.py
.py
20efc28b1afb15e5
7.52
10
"""Seed the database with Systems.""" import json from pathlib import Path import requests from datoso import ROOT_FOLDER from datoso.configuration import config from datoso.database.models import System fields = [ 'company', 'system', 'override', 'extra_configs', 'system_type', ] def get_syste...
laromicas/datoso
src/datoso/database/seeds/dat_rules.py
.py
4893974a26834bb3
7.52
10
"""Seed the database with mia.""" import json from pathlib import Path import requests from datoso import ROOT_FOLDER from datoso.configuration import config fields = [ 'system', 'game', 'size', 'crc32', 'md5', 'sha1', ] def get_mia() -> dict: """Get MIA from the Google Sheets.""" i...
laromicas/datoso
src/datoso/database/seeds/mia.py
.py
fe9f01b483cdafb7
7.52
10
"""Helpers.""" import re from numbers import Number from pathlib import Path from dateutil import parser class BcolorsMeta(type): """Metaclass for Bcolors.""" @classmethod def __getattr__(cls, name: str) -> str: """Get attribute.""" if name.upper() in Bcolors.color_list(): de...
laromicas/datoso
src/datoso/helpers/__init__.py
.py
0ac48ee21f3ff7f3
7.52
10
"""Command executor. This module provides a wrapper for subprocess.Popen to execute commands. """ import logging from subprocess import PIPE, CalledProcessError, Popen class Command: """Subprocess wrapper.""" def __init__(self, command: str) -> None: """Initialize the command.""" self.comman...
laromicas/datoso
src/datoso/helpers/executor.py
.py
239003882284030a
7.52
10
"""File utils.""" import os import shutil from contextlib import suppress from pathlib import Path def copy_path(origin: str | Path, destination: str | Path) -> None: """Copy file to destination.""" Path(destination).parent.mkdir(parents=True, exist_ok=True) try: if Path(origin).is_dir(): ...
laromicas/datoso
src/datoso/helpers/file_utils.py
.py
15ae72c2fe75e1c7
7.52
10
"""List all installed seeds.""" from enum import Enum from pydoc import locate from types import ModuleType from datoso import __app_name__ class PluginType(Enum): """Plugin type Enum.""" SEED = 'seed' PLUGIN = 'plugin' def get(plugin: str, module: str, plugin_type: str) -> ModuleType: """Get a plu...
laromicas/datoso
src/datoso/helpers/plugins.py
.py
2ea14d5aa98b293f
7.52
10