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 |
|---|---|---|---|---|---|---|
"""Scheduler state and statistics model."""
from datetime import datetime
from sqlalchemy import DateTime, Integer
from sqlalchemy.orm import Mapped, mapped_column
from core.time import utcnow
from models.base import Base, TimestampMixin
class SchedulerState(Base, TimestampMixin):
"""
Scheduler state, timi... | kernelcoffee/SteamSelfGifter | backend/src/models/scheduler_state.py | .py | 8248af4720291b18 | 7.56 | 12 |
"""Application settings model for SteamSelfGifter."""
from datetime import datetime
from sqlalchemy import Boolean, DateTime, Integer, String
from sqlalchemy.orm import Mapped, mapped_column
from models.base import Base, TimestampMixin
class Settings(Base, TimestampMixin):
"""
Application settings stored i... | kernelcoffee/SteamSelfGifter | backend/src/models/settings.py | .py | e496a8e4fa51a435 | 7.56 | 12 |
"""
Profile PCG implementations: numexpr vs optimized numba.
Usage:
python scripts/profile_pcg.py [--shape 8,8000,8000] [--maxit 50] [--warmup 5]
"""
import argparse
import gc
import tracemalloc
from time import time
import numpy as np
def make_toy_aop(shape, eta=0.1):
"""
Toy Hessian-like operator: el... | ratt-ru/pfb-imaging | scripts/profile_pcg.py | .py | 466badeff588a09e | 7.56 | 12 |
"""
Profile power_method implementations: numpy vs optimized numba.
Usage:
python scripts/profile_power_method.py [--shape 8,8000,8000] [--maxit 50] [--warmup 3]
"""
import argparse
import gc
import tracemalloc
from time import time
import numpy as np
def make_toy_aop(shape, eta=0.1):
"""
Toy Hessian-l... | ratt-ru/pfb-imaging | scripts/profile_power_method.py | .py | efb9e352f459d68c | 7.56 | 12 |
"""
Profile primal_dual implementations:
- primal_dual_optimised (numexpr + numba dual update)
- primal_dual_numba (all-numba)
Usage:
python scripts/profile_primal_dual.py [--shape 8,8000,8000] [--maxit 50] [--warmup 3]
The toy operators simulate a simple diagonal Hessian with wavelet-like
dual domain. psi/ps... | ratt-ru/pfb-imaging | scripts/profile_primal_dual.py | .py | 2b69a6fd712b66f5 | 7.56 | 12 |
import ctypes
import importlib
import logging
import os
import warnings
from importlib.metadata import version
from pfb_imaging.utils import logging as pfb_logging
__version__ = "0.0.11"
pfb_version = version("pfb-imaging")
# This need to happen before importing numba
os.environ["NUMBA_THREADING_LAYER"] = "tbb"
# Als... | ratt-ru/pfb-imaging | src/pfb_imaging/__init__.py | .py | 53e42687d14995c8 | 7.56 | 12 |
"""Lightweight CLI for pfb-imaging."""
import typer
import typer.core
from pfb_imaging.cli._deprecation import warn_deprecated
# Subcommands retired in pfb-imaging v0.1.0, mapped to their replacement. The
# callback below prints a loud banner when one of these is invoked; the commands
# themselves still run for now.... | ratt-ru/pfb-imaging | src/pfb_imaging/cli/__init__.py | .py | 2280cfb8391717a9 | 7.56 | 12 |
import concurrent.futures as cf
import time
from copy import deepcopy
from functools import partial
import numpy as np
import psutil
import xarray as xr
from daskms.fsspec_store import DaskMSStore
from ducc0.misc import resize_thread_pool, thread_pool_size
from numba import threading_layer
from pfb_imaging import pfb... | ratt-ru/pfb-imaging | src/pfb_imaging/core/sara.py | .py | af4c32eec4778fe9 | 7.56 | 12 |
"""
pfb-imaging
author - Landman Bester
email - lbester@ska.ac.za
date - 31/03/2020
MIT License
Copyright (c) 2020 Rhodes University Centre for Radio Astronomy Techniques & Technologies (RATT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentati... | ratt-ru/pfb-imaging | src/pfb_imaging/deconv/__init__.py | .py | 5c080dfb10be7840 | 7.56 | 12 |
"""PFBSolver: the concrete DeconvSolver composing (hess, forward, backward, prox)."""
import numpy as np
from pfb_imaging.deconv import Regulariser
from pfb_imaging.operators import LinearOperator, require_protocol
from pfb_imaging.opt import BackwardSolver, ForwardSolver
from pfb_imaging.opt.power_method import powe... | ratt-ru/pfb-imaging | src/pfb_imaging/deconv/pfb.py | .py | dbe7df54b0527478 | 7.56 | 12 |
"""Minor-cycle preset factories: assemble PFBSolver from CLI options.
Contributors add a deconvolution algorithm by writing a Regulariser and
registering a factory here ("kclean" will slot in as OneShot + ClarkProx).
"""
import numpy as np
from pfb_imaging.deconv.pfb import PFBSolver
from pfb_imaging.operators.band_... | ratt-ru/pfb-imaging | src/pfb_imaging/deconv/presets.py | .py | 0975170e1257d009 | 7.56 | 12 |
"""
pfb-imaging
author - Landman Bester
email - lbester@ska.ac.za
date - 31/03/2020
MIT License
Copyright (c) 2020 Rhodes University Centre for Radio Astronomy Techniques & Technologies (RATT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentati... | ratt-ru/pfb-imaging | src/pfb_imaging/operators/__init__.py | .py | 0d02ae039d159431 | 7.56 | 12 |
"""Per-band Ray worker co-locating all of a band's deconvolution state.
Bands couple only through the prox, so everything else a deconv run needs —
the PSF-convolution Hessian (with its in-actor CG), the wavelet dictionary,
and the gridding inputs for the exact residual — is per-band state. One
``_BandWorkerImpl`` act... | ratt-ru/pfb-imaging | src/pfb_imaging/operators/band_worker.py | .py | b028963387bef898 | 7.56 | 12 |
import numpy as np
class Mask(object):
def __init__(self, mask):
"""
Mask operator
"""
nx, ny = mask.shape
self.nx = nx
self.ny = ny
self.mask = mask
def dot(self, x):
"""
Components to image
"""
return x[~self.mask]
... | ratt-ru/pfb-imaging | src/pfb_imaging/operators/mask.py | .py | d77d59790ad261b3 | 7.06 | 12 |
from qgis.core import QgsProcessingProvider
from .rvt_hillshade import RVTHillshade
from .rvt_multi_hillshade import RVTMultiHillshade
from .rvt_slope import RVTSlope
from .rvt_slrm import RVTSlrm
from .rvt_svf import RVTSvf
from .rvt_asvf import RVTASvf
from .rvt_opns import RVTOpns
from .rvt_sky_illum import RVTSim
... | EarthObservation/rvt-qgis | processing_provider/provider.py | .py | d783d4d1ad2a051f | 7.66 | 20 |
# coding=utf-8
"""Tests QGIS plugin init."""
__author__ = 'Tim Sutton <tim@linfiniti.com>'
__revision__ = '$Format:%H$'
__date__ = '17/10/2010'
__license__ = "GPL"
__copyright__ = 'Copyright 2012, Australia Indonesia Facility for '
__copyright__ += 'Disaster Reduction'
import os
import unittest
import logging
import ... | EarthObservation/rvt-qgis | test/test_init.py | .py | 0ca37b64cdbfadd9 | 8.16 | 20 |
# coding=utf-8
"""Dialog test.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'zig... | EarthObservation/rvt-qgis | test/test_qrvt_dialog.py | .py | f0766ba5f2485e40 | 8.16 | 20 |
# coding=utf-8
"""Resources test.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = '... | EarthObservation/rvt-qgis | test/test_resources.py | .py | fe3e6bda90a28d2b | 8.16 | 20 |
"""Kostal Piko custom component."""
from datetime import timedelta
import logging
from math import ceil
from kostal import InfoVersions, Piko, SettingsGeneral
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, Platform
from homeassistant.core ... | scheidtdav/homeassistant-kostal-piko | custom_components/kostal_piko/__init__.py | .py | 73245e845994f9db | 7.65 | 19 |
"""Config flow for Kostal Piko solar inverters."""
import logging
from typing import Any
import kostal
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_BASE, CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.d... | scheidtdav/homeassistant-kostal-piko | custom_components/kostal_piko/config_flow.py | .py | 720a487846989ab1 | 7.65 | 19 |
"""Kostal Piko sensors."""
import logging
import kostal
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity import DeviceInfo
fro... | scheidtdav/homeassistant-kostal-piko | custom_components/kostal_piko/sensor.py | .py | 7d7205c73a1dfb80 | 7.65 | 19 |
import docker
client = docker.from_env()
prompt_output = b'\n\x1b[38;2;66;113;174m/home/pure/.pure \x1b[38;2;150;152;150m\x1b[38;2;150;152;150m\n\x1b[38;2;150;152;150m\x1b[38;2;137;89;168m\xe2\x9d\xaf '
def test_bash_render():
client.images.build(path='./',
dockerfile='containers/bash.Do... | edouard-lopez/pure.py | tests/integration_test.py | .py | 617f3ea5b65c71c4 | 7 | 9 |
import dataclasses
import struct
from enum import IntEnum, IntFlag
from functools import partial
from typing import Callable, ClassVar, Dict, List, Tuple, Type, Union, get_type_hints
from binmap import types as b_types
class BaseDescriptor:
"""Base class for all descriptors
:param name: Variable name"""
... | HeMan/binmap | binmap/__init__.py | .py | 7df802b95d9d7244 | 7.62 | 16 |
"""微信小程序登录:code 换 openid,签发本地 token。
未配置 WX_APPID / WX_SECRET 时登录接口会明确报错,方便联调定位。
"""
from __future__ import annotations
import secrets
from typing import Optional
import httpx
from .config import settings
from .db import get_user_by_token, upsert_user
JSCode2Session_URL = "https://api.weixin.qq.com/sns/jscode2sess... | zhuchance/Aimusic | app/auth.py | .py | 430c74158c516536 | 7.52 | 10 |
"""配置加载:从环境变量 / .env 读取各大模型的 API Key 与默认参数。
只有配置了对应 API Key 的模型才会被注册进可用模型列表。
"""
from __future__ import annotations
from typing import Optional
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""应用全局配置。"""
model_config = SettingsConfigDict(
env_file=".e... | zhuchance/Aimusic | app/config.py | .py | e4893adf3db7bcf7 | 7.52 | 10 |
"""SQLite 存储:用户与云端历史记录。
无需额外依赖(标准库 sqlite3),数据库文件为项目根目录的 aimusic.db。
"""
from __future__ import annotations
import json
import sqlite3
from contextlib import closing
from pathlib import Path
from typing import Optional
from .schemas import HistoryItemIn, HistoryItemOut, NoteOut
# 数据库文件(与 output/ 同级的项目根目录)
DB_PATH =... | zhuchance/Aimusic | app/db.py | .py | a06dd52c625e5dc4 | 7.52 | 10 |
"""LLM provider 抽象基类。
所有主流大模型(OpenAI / Claude / DeepSeek / Gemini / Qwen / Kimi 等)
都实现统一接口 :meth:`LLMProvider.complete`,返回模型的文本输出。
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Optional
import httpx
# 统一的请求超时(秒)
DEFAULT_TIMEOUT = httpx.Timeout(120.0, connect=15.0)
c... | zhuchance/Aimusic | app/llm/base.py | .py | c8dad4c2810c3879 | 7.52 | 10 |
"""Anthropic Claude provider(Messages API)。"""
from __future__ import annotations
import httpx
from .base import LLMError, LLMProvider
API_URL = "https://api.anthropic.com/v1/messages"
API_VERSION = "2023-06-01"
class ClaudeProvider(LLMProvider):
"""调用 Anthropic Claude。"""
def __init__(self, api_key: str,... | zhuchance/Aimusic | app/llm/claude.py | .py | c8f1e2114a794b15 | 7.52 | 10 |
"""OpenAI 兼容接口 provider。
OpenAI、DeepSeek、通义千问、Moonshot Kimi 等都提供与 OpenAI 一致的
``/chat/completions`` 接口,因此用一个通用实现即可覆盖多家模型。
"""
from __future__ import annotations
import httpx
from .base import LLMError, LLMProvider
class OpenAICompatProvider(LLMProvider):
"""通用 OpenAI 兼容 provider。"""
def __init__(self, id: ... | zhuchance/Aimusic | app/llm/openai_compat.py | .py | f37b15489d79fd8e | 7.52 | 10 |
"""模型注册中心:根据 .env 中配置的 API Key 动态构建可用 provider 列表。
只注册真正配置了 Key 的模型;前端下拉框仅展示这些模型。
"""
from __future__ import annotations
from typing import Dict, List, Optional
from ..config import settings
from .base import LLMError, LLMProvider
from .claude import ClaudeProvider
from .gemini import GeminiProvider
from .openai_com... | zhuchance/Aimusic | app/llm/registry.py | .py | 9415b6b90e665690 | 7.52 | 10 |
"""FastAPI 应用入口:提供 REST API 与 Web 前端。
启动:uvicorn app.main:app --reload
访问:http://127.0.0.1:8000
"""
from __future__ import annotations
from pathlib import Path
from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFi... | zhuchance/Aimusic | app/main.py | .py | cd5dcaa413bf468b | 7.52 | 10 |
"""把 :class:`CompositionOut` 渲染为 MIDI 文件。
使用 midiutil 写入标准 MIDI,可直接下载或用任意播放器打开。
前端播放则直接用 Web Audio API 读取 notes JSON,无需依赖此文件。
"""
from __future__ import annotations
import io
from midiutil import MIDIFile
from ..schemas import CompositionOut
# 乐器音色(GM Program):0=原声大钢琴
ACOUSTIC_GRAND_PIANO = 0
def render_midi(com... | zhuchance/Aimusic | app/music/midi.py | .py | d1fb65e5d9825a82 | 7.52 | 10 |
"""解析并校验大模型返回的曲谱 JSON。
模型输出可能带有 Markdown 代码块标记、前后说明文字或非法字段,
这里做宽容提取 + 严格规范化,最终产出可直接渲染的 :class:`CompositionOut`。
"""
from __future__ import annotations
import json
import re
from typing import List, Optional
from ..schemas import CompositionOut, NoteOut, RawComposition, RawNote
# 音名 -> 半音偏移(用于把 "C4" / "D#5" 这类音名转成 M... | zhuchance/Aimusic | app/music/parser.py | .py | 4120ec7f5c2a712b | 7.52 | 10 |
"""Pydantic 数据模型:API 请求/响应与曲谱结构定义。
曲谱采用结构化中间格式:AI 输出一段 JSON(音符列表),
后端再将其渲染为 MIDI / 供前端用 Web Audio 播放。
"""
from __future__ import annotations
from typing import List, Optional
from pydantic import BaseModel, Field
# ========================= 请求 / 响应 =========================
class GenerateRequest(BaseModel):
""... | zhuchance/Aimusic | app/schemas.py | .py | 038bd60f44a82d72 | 7.52 | 10 |
"""生成流程编排:串起模型调用、曲谱解析与 MIDI 渲染。"""
from __future__ import annotations
import uuid
from pathlib import Path
from .config import settings
from .llm import get_provider
from .music import build_user_prompt, midi_filename, parse_composition, render_midi
from .music.prompt import SYSTEM_PROMPT
from .schemas import Composi... | zhuchance/Aimusic | app/services.py | .py | d0bdf61d74d3d8d5 | 7.52 | 10 |
import types
from collections.abc import Mapping, Sequence
from typing import get_args, get_origin
def is_instance_of_type(value: object, tp: type | types.UnionType) -> bool:
return _isinstance(value, tp)
def _isinstance(value: object, tp: type | types.UnionType) -> bool:
"""
Check if value is an instan... | suutari/drf-jwt-2fa | drf_jwt_2fa/_type_checking.py | .py | 224a247bc5930980 | 7.66 | 20 |
from typing import TYPE_CHECKING
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from .models import UserTwoFactorAuthData
if TYPE_CHECKING:
ModelAdmin = admin.ModelAdmin[UserTwoFactorAuthData]
else:
ModelAdmin = admin.ModelAdmin
@admin.register(UserTwoFactorAuthData... | suutari/drf-jwt-2fa | drf_jwt_2fa/admin.py | .py | 43739e69a9e6c4e8 | 7.66 | 20 |
"""
Enrollment token for TOTP setup after an untrusted 2FA method.
When a user completes the first factor (username + password) but their
preferred 2FA method is not in ``TRUSTED_2FA_METHODS`` (e.g. they have
not yet enrolled any second factor), the auth endpoint returns an
*enrollment token* instead of full auth toke... | suutari/drf-jwt-2fa | drf_jwt_2fa/enrollment_token.py | .py | 40ea141c92734f44 | 7.66 | 20 |
from django.conf import settings
from django.contrib.auth.base_user import AbstractBaseUser
from django.db import models
from django.utils.translation import gettext_lazy as _
from .settings import api_settings
from .totp import make_sure_is_valid_totp_secret
from .totp_encryption import decrypt_totp_secret, encrypt_t... | suutari/drf-jwt-2fa | drf_jwt_2fa/models.py | .py | 43709d83071ec26e | 7.66 | 20 |
"""
Serializer for the set-2fa-method endpoint.
"""
from django.utils.translation import gettext_lazy as _
from rest_framework import exceptions, serializers
from .models import TwoFactorAuthMethod, UserTwoFactorAuthData
from .settings import api_settings
class Set2faMethodSerializer(serializers.Serializer[dict[str... | suutari/drf-jwt-2fa | drf_jwt_2fa/serializers_2fa_method.py | .py | 33178cb183cf630e | 7.66 | 20 |
from unittest.mock import Mock, patch
from django.contrib.auth.models import User
from drf_jwt_2fa.models import TwoFactorAuthMethod, UserTwoFactorAuthData
from drf_jwt_2fa.token_manager import CodeTokenManager
from .utils import check_code_token
def get_user(username="testuser", password="a42", email="testuser@lo... | suutari/drf-jwt-2fa | drf_jwt_2fa/tests/factories.py | .py | fce3aa67e9e2c0ec | 8.16 | 20 |
import datetime
import math
import pickle
import time
from unittest.mock import Mock, patch
import pytest
from django.core.cache.backends.locmem import LocMemCache
from django.test.client import RequestFactory
from django.urls import reverse
from freezegun import freeze_time
from rest_framework import status
from rest... | suutari/drf-jwt-2fa | drf_jwt_2fa/tests/test_throttling.py | .py | 7f99ea828c652aa9 | 8.16 | 20 |
"""
Tests for drf_jwt_2fa.totp_encryption.
"""
from drf_jwt_2fa.totp import generate_totp_secret
from drf_jwt_2fa.totp_encryption import (
decrypt_totp_secret,
encrypt_totp_secret,
)
def test_encrypt_decrypt_roundtrip():
secret = generate_totp_secret()
ciphertext = encrypt_totp_secret(secret)
ass... | suutari/drf-jwt-2fa | drf_jwt_2fa/tests/test_totp_encryption.py | .py | 139a27c9a79824fe | 8.16 | 20 |
"""
TOTP (Time-based One-Time Password) utilities.
"""
import re
import pyotp
from django.contrib.auth.base_user import AbstractBaseUser
from .settings import api_settings
def make_sure_is_valid_totp_secret(secret: str, /) -> None:
"""
Raise ValueError if given value is not a valid TOTP secret.
"""
... | suutari/drf-jwt-2fa | drf_jwt_2fa/totp.py | .py | 4cf8b3b31e18ed5d | 7.66 | 20 |
"""
Fernet-based encryption helpers for TOTP secrets.
"""
import base64
from cryptography.fernet import Fernet, InvalidToken
from .settings import api_settings
def encrypt_totp_secret(secret: str) -> str:
"""
Encrypt a TOTP secret for storage.
Encrypt given secret using Fernet symmetric encryption wit... | suutari/drf-jwt-2fa | drf_jwt_2fa/totp_encryption.py | .py | fd3a155891ac1b41 | 7.66 | 20 |
"""
Serializers for TOTP enrollment (setup and confirm).
"""
from django.utils.translation import gettext_lazy as _
from rest_framework import exceptions, serializers
from .models import TwoFactorAuthMethod, UserTwoFactorAuthData
from .settings import api_settings
from .totp import (
generate_totp_secret,
get... | suutari/drf-jwt-2fa | drf_jwt_2fa/totp_serializers.py | .py | a1ea7a2d0de39ee2 | 7.66 | 20 |
import base64
import hashlib
import hmac
from django.contrib.auth.models import AbstractBaseUser
from rest_framework import exceptions
def check_user_validity(user: AbstractBaseUser) -> None:
"""
Check validity of given user.
"""
if not user.is_active:
raise exceptions.PermissionDenied()
de... | suutari/drf-jwt-2fa | drf_jwt_2fa/utils.py | .py | 14b1590fea4f39d7 | 7.66 | 20 |
#!/usr/bin/env python3
from collections import OrderedDict
from suds.sudsobject import asdict, Factory as SudsFactory
def suds2dict(d):
"""
Suds object serializer
Borrowed from https://stackoverflow.com/questions/2412486/serializing-a-suds-object-in-python/15678861#15678861
"""
if type(d) in [dict... | eddo888/STEP.py | STEP/Cleaner.py | .py | c3aa9251e77e1892 | 7.5 | 9 |
from datetime import datetime
from datetime import timedelta
from datetime import timezone as datetime_timezone
from zoneinfo import ZoneInfo
import pytest
import timezone_converter.comparison_view as comparison_view
from timezone_converter.comparison_view import ComparisonView
def _make_view(
timezones=('new_y... | ibLeDy/timezone-converter | tests/comparison_view_test.py | .py | d3e64b16e7a55d03 | 7.07 | 13 |
import string
from timezone_converter.list_view import ListView
def test_list_groups_filtered_by_letter(capsys):
code = ListView(['a']).print_columns()
out = capsys.readouterr().out
assert code == 0
assert 'amsterdam' in out
def test_list_includes_ambiguous_canonical_paths(capsys):
ListView(['a... | ibLeDy/timezone-converter | tests/list_view_test.py | .py | 00222e7aee34da82 | 7.07 | 13 |
from datetime import datetime
from datetime import timedelta
from datetime import timezone as datetime_timezone
from datetime import tzinfo
from difflib import get_close_matches
from typing import List
from typing import Optional
from zoneinfo import ZoneInfo
from rich.table import Table
from timezone_converter.helpe... | ibLeDy/timezone-converter | timezone_converter/comparison_view.py | .py | 00fdd85e3ba7a291 | 7.57 | 13 |
from collections import Counter
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
from zoneinfo import available_timezones
from rich.columns import Columns
from rich.console import Console
from rich.table import Table
_ALL_TIMEZONES = sorted(available_timezones())
_T... | ibLeDy/timezone-converter | timezone_converter/helper.py | .py | 0b33acedfef89239 | 7.57 | 13 |
from collections import defaultdict
from typing import DefaultDict
from typing import List
from rich.columns import Columns
from rich.panel import Panel
from timezone_converter.helper import Helper
class ListView(Helper):
"""Render available timezone names as Rich panels grouped by letter."""
def __init__(... | ibLeDy/timezone-converter | timezone_converter/list_view.py | .py | b900e14c277b22a0 | 7.57 | 13 |
from difflib import get_close_matches
from typing import List
from timezone_converter.helper import Helper
class SearchView(Helper):
"""Fuzzy-match a search term against the available timezone names."""
def __init__(self, search: str) -> None:
self.search = search.lower()
def _search_and_sort(s... | ibLeDy/timezone-converter | timezone_converter/search_view.py | .py | 1c17ffa00648d4ba | 7.57 | 13 |
# Copyright (c) 2018 Ilya Shchepetkov
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
import os
import unittest
from eventb_to_txt.context import Context
from eventb_to_txt.machine import Machine
class EventBTestCase(unittest.TestCase):
def __init__(self, *argum... | eventb-rossi/eventb-to-txt | tests/utils.py | .py | 679092b892876240 | 7.92 | 6 |
import astropy.units as u
import numpy as np
from astropy.coordinates import Angle
from astropy.time import TimeDelta
__all__ = ['Precession']
class Precession:
"""Represent sinusoidal precession terms.
Parameters
----------
params : `float`, `list`, `numpy.ndarray`
Parameters used to form t... | riogroup/SORA | sora/body/frame/meta.py | .py | 43bf9a5dbcc0f6b9 | 7.64 | 18 |
import astropy.units as u
import matplotlib.pyplot as plt
import numpy as np
import shapely.geometry as geometry
__all__ = ['Limb']
zero = geometry.Point(0, 0)
class Limb:
__doc__ = geometry.LineString.__doc__
def __init__(self, *args, **kwargs):
self._contour = geometry.LineString(*args, **kwargs)... | riogroup/SORA | sora/body/shape/limb.py | .py | f9d46b481ed50943 | 7.64 | 18 |
from abc import ABC, abstractmethod
class BaseShape(ABC):
"""Abstract base class for shape models."""
def __init__(self) -> None:
super(BaseShape, self).__init__()
def __repr__(self) -> str:
"""Return the unambiguous string representation of the shape."""
return '<{}>'.format(sel... | riogroup/SORA | sora/body/shape/meta.py | .py | 87373548745288d9 | 7.64 | 18 |
import astropy.units as u
import numpy as np
from astropy.coordinates import SkyCoord
from astropy.coordinates.matrix_utilities import rotation_matrix
__all__ = ['read_obj_file', 'rotated_matrix']
def read_obj_file(filename):
"""Read vertices and faces from a Wavefront OBJ file.
Parameters
----------
... | riogroup/SORA | sora/body/shape/utils.py | .py | 70c2011406f9fc1b | 7.64 | 18 |
import functools
import warnings
next_major_version = 'v1.0'
warnings.simplefilter('always', FutureWarning)
def deprecated_alias(**aliases):
"""Create a decorator that renames deprecated keyword arguments.
Parameters
----------
**aliases
Mapping from deprecated keyword names to their replac... | riogroup/SORA | sora/config/decorators.py | .py | a7a41bbffdb73ece | 7.64 | 18 |
def check_kwargs(input_kwargs, allowed_kwargs, raise_error=True):
"""Test whether input keyword names are allowed.
Parameters
----------
input_kwargs : `dict`, `list`
Dictionary or list with the input keyword names.
allowed_kwargs : `list`
List with the allowed keys.
raise_err... | riogroup/SORA | sora/config/input_tests.py | .py | 3d08ae992f032278 | 8.14 | 18 |
from collections import OrderedDict
__all__ = ['List']
class List(OrderedDict):
"""Base class for SORA ordered list containers.
This class inherits from `collections.OrderedDict`, which keeps the order
in which objects were added. Items can be accessed by name or by insertion
order.
"""
_al... | riogroup/SORA | sora/config/list.py | .py | c2ac1e57df6826ff | 7.64 | 18 |
import sys
def progressbar(it, prefix="", size=40, file=sys.stdout):
"""Yield items while displaying a text progress bar.
Parameters
----------
it : iterable
Iterable object with a defined length.
prefix : `str`, optional
Text printed before the progress bar. Default is an empty s... | riogroup/SORA | sora/config/visuals.py | .py | 813f96e402c695e6 | 7.64 | 18 |
import os
import numpy as np
from sora.config.decorators import deprecated_alias
__all__ = ['calc_fresnel', 'calc_magnitude_drop']
@deprecated_alias(lambida='bandpass') # remove this line for v1.0
def calc_fresnel(distance, bandpass):
"""Calculates the Fresnel scale.
Fresnel Scale = square root of half t... | riogroup/SORA | sora/lightcurve/utils.py | .py | db4559602ed6bc69 | 7.64 | 18 |
# remove this block for v1.0
class _PositionDict(dict):
"""Dictionary that allows switching occultation data points on or off.
It also prevents users from changing stored data directly.
"""
def __setitem__(self, key, value):
"""Sets protected keys or toggles existing occultation entries.
... | riogroup/SORA | sora/occultation/meta.py | .py | 483dbfe048eddae9 | 7.64 | 18 |
"""
Tests for aiocasambi
"""
import argparse
import asyncio
import logging
import logging.handlers
import sys
import os
from pprint import pprint, pformat
import yaml
import aiohttp
import async_timeout
sys.path.append(os.path.split(os.path.dirname(sys.argv[0]))[0])
try:
import aiocasambi
except ModuleNotFoundE... | hellqvio86/aiocasambi | src/aiocasambi/__test_network_login__.py | .py | 384675b2471b4be0 | 8.04 | 11 |
"""
Tests for aiocasambi
"""
import argparse
import asyncio
import logging
import logging.handlers
import sys
import random
import os
from pprint import pprint, pformat
import yaml
import aiohttp
import async_timeout
sys.path.append(os.path.split(os.path.dirname(sys.argv[0]))[0])
try:
import aiocasambi
except M... | hellqvio86/aiocasambi | src/aiocasambi/__test_user_login__.py | .py | a8a1a69853c1f2f3 | 8.04 | 11 |
"""
Tests for aiocasambi
"""
import argparse
import asyncio
import logging
import logging.handlers
import sys
import random
import os
from pprint import pprint, pformat
import yaml
import aiohttp
import async_timeout
sys.path.append(os.path.split(os.path.dirname(sys.argv[0]))[0])
try:
import aiocasambi
except M... | hellqvio86/aiocasambi | src/aiocasambi/__test_ws_connect.py | .py | ac8466625adfbf93 | 8.04 | 11 |
"""State representation of Casanbi Scene"""
import logging
from pprint import pformat
LOGGER = logging.getLogger(__name__)
SCENE_STATE_OFF = "off"
SCENE_STATE_ON = "on"
"""
'scenes':
{'1': {'color': '#FFFFFF',
'hidden': False,
'icon': 0,
'id': 1,
'name': 'Foo',
'position': 0,
... | hellqvio86/aiocasambi | src/aiocasambi/scenes.py | .py | c5c2baa73d77bec5 | 7.54 | 11 |
# !/usr/bin/env python3
"""
pdf2image is a light wrapper for the poppler-utils tools that can
convert PDFs into Pillow images.
Reference: https://github.com/Belval/pdf2image
Third-party Requirements:
* ``io``
* ``tempfile``
* ``re``
* ``os``
* ``subprocess``
* ``PIL``
* ``uuid``
* ``P... | NASA-Planetary-Science/AmesCAP | amescap/pdf2image.py | .py | 0a54db3d090f2c37 | 7.56 | 12 |
#!/usr/bin/env python3
"""
Shared test class methods and functions
"""
import os
import sys
import unittest
import shutil
import subprocess
import tempfile
import glob
import numpy as np
from netCDF4 import Dataset
class BaseTestCase(unittest.TestCase):
"""Base class for integration tests with common setup method... | NASA-Planetary-Science/AmesCAP | tests/base_test.py | .py | 0a673c65bab54079 | 8.06 | 12 |
#!/usr/bin/env python3
"""
Integration tests for MarsCalendar.py
These tests verify the functionality of MarsCalendar for converting between
Martian solar longitude (Ls) and sol values.
"""
import os
import sys
import unittest
import shutil
import tempfile
import argparse
import subprocess
import re
from base_test im... | NASA-Planetary-Science/AmesCAP | tests/test_marscalendar.py | .py | 5e4947646dd1bd4b | 8.06 | 12 |
#!/usr/bin/env python3
"""
Integration tests for MarsInterp.py
These tests verify the functionality of MarsInterp for interpolating netCDF files
to various pressure and altitude coordinates.
"""
import os
import sys
import unittest
import shutil
import platform
import subprocess
import tempfile
import glob
import re
... | NASA-Planetary-Science/AmesCAP | tests/test_marsinterp.py | .py | e782e9e0181b6280 | 8.06 | 12 |
#!/usr/bin/env python3
"""
Integration tests for MarsVars.py
These tests verify the functionality of MarsVars for manipulating variables in netCDF files.
"""
import os
import sys
import unittest
import shutil
import subprocess
import tempfile
import glob
import numpy as np
from netCDF4 import Dataset
from base_test i... | NASA-Planetary-Science/AmesCAP | tests/test_marsvars.py | .py | e276996a392e2613 | 7.06 | 12 |
"""
A simple example of using the Pinnacle ASIC in absolute mode.
"""
import math
import sys
import time
import board
from digitalio import DigitalInOut
from circuitpython_cirque_pinnacle import (
PinnacleTouchSPI,
PinnacleTouchI2C, # noqa: imported-but-unused
PINNACLE_ABSOLUTE,
AbsoluteReport,
)
IS_... | 2bndy5/CircuitPython_Cirque_Pinnacle | examples/cirque_pinnacle_absolute_mode.py | .py | f0780d2638817532 | 7.66 | 20 |
"""
A simple example of using the Pinnacle ASIC in anymeas mode.
"""
import sys
import time
import board
from digitalio import DigitalInOut
from circuitpython_cirque_pinnacle import (
PinnacleTouchSPI,
PinnacleTouchI2C,
PINNACLE_ANYMEAS,
)
IS_ON_LINUX = sys.platform.lower() == "linux"
print("Cirque Pinna... | 2bndy5/CircuitPython_Cirque_Pinnacle | examples/cirque_pinnacle_anymeas_mode.py | .py | 679f139cc3c417ca | 7.66 | 20 |
"""
A simple example of using the Pinnacle ASIC in relative mode.
"""
import sys
import time
import board
from digitalio import DigitalInOut
from circuitpython_cirque_pinnacle import (
PinnacleTouchSPI,
PinnacleTouchI2C,
RelativeReport,
PINNACLE_RELATIVE,
)
IS_ON_LINUX = sys.platform.lower() == "linux... | 2bndy5/CircuitPython_Cirque_Pinnacle | examples/cirque_pinnacle_relative_mode.py | .py | 8652a0a6688018f8 | 7.66 | 20 |
"""
This example uses CircuitPython's built-in `usb_hid` API
to emulate a mouse with the Cirque circle trackpad.
NOTE: This example won't work on Linux (eg. using Raspberry Pi GPIO pins).
"""
import sys
import time
import board
from digitalio import DigitalInOut
import usb_hid
from circuitpython_cirque_pinnacle impor... | 2bndy5/CircuitPython_Cirque_Pinnacle | examples/cirque_pinnacle_usb_mouse.py | .py | 3ea272bb25f75b0c | 7.66 | 20 |
"""Check Python code String Formatting Style (SFS).
This is a plugin for the tool flake8 tool for checking Python source code.
"""
import ast
from flake8 import utils as stdin_utils
__version__ = "1.0.1"
plugin_prefix = "SFS"
class StringFormatStyleChecker:
"""Checker of Python code for string formatting sty... | peterjc/flake8-sfs | flake8_sfs.py | .py | 7e4ded7162d46140 | 7.42 | 6 |
"""Example of f-string with custom format method."""
class Client:
"""Customer or client object."""
def __init__(self, id, polite, casual):
"""Initialise the class."""
self.polite = polite
self.casual = casual
def __format__(self, format_spec):
"""Support format method or... | peterjc/flake8-sfs | tests/SFS301/custom_format.py | .py | 00e9e508cc2a5244 | 7.92 | 6 |
"""
Bee flight model – the "b" in ``blpd``.
Based on the Lévy flight random walk model as implemented in
[Fuentes et al. (2016)](https://doi.org/10.1016/j.atmosenv.2016.07.002)
but with some enhancements.
"""
import math
import numpy as np
from scipy import stats
__all__ = (
"draw_step_length",
"flight",
)
... | zmoon/blpd | blpd/bees.py | .py | 43529bb6a91a5e94 | 7.45 | 7 |
"""
Chemistry and emissions calculations
on LPD (Lagrangian particle dispersion) model output.
>>> ds0 = blpd.Model().run().to_xr() # LPD output
>>> ds = blpd.chem.calc_relative_levels_fixed_oxidants(ds0)
"""
import numpy as np
import xarray as xr
from scipy import stats
from .utils import auto_bins_xy
from .utils ... | zmoon/blpd | blpd/chem.py | .py | 2c647b01c8d3e30e | 7.45 | 7 |
"""
Lagrangian stochastic particle dispersion.
Using [Numba](https://numba.pydata.org/), particles are integrated in parallel.
Although it is possible to use these functions directly,
the intention is for `blpd.model.Model` to be used.
"""
import numpy as np
from numba import njit
from numba import prange
@njit
def... | zmoon/blpd | blpd/lpd.py | .py | 49a209cc8ba452d4 | 7.45 | 7 |
"""
Miscellaneous utility functions,
mostly for internal use.
"""
import inspect
import sys
from collections import namedtuple
from functools import partial
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
if sys.version_info >= (3, 9):
from functools import cache
else:
from functo... | zmoon/blpd | blpd/utils.py | .py | de99029f142c867f | 7.45 | 7 |
from datetime import datetime
from typing import List, Dict, Any, Optional, Tuple, Union, Iterator
import deprecation
from orjson import loads
from urllib3.util.retry import Retry
from .exceptions import OnboardApiException
from .helpers import ClientBase
from .models import (
PointSelector,
PointDataUpdate,
... | onboard-data/client-py | onboard/client/client.py | .py | c80040e6f14a4002 | 7.5 | 9 |
import math
from dataclasses import field
from datetime import datetime, timezone
from typing import List, Optional, Union, Dict
from pydantic import field_validator, ConfigDict, BaseModel
class PointDataUpdate(object):
"""Model for bulk-updating a point's data value and timestamp"""
__slots__ = ["point_id"... | onboard-data/client-py | onboard/client/models.py | .py | 8ab1e3314e0d7b74 | 7.5 | 9 |
from typing import List, Dict, Any, Optional, Tuple
import deprecation
from urllib3.util.retry import Retry
from .helpers import ClientBase
from .util import json
class StagingClient(ClientBase):
"""Staging area API bindings"""
def __init__(
self,
api_url: str,
api_key: Optional[str... | onboard-data/client-py | onboard/client/staging.py | .py | 88ee8e7b429fbce4 | 7.5 | 9 |
from typing import List, Iterable, TypeVar, Callable
import requests
from .exceptions import OnboardApiException, OnboardTemporaryException
T = TypeVar("T")
def divide_chunks(input_list: List[T], n: int) -> Iterable[List[T]]:
# looping till length input_list
for i in range(0, len(input_list), n):
y... | onboard-data/client-py | onboard/client/util.py | .py | a15457da50b1facc | 7.5 | 9 |
### clue-thermal-camera v0.8
### Thermal camera display on CLUE or PyPortal
### This plots the output from two thermal infrared sensors (cameras)
### the AMG8833 8x8 and the MLX90640 32x24
### copy this file to CLUE board as code.py
### MIT License
### Copyright (c) 2020 Kevin J. Walters
### Permission is hereby g... | kevinjwalters/circuitpython-examples | clue/clue-thermal-camera.py | .py | 2f83357ceac14468 | 7.52 | 10 |
### MIT License
### Copyright (c) 2020 Kevin J. Walters
### Permission is hereby granted, free of charge, to any person obtaining a copy
### of this software and associated documentation files (the "Software"), to deal
### in the Software without restriction, including without limitation the rights
### to use, copy, ... | kevinjwalters/circuitpython-examples | clue/rps_audio.py | .py | b6e4bc26ba4954d2 | 7.52 | 10 |
### MIT License
### Copyright (c) 2020 Kevin J. Walters
### Permission is hereby granted, free of charge, to any person obtaining a copy
### of this software and associated documentation files (the "Software"), to deal
### in the Software without restriction, including without limitation the rights
### to use, copy, ... | kevinjwalters/circuitpython-examples | clue/rps_crypto.py | .py | 1ba9e55930bab068 | 7.52 | 10 |
import json
import re
import markdown2
import timeout_decorator
from .helper import reputation_to_score, calc_flag_weight
def make_index_config(type_name):
return {
'settings': {
'analysis': {
'analyzer': {
'index_analyzer': {
'toke... | ecency/hivesearcher-elastic | post/es_helpers.py | .py | 22240a89ebe3f179 | 7.48 | 8 |
import math
def reputation_to_score(rep):
"""
Converts the raw reputation value into the reputation score.
If the input is already a 2-digit score, it returns it directly.
"""
if isinstance(rep, str):
rep = int(rep)
# If rep is already in 2-digit format, return it as a float
if 10... | ecency/hivesearcher-elastic | post/helper.py | .py | e77e464954c8274e | 7.48 | 8 |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
class SandcastleException(Exception):
"""Something went wrong."""
class SandcastleTimeoutReached(SandcastleException):
"""Timeout was reached while sandboxing"""
class SandcastleExecutionError(SandcastleException):
"""There... | packit/sandcastle | sandcastle/exceptions.py | .py | 16fc2d24ca43b98e | 7.52 | 10 |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
"""
Kube objects generation.
"""
from pathlib import Path
from typing import List, Union, Optional
from sandcastle.utils import clean_string, get_timestamp_now
class PVC:
def __init__(
self,
path: Union[str, Path],
... | packit/sandcastle | sandcastle/kube.py | .py | 51e60ddebb5ab442 | 7.52 | 10 |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
import datetime
import logging
import os
import shlex
import subprocess
logger = logging.getLogger(__name__)
def run_command(cmd, cwd=None, output=False):
if not isinstance(cmd, list):
cmd = shlex.split(cmd)
cwd = cwd or... | packit/sandcastle | sandcastle/utils.py | .py | 7fedb3b826fa36db | 7.52 | 10 |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
import time
from subprocess import check_output
from typing import Optional, Any, Dict
import pytest
import urllib3
from kubernetes import client
from kubernetes.client import V1DeleteOptions
from kubernetes.client.rest import ApiException... | packit/sandcastle | tests/conftest.py | .py | a90d9eef428c99ea | 8.02 | 10 |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
import json
import os
from pathlib import Path
from shutil import rmtree, copy2
import pytest
from flexmock import flexmock
from sandcastle import (
Sandcastle,
VolumeSpec,
SandcastleTimeoutReached,
MappedDir,
)
from sandca... | packit/sandcastle | tests/e2e/test_ironman.py | .py | 7202f71f79bee4b2 | 7.02 | 10 |
"""
Module for handling and bundling various configuration options for TESTed.
"""
import logging
from pathlib import Path
from typing import IO, TYPE_CHECKING, Any, Optional
from attrs import define, evolve, field
from tested.parsing import fallback_field, get_converter
from tested.testsuite import ExecutionMode, S... | dodona-edu/universal-judge | tested/configs.py | .py | 82069ee17cd63efe | 8 | 9 |
"""
The data types.
The data type system is used in two ways:
1. As a describing system: the types are used to denote the datatype of actual data.
2. As a prescribing system: the types are used to denote the channel type of some
variable.
As mentioned in the manuscript, the context_testcase use is scenario 1.
Ad... | dodona-edu/universal-judge | tested/datatypes/__init__.py | .py | 556e8bb7ee69d01f | 8 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.