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 |
|---|---|---|---|---|---|---|
class attribute(object): # noqa: N801
"""``attribute`` decorator is intended to promote a
function call to object attribute. This means the
function is called once and replaced with
returned value.
>>> class A:
... def __init__(self):
... self.counter = 0
... @... | akornatskyy/wheezy.core | src/wheezy/core/descriptors.py | .py | c7dd8ff564b1c3c3 | 7 | 0 |
def make_feistel_number(f):
"""Generate pseudo random consistent reversal number
per Feistel cypher algorithm.
see http://en.wikipedia.org/wiki/Feistel_cipher
>>> feistel_number = make_feistel_number(sample_f)
>>> feistel_number(1)
573852158
>>> feistel_number(2)
1788827948
... | akornatskyy/wheezy.core | src/wheezy/core/feistel.py | .py | 364d979e7be64758 | 7 | 0 |
from http.client import HTTPConnection, HTTPSConnection
from http.cookies import SimpleCookie
from json import loads as json_loads
from urllib.parse import urlencode, urljoin, urlsplit
from wheezy.core.collections import attrdict, defaultdict
from wheezy.core.gzip import decompress
class HTTPClient(object):
"""H... | akornatskyy/wheezy.core | src/wheezy/core/httpclient.py | .py | 7149b488e3326a5c | 7 | 0 |
import gettext
import os
import os.path
from collections import defaultdict
null_translations = gettext.NullTranslations()
class TranslationsManager(object):
"""Manages several languages and translation domains."""
def __init__(self, directories=None, default_lang="en"):
"""
>... | akornatskyy/wheezy.core | src/wheezy/core/i18n.py | .py | 96aa41797e7ad33d | 7 | 0 |
import warnings
from inspect import isfunction, signature
def import_name(fullname):
"""Dynamically imports object by its full name.
>>> from datetime import timedelta
>>> import_name('datetime.timedelta') is timedelta
True
"""
namespace, name = fullname.rsplit(".", 1)
obj = __import__(na... | akornatskyy/wheezy.core | src/wheezy/core/introspection.py | .py | 51e830222f35da36 | 7.5 | 0 |
from decimal import Decimal
from json import (
JSONEncoder as SimpleJSONEncoder,
dumps as json_dumps,
loads as json_loads,
)
from wheezy.core.datetime import format_iso_datetime, format_iso_time
from wheezy.core.introspection import import_name
date = import_name("datetime.date")
datetime = imp... | akornatskyy/wheezy.core | src/wheezy/core/json.py | .py | 9feb70d57bbbe7dc | 7 | 0 |
def luhn_checksum(n):
"""Calculates checksum based on Luhn algorithm, also known as
the "modulus 10" algorithm.
see http://en.wikipedia.org/wiki/Luhn_algorithm
>>> luhn_checksum(1788827948)
0
>>> luhn_checksum(573852158)
1
>>> luhn_checksum(123456789)
7
"""
dig... | akornatskyy/wheezy.core | src/wheezy/core/luhn.py | .py | 1f69273b06f5315b | 7 | 0 |
from mimetypes import guess_type
from os.path import split as path_split
from smtplib import SMTP
from time import time
try:
from email.charset import CHARSETS, QP, SHORTEST
from email.encoders import encode_base64
from email.header import Header
from email.message import Message
from ema... | akornatskyy/wheezy.core | src/wheezy/core/mail.py | .py | 712e99f3fa62274f | 7 | 0 |
from queue import LifoQueue, Queue
class EagerPool(object):
"""Eager pool implementation.
Allocates all pool items during initialization.
"""
def __init__(self, create_factory, size):
self.size = size
items = Queue(size)
for _ in range(size):
items.pu... | akornatskyy/wheezy.core | src/wheezy/core/pooling.py | .py | 6dc45db6590653e7 | 7 | 0 |
from time import sleep, time
def make_retry(timeout, start, end=None, slope=1.0, step=0.0):
"""Return a function that accepts a single argument ``acquire`` which
should be a callable (without any arguments) that returns a boolean
value when attempt to acquire some resource or perform operation
... | akornatskyy/wheezy.core | src/wheezy/core/retry.py | .py | 0f82f5a082e17cfe | 7 | 0 |
import unittest
from unittest.mock import Mock, PropertyMock
from wheezy.core.benchmark import Benchmark, Timer
class BenchmarkTestCase(unittest.TestCase):
def test_run(self):
"""Ensure targets are called."""
t1 = Mock()
t1.__name__ = "t1"
t2 = Mock()
t2.__name... | akornatskyy/wheezy.core | src/wheezy/core/tests/test_benchmark.py | .py | 206431740cf10481 | 7.5 | 0 |
import unittest
from wheezy.core.gzip import compress, decompress
class GzipTestCase(unittest.TestCase):
def test_compress_decompress(self):
"""Ensure decompress is a reverse function of compress."""
c = compress("test".encode("utf-8"))
assert "test" == decompress(c).decode("utf-... | akornatskyy/wheezy.core | src/wheezy/core/tests/test_gzip.py | .py | 45d46303246829b8 | 7 | 0 |
import unittest
from unittest.mock import ANY, call, patch
from wheezy.core.mail import (
Alternative,
Attachment,
MailMessage,
Related,
SMTPClient,
mail_address,
mime,
mime_alternative,
mime_attachment,
mime_header,
mime_multipart,
mime_part,
)
def ... | akornatskyy/wheezy.core | src/wheezy/core/tests/test_mail.py | .py | 951b6d310698cd5b | 7.5 | 0 |
from urllib.parse import urlunsplit
def urlparts(
parts=None, scheme=None, netloc=None, path=None, query=None, fragment=None
):
"""Factory function for :py:class:`~wheezy.core.url.UrlParts` that
create an instance :py:class:`~wheezy.core.url.UrlParts` with
partial content.
``parts`` mus... | akornatskyy/wheezy.core | src/wheezy/core/url.py | .py | 352f95567773c028 | 7 | 0 |
from base64 import b64decode, b64encode
from binascii import Error
from uuid import UUID
BASE64_ALTCHARS = "-_".encode("latin1")
BASE64_SUFFIX = "==".encode("latin1")
UUID_EMPTY = UUID("00000000-0000-0000-0000-000000000000")
def shrink_uuid(uuid):
"""Returns base64 representation of ``uuid``.
>>... | akornatskyy/wheezy.core | src/wheezy/core/uuid.py | .py | 6766674517e6ac5f | 7 | 0 |
"""Lightweight DataCite client wrapper."""
from __future__ import annotations
import logging
import netrc
import sys
import time
import traceback
from typing import Any
import requests
from requests.auth import HTTPBasicAuth
from gen_pids.settings import (
DATACITE_RATE_LIMIT,
DATACITE_RATE_LIMIT_TIMEOUT,
... | spraakbanken/metadata-api | gen_pids/datacite.py | .py | b3002945d13cf732 | 7.15 | 1 |
"""Utility functions for dumping YAML files with preserved formatting."""
from pathlib import Path
from typing import Any
import yaml
def str_presenter(dumper: yaml.Dumper, data: str) -> yaml.ScalarNode:
"""Configure yaml package for dumping multiline strings (for preserving format).
# https://github.com/y... | spraakbanken/metadata-api | gen_pids/dump_yaml.py | .py | bbbd57715f9e02d5 | 7.15 | 1 |
"""Logging utilities for gen_pids."""
from __future__ import annotations
import datetime
import logging
from pathlib import Path
from gen_pids.settings import LOG_FORMAT
def configure_logging(log_dir: Path, logger: logging.Logger) -> None:
"""Ensure logging is configured."""
logging.basicConfig(level=loggi... | spraakbanken/metadata-api | gen_pids/log_utils.py | .py | 94299fca1976cb57 | 7.15 | 1 |
"""Helper functions for DMS metadata generation."""
import datetime
import logging
import re
from typing import Any
import markdown
import pycountry
from bs4 import BeautifulSoup
from gen_pids.settings import (
DMS_CREATOR_NAME,
DMS_CREATOR_ROR,
DMS_LANG_ENG,
DMS_LANG_MUL,
DMS_LANGUAGE_SCHEME_URI... | spraakbanken/metadata-api | gen_pids/utils.py | .py | 15d6883c604ca517 | 7.15 | 1 |
"""Adapt JSON schema to the resource data that is output by the API."""
# Changes to be applied to the JSON schema
SCHEMA_CHANGES = {
# Properties to add or update
"update_properties": {
"id": {"description": "Unique identifier for the resource", "type": "string", "pattern": "^[a-z0-9_-]+$"},
"... | spraakbanken/metadata-api | metadata_api/adapt_schema.py | .py | b73aa84f67574449 | 7.15 | 1 |
"""Memcached client management."""
import logging
from collections.abc import Generator
from contextlib import contextmanager
from typing import Any
logger = logging.getLogger(__name__)
class CacheManager:
"""Manages the cache client instance."""
def __init__(self) -> None:
"""Initialize the CacheM... | spraakbanken/metadata-api | metadata_api/memcached.py | .py | 9153c7dc2b05c74b | 7.15 | 1 |
"""Pydantic models for the metadata API responses."""
from pydantic import BaseModel, ConfigDict, Field
class Resource(BaseModel):
"""Metadata resource; keep permissive."""
model_config = ConfigDict(extra="allow")
id: str = Field(..., description="Unique identifier for the resource", examples=["attasido... | spraakbanken/metadata-api | metadata_api/models.py | .py | f5cf7d3e7b4ec950 | 7.15 | 1 |
"""Util functions used by the metadata API."""
from __future__ import annotations
import datetime
import json
import logging
import tomllib
from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, Any
import requests
from metadata_api.settings import settings
if TYPE_CHECKING:
from pyme... | spraakbanken/metadata-api | metadata_api/utils.py | .py | 877bdcea3eed7d02 | 7.15 | 1 |
"""Tests for parse_yaml module."""
import logging
from collections import defaultdict
from pathlib import Path
import pytest
from metadata_api.parse_yaml import _get_validator, _process_yaml_file # ruff: ignore[import-private-name]
from metadata_api.settings import settings
YAML_CONTENT: str = """
name:
swe: t... | spraakbanken/metadata-api | tests/test_parse_yaml.py | .py | a67e463343ca60fb | 7.65 | 1 |
"""Application-owned administrator and principal authority boundary."""
from __future__ import annotations
import logging
from collections.abc import Mapping
from typing import Any
from .app_support import _parse_admin_user_ids, _PrincipalAuthority
from .interfaces import DeliveryTarget, PluginPrincipal, ScheduleDel... | SukiYume/XiaoQing | core/app_identity.py | .py | f7aa84029ab6edb6 | 7.3 | 3 |
# mypy: disable-error-code=attr-defined
"""Application-owned plugin watcher supervision."""
from __future__ import annotations
import asyncio
import logging
from collections.abc import Mapping
from typing import Any
from .app_support import (
_AppLifecycleState,
_coerce_runtime_number,
_run_background_op... | SukiYume/XiaoQing | core/app_plugin_watch.py | .py | b03f93547a68d304 | 7.3 | 3 |
"""Shared application credentials, lifecycle records, and principal authority."""
import asyncio
import logging
import math
import weakref
from collections.abc import Awaitable, Callable, Mapping
from contextvars import ContextVar
from dataclasses import dataclass
from enum import Enum
from typing import Any, Literal,... | SukiYume/XiaoQing | core/app_support.py | .py | baca8dd4b4873dfd | 7.3 | 3 |
"""
命令参数解析模块
提供灵活的命令参数解析功能。
"""
import re
import shlex
from dataclasses import dataclass, field
_SHORT_OPTION_PATTERN = re.compile(r"-[A-Za-z]\Z")
_LONG_OPTION_PATTERN = re.compile(r"--[A-Za-z][A-Za-z0-9_-]*(?:=.*)?\Z")
_INTEGER_PATTERN = re.compile(r"[+-]?[0-9]+\Z")
FLAG_VALUE = "true"
def _is_option_token(token:... | SukiYume/XiaoQing | core/args.py | .py | c9939d04437c94ba | 7.3 | 3 |
"""Core 与插件共用的崩溃安全本地持久化原语。"""
from __future__ import annotations
import json
import os
import tempfile
import threading
import time
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Any, TypeVar
T = TypeVar("T")
MI... | SukiYume/XiaoQing | core/atomic_store.py | .py | 56781a037c57217d | 7.3 | 3 |
"""In-process delivery receipts for commit-after-ack plugin state."""
from __future__ import annotations
import inspect
import logging
import threading
from collections.abc import Awaitable, Callable, Sequence
from dataclasses import dataclass
from typing import Any
from .interfaces import DeliveryTarget
from .messa... | SukiYume/XiaoQing | core/delivery.py | .py | 88593e97f1f18be9 | 7.3 | 3 |
"""Security policy for XiaoQing's plaintext inbound HTTP/WS listeners."""
from __future__ import annotations
import ipaddress
from typing import Literal
from urllib.parse import SplitResult, urlsplit
InboundTransport = Literal["http", "ws"]
def is_loopback_host(host: str) -> bool:
"""Return whether a listener ... | SukiYume/XiaoQing | core/inbound_policy.py | .py | b58fa3b4379986a3 | 7.3 | 3 |
"""核心生命周期任务的取消与致命异常处理。
应用和入站服务器都需要在调用方被取消后继续完成自己拥有的回滚任务。本模块集中维护这组
语义,避免两套实现随时间产生差异。
"""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from typing import Any
class LazyAsyncLock:
"""在首次异步操作时创建锁,供可在同步阶段构造的长期对象使用。"""
__slots__ = ("_lock",)
def __init__... | SukiYume/XiaoQing | core/lifecycle.py | .py | 57b987e7478efaf9 | 7.3 | 3 |
"""
消息处理工具
提供消息解析功能。
"""
import re
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any
_MEDIA_SEGMENT_TYPES = frozenset({"image", "mface", "face"})
class ValidatedInboundEvent(dict[str, Any]):
"""Detached, mutable payload that crossed the OneBot validation boundary.
... | SukiYume/XiaoQing | core/message.py | .py | 29b285dd470efc2f | 7.3 | 3 |
"""
性能监控模块
提供插件执行时间统计、消息处理监控等功能。
"""
import asyncio
import functools
import logging
import threading
import time
from collections import defaultdict
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
logger = logging.getLogger(__name__)
@dataclass
class ExecutionStats:
... | SukiYume/XiaoQing | core/metrics.py | .py | cfaafdebad2a6e31 | 7.3 | 3 |
"""Safe, correlated error responses for public plugin entry points.
Public handlers must not expose exception text to QQ users. This module keeps
the public contract deliberately small while retaining enough, bounded and
redacted diagnostic information for an operator to correlate the failure.
面向 QQ 的返回值只包含固定错误码和经校验... | SukiYume/XiaoQing | core/public_errors.py | .py | c9c9c227e39720e4 | 7.3 | 3 |
"""线程安全的命令注册、索引构建与最长触发词路由。"""
from __future__ import annotations
import logging
import threading
from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from .context import PluginContext
from .plugin_execution ... | SukiYume/XiaoQing | core/router.py | .py | 508e69b721198db5 | 7.3 | 3 |
"""Safe, restart-scoped fingerprints for sensitive log metadata.
Administrator tools intentionally accept arbitrary commands and prompts. The
payload must remain available to the tool, but ordinary logs should contain
only enough metadata to correlate lifecycle events. A process-random HMAC
key makes the fingerprint... | SukiYume/XiaoQing | core/sensitive_audit.py | .py | 5774ee97ff72ae0c | 7.3 | 3 |
import json
import os
from contextlib import contextmanager
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Iterable, Iterator, Optional, cast
import pandas as pd
import numpy as np
from data_science_pipeline.utils.io import open_with_auto_compression
def get_json_compatible_valu... | elifesciences/data-science-dags | data_science_pipeline/utils/json.py | .py | c453ffe62e124173 | 7.24 | 2 |
"""Compact catalog views used by inference data loading."""
import numpy as np
def _compact_pixel_rows(pixels, ngals, required_pixels=None):
"""Unique-pixel rows, sample→row lookup, and per-row counts — no galaxy tables.
``required_pixels`` are included in the row set even if no sample falls in
them. T... | ignaciomagana/darksirens | darksirens/catalogs/compact.py | .py | 807658d29ccbfaf2 | 7.15 | 1 |
"""Bright-siren counterpart catalog construction."""
import healpy as hp
import numpy as np
def as_counterpart_array(counterpart) -> np.ndarray:
"""Return counterpart metadata as an ``(N, 3)`` float array.
The public CLI accepts either one ``RA DEC Z`` triplet or a flattened list
of triplets for multi-e... | ignaciomagana/darksirens | darksirens/catalogs/counterparts.py | .py | 0d87fe6254fe35aa | 7.15 | 1 |
"""Survey catalog I/O helpers.
This module loads pixelated survey HDF5 files and optional per-galaxy mark
datasets. Redshift grids live in :mod:`darksirens.redshift.grid`.
"""
import jax.numpy as jnp
import numpy as np
import h5py
def _row_z_sort_order(zgals, ngals):
"""Per-row permutation sorting the real-gala... | ignaciomagana/darksirens | darksirens/catalogs/io.py | .py | 5f27eddd0795b7b4 | 7.15 | 1 |
"""Galaxy mark loading and centering helpers."""
import jax.numpy as jnp
import numpy as np
from darksirens.redshift import zgrid
from darksirens.catalogs.io import load_survey_marks
#: z-bins for centering per-galaxy marks (subtract the running mean E[m|z]).
_MARK_CENTER_NBINS = 40
def _center_marks(raw_marks: di... | ignaciomagana/darksirens | darksirens/catalogs/marks.py | .py | b800f184fcbf8394 | 7.15 | 1 |
from argparse import ArgumentParser
from pathlib import Path
import numpy as np
import h5py
import healpy as hp
from tqdm import tqdm
import matplotlib.pyplot as plt
from darksirens.cli.common import _banner, _section, _row, _end, _ok, _fatal
#: Optional per-galaxy "mark" columns -> EMCatalog mark dataset name. Rea... | ignaciomagana/darksirens | darksirens/cli/pixelate.py | .py | e9fd69ed4c23d0e1 | 7.15 | 1 |
"""One requirement table for gwcat PE/selection stores, shared by every gate.
The loaders (``darksirens.gw.utils``) and the preflight validators
(``darksirens.lensing.file_contract``) used to carry independent copies of
"what a gwcat file must contain", and the copies drifted: the preflight did
not require ``m1src``/`... | ignaciomagana/darksirens | darksirens/gw/store_contract.py | .py | 6926a6be394ef62e | 7.15 | 1 |
# data.py
import healpy as hp
import jax.numpy as jnp
import numpy as np
from darksirens.catalogs.compact import validate_loaded_survey_shapes
from darksirens.inference import loaders
from darksirens.core.model_kinds import BRIGHT_SIREN_MODELS
#: Store attrs worth carrying into the run record: they exist in the inpu... | ignaciomagana/darksirens | darksirens/inference/data.py | .py | 9d327dab7b3ee1b9 | 7.15 | 1 |
"""
pop_extractor.py
----------------
make_pop_extractor(settings) — single source of truth for extracting the
population parameter sub-vector from the flat sampled coordinate vector theta.
Multitracer post-processing
---------------------------
``catalog_sticks_to_weights`` / ``fcat_to_component_fraction`` turn the s... | ignaciomagana/darksirens | darksirens/inference/pop_extractor.py | .py | 16d60a2b3e104253 | 7.15 | 1 |
"""Q_LSS provenance enforcement.
A prebuilt LSS completion table ``Q`` is not a free function of the inference
parameters: it is a *fit*, conditioned at build time on a specific cosmology,
comoving density ``n0``, density evolution ``delta`` and field bias ``b_miss``
(``cli/build_lognormal_completion.py`` stamps all o... | ignaciomagana/darksirens | darksirens/inference/q_provenance.py | .py | 3a090e346e77cb30 | 7.15 | 1 |
"""Common definitions which are specific to the Oaat handler."""
import pykube
class ProcessingComplete(BaseException):
"""Signal from a subfunction to a handler that processing is complete."""
def __init__(self, **kwargs):
self.ret = {}
for arg in kwargs:
self.ret[arg] = kwargs[ar... | kawaja/oaat-operator | oaatoperator/common.py | .py | 7e7f0cfebe3971ec | 7.24 | 2 |
"""
oaatitem.py
Manage OaatItems within an OaatGroup.
"""
from __future__ import annotations
import datetime
import kopf
import pykube # type: ignore
from typing import Any, Optional, TYPE_CHECKING
from oaatoperator.utility import date_from_isostr, now
from oaatoperator.common import ProcessingComplete
if TYPE_CH... | kawaja/oaat-operator | oaatoperator/oaatitem.py | .py | 6396b076af3ce054 | 7.24 | 2 |
"""
utility.py
Various stand-alone utility functions.
"""
from typing import Any, Set, Optional, Callable
import datetime
import re
import sys
import inspect
UTC = datetime.timezone.utc
DURMATCH = re.compile(r'''
\b
(?P<val>\d+)
\s*
(?P<unit>(
s(ec(ond)?s?)?|
m(in(ute)?s?)?|
h... | kawaja/oaat-operator | oaatoperator/utility.py | .py | 164adf7b0642fcc8 | 7.24 | 2 |
"""Integration tests for OaatType class requiring k3d cluster."""
import unittest
import pytest
import pykube
from pykube.query import Query
from tests.integration.utils import ensure_kubeobj_deleted
from oaatoperator.common import KubeOaatType
pytestmark = pytest.mark.integration
class MiniKubeTests(unittest.Test... | kawaja/oaat-operator | tests/integration/test_oaattype_integration.py | .py | 6ea83db82d63e4f6 | 7.74 | 2 |
"""
Conditional pykube mocking module for unit tests.
This module provides mocking functionality that is applied only when explicitly requested.
This prevents integration tests from being affected by the mocking.
"""
import os
import sys
from unittest.mock import Mock, patch
import pykube
# Global variables to store... | kawaja/oaat-operator | tests/unit/early_pykube_mock.py | .py | 765a0502f8baf3df | 7.74 | 2 |
"""Integration tests for OaatGroup runtime statistics functionality."""
import pytest
import unittest
import unittest.mock
import datetime
from unittest.mock import Mock, patch
# Test setup imports
import sys
import os
sys.path.append(os.path.dirname(
os.path.realpath(__file__)) + "/../../oaatoperator")
from tes... | kawaja/oaat-operator | tests/unit/test_oaatgroup_runtime_stats.py | .py | 426044f17fcb66da | 7.74 | 2 |
"""Unit tests for runtime statistics collection and prediction."""
import pytest
import math
from oaatoperator.runtime_stats import JobRuntimeStats, RuntimeStatsManager
class TestJobRuntimeStats:
"""Test the JobRuntimeStats class."""
def test_init_defaults(self):
"""Test default initialization."""
... | kawaja/oaat-operator | tests/unit/test_runtime_stats.py | .py | e76b846c12a0cbe0 | 7.74 | 2 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This script contains historical benchmarking code that was originally at the
end of the System.py module. It compares the performance of the obsolete
`SymbolicComputer` class with the `IndexedBaseSymbolicComputer`.
"""
import timeit
import numpy as np
import sympy as ... | ashishbhatt8050/constrained_mechanics | scripts/benchmark_symbolics.py | .py | fabcdc697eed3341 | 7 | 0 |
#%%
import numpy as np
import time
from scipy.linalg import qr
import matplotlib.pyplot as plt
import sympy as sp
# make text in plots twice as large as the default
plt.rcParams.update({'font.size': 14})
# Parameters
nx = 100 # grid points in x
ny = 100 # grid points in y
n = nx * ny # dimension of the full system... | ashishbhatt8050/constrained_mechanics | scripts/deim_2d_comparison.py | .py | 57e3f5f11fe8fabe | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import os
import sys
import cloudpickle as pickle
import time
from functools import partial
from itertools import product
import multiprocessing
import matplotlib.pyplot as plt
from scipy.linalg import qr
import sympy as sp
# Add project source to path... | ashishbhatt8050/constrained_mechanics | scripts/deim_nd_comparison.py | .py | ea7db0145f23a7cf | 7 | 0 |
from numpy import linalg as LA
import numpy as np
def Newton(f, x, dfdx, tol, M, store):
"""
Newton's method for finding roots of a function.
Parameters:
f (function): The function to find roots for.
x (float or array): The initial guess.
dfdx (function): The derivative of the function.
to... | ashishbhatt8050/constrained_mechanics | src/Newton.py | .py | 5b82b37353c327b7 | 7 | 0 |
import numpy as np
import sympy as smp
from functools import wraps
from PlotScript import timing
import concurrent.futures
import cloudpickle
from tqdm.auto import tqdm
import joblib
import os
import json
import shutil
CODE_VERSION = "1.0"
class ShapeWrapper:
"""Picklable wrapper for handling input shapes."""
... | ashishbhatt8050/constrained_mechanics | src/SymbolicComputer.py | .py | d46be6365207f93a | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 11 11:38:09 2021
@author: bhattah
function DEIM to obtain Interpolating matrix P and a list of interpolation
indices P_list from DEIM basis Ub, a POD basis of nonlinear function
Tests for the 1D and 2D cases
"""
from mpl_toolkits.mplot3d.axes3d... | ashishbhatt8050/constrained_mechanics | src/podDEIM.py | .py | f6fc42aea28becfc | 7 | 0 |
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from treegrafter import _querymsf
def test_single_domain_single_block():
"""Single domain, alignment fits in one block (< 80 chars)."""
match_data = {
'hmmstart': ['3'],
'hmmend': ['8'],
... | ebi-pf-team/treegrafter | tests/test_querymsf.py | .py | 2998a2f4109c19d3 | 7.5 | 0 |
import re
def dollars_to_math(source):
r"""
Replace dollar signs with backticks.
More precisely, do a regular expression search. Replace a plain
dollar sign ($) by a backtick (`). Replace an escaped dollar sign
(\$) by a dollar sign ($). Don't change a dollar sign preceded or
followed by a ... | maahn/meteo_si | doc/sphinxext/math_dollar.py | .py | 2d23b9da664c41c4 | 7 | 0 |
# -*- coding: utf-8 -*-
# (c) Ralph Carmichael, Public Domain Aeronautical Software (original
# algorithm, http://www.pdas.com/programs/atmos.f90)
# (c) Maximilian Maahn 2011 (Python translation)
'''
Functions to compute properties of the 1976 US Standard Atmosphere.
'''
from collections.abc import Iterable
imp... | maahn/meteo_si | meteo_si/atmosphere.py | .py | e0b424a20ad44f3a | 7 | 0 |
# emacs: at the end of the file
# ex: set sts=4 ts=4 sw=4 et:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
"""
Stub file for a guaranteed safe import of duecredit constructs: if duecredit
is not available.
To use it, place it into your project codebase to be imported, e.g. copy as
... | maahn/meteo_si | meteo_si/due.py | .py | 7df16fedc9cd0385 | 7 | 0 |
import asyncio
import json
import logging
import structlog
from redis.asyncio import Redis as AIORedis
from shared import REPEAT, get_big_dict, timeit
from nwastdlib.asyncio_cache import cached_result
cache: AIORedis = AIORedis(host="127.0.0.1", port=6379)
logger = structlog.get_logger(__name__)
structlog.configure... | workfloworchestrator/nwa-stdlib | benchmarks/benchmark_async_cache_with_json.py | .py | 46037bcda10784d2 | 7.24 | 2 |
# Copyright 2019-2026 SURF.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | workfloworchestrator/nwa-stdlib | nwastdlib/asyncio_cache.py | .py | f402a15311edec97 | 7.24 | 2 |
# Copyright 2019-2026 SURF.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | workfloworchestrator/nwa-stdlib | nwastdlib/f.py | .py | e5aa1c90a4af05af | 7.24 | 2 |
# Copyright 2019-2026 SURF.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | workfloworchestrator/nwa-stdlib | nwastdlib/graphql/extensions/deprecation_checker_extension.py | .py | f20ae31dd91b8bc7 | 7.24 | 2 |
# Copyright 2019-2026 SURF.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | workfloworchestrator/nwa-stdlib | nwastdlib/graphql/extensions/error_handler_extension.py | .py | b48584d5f905d87f | 7.24 | 2 |
# Copyright 2019-2026 SURF.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | workfloworchestrator/nwa-stdlib | nwastdlib/logging.py | .py | 574f3a9b9d1c9edd | 7.24 | 2 |
# Copyright 2019-2026 SURF.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | workfloworchestrator/nwa-stdlib | nwastdlib/url.py | .py | 3b7bd615cf2bd16e | 7.24 | 2 |
# Copyright 2019-2026 SURF.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | workfloworchestrator/nwa-stdlib | nwastdlib/vlans.py | .py | 81bb79b46fb0eded | 7.24 | 2 |
import ast
import logging
from decimal import ROUND_HALF_UP, Decimal
from django.conf import settings
from django.db import transaction
from paypal.standard.ipn.signals import valid_ipn_received
from paypal.standard.models import ST_PP_COMPLETED, ST_PP_PENDING
from plans import utils as plans_utils
from plans.base.mod... | PetrDlouhy/django-plans-paypal | plans_paypal/hooks.py | .py | b3228fa019f6ba68 | 7.24 | 2 |
from django.core import checks
from django.test import TestCase
from django.urls import reverse
from model_bakery import baker
from plans_paypal.models import PayPalPayment
class PayPalPaymentAdminTests(TestCase):
def setUp(self):
self.superuser = baker.make("User", is_staff=True, is_superuser=True)
... | PetrDlouhy/django-plans-paypal | plans_paypal/tests/test_admin.py | .py | 35061b9c35099882 | 7.74 | 2 |
#!/usr/bin/env python3
"""
笔试题生成器
从模板生成可执行的编程练习文件
用法:
python generate_problem.py --lang python --output /path/to/output.py --config problem.json
或通过参数直接指定:
python generate_problem.py --lang python \
--company "字节跳动" \
--position "后端工程师" \
--title "两数之和" \
--difficulty 2... | hotttao/backup | .codex/skills/interview-coach/scripts/generate_problem.py | .py | 469f221d580bdf87 | 7.24 | 2 |
#!/usr/bin/env python3
"""
代码评测器
运行用户代码,对比测试用例,给出评分和反馈
用法:
python judge.py --solution solution.py --test-cases cases.json
python judge.py --solution solution.py --function-name "solution" --cases '[{"input": [1,2], "expected": 3}]'
输出:
- 每个用例的通过/失败状态
- 运行时间
- 内存使用(近似)
- 总体评分
"""
import argpar... | hotttao/backup | .codex/skills/interview-coach/scripts/judge.py | .py | 07eddb3493e1f7e2 | 7.24 | 2 |
from __future__ import annotations
import sqlite3
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterator
from .models import CollectionMetadata, VideoMetadata
def utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
cl... | hotttao/backup | bilibili/src/bili_sync/database.py | .py | 17b617e8d7782568 | 7.24 | 2 |
import visdom
import numpy as np
import time
class Visualizer(object):
"""
封装了visdom的基本操作,但是你仍然可以通过`self.vis.function`
或者`self.function`调用原生的visdom接口
比如
self.text('hello visdom')
self.histogram(t.randn(1000))
self.line(t.arange(0, 10),t.arange(1, 11))
"""
def __init__(self, env='de... | Siddharth-Shrivastava7/Comparative-Study-of-Deep-Learning-Models-for-Segmentation-of-Corpus-Callosum | Visualizer.py | .py | 6529f62e9d3c10a3 | 7 | 0 |
import torch
import torch.nn as nn
from torch.autograd import Variable as V
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import cv2
import numpy
import skimage as ski
from sklearn.metrics import confusion_matrix
import numpy as np
class weighted_cross_entro... | Siddharth-Shrivastava7/Comparative-Study-of-Deep-Learning-Models-for-Segmentation-of-Corpus-Callosum | loss.py | .py | 624a498196a1f1ca | 7 | 0 |
import numpy as np
import torch
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, patience=7, verbose=False, delta=0):
"""
Args:
patience (int): How long to wait after last time validation loss improved.... | Siddharth-Shrivastava7/Comparative-Study-of-Deep-Learning-Models-for-Segmentation-of-Corpus-Callosum | pytorchtools.py | .py | 60da458ff0fd8085 | 7 | 0 |
import pytest
from rest_framework.test import APIClient
from users.models import User
@pytest.fixture
def api_client():
return APIClient()
@pytest.fixture
def user():
"""Create a user which should automatically create UserData via signal"""
return User.objects.create_user(username="testuser", email="te... | City-of-Helsinki/example-backend-profile | users/tests/conftest.py | .py | 2ac03bc6a35705de | 7 | 0 |
# -*- coding: utf-8 -*-
"""The module with ``AddKey`` class"""
import json
class AddKey:
"""A class to add a new key to each object in the JSON file.
Args:
``full_path (str)``: the full path to the JSON file.
Raises:
``FileNotFoundError``: \
if the JSON file is not found by ``fu... | andrei-polukhin/JSONManipulator | JSONManipulator/core/AddKey.py | .py | 9c150ad25fcdca06 | 7.15 | 1 |
# -*- coding: utf-8 -*-
"""The module with ``ChangeAllValues`` class"""
import json
from JSONManipulator.core.ChangeValue import ChangeValue
class ChangeAllValues(ChangeValue):
"""A class to change values of all objects in the JSON file.
Args:
``value (str)``: a redundant parameter, \
exists... | andrei-polukhin/JSONManipulator | JSONManipulator/core/ChangeAllValues.py | .py | 39c0347aec05a1ca | 7.15 | 1 |
# -*- coding: utf-8 -*-
"""The module with ``DeleteObject`` class"""
import json
from JSONManipulator.core.ChangeValue import ChangeValue
class DeleteObject(ChangeValue):
"""A class to delete found objects.
Args:
``key (str)``: to find the object by the key in the JSON file.\n
``desc (str)``... | andrei-polukhin/JSONManipulator | JSONManipulator/core/DeleteObject.py | .py | fe53f1cc7518d636 | 7.15 | 1 |
# -*- coding: utf-8 -*-
"""The JSONManipulator's exceptions."""
class NoKeyAndDesc(Exception):
"""Raised when a user has entered neither key nor desc."""
def __init__(self):
super().__init__(
"You have entered neither ``key``, nor ``desc``,"
" process terminated."
)
... | andrei-polukhin/JSONManipulator | JSONManipulator/exceptions.py | .py | 427654a58ca52425 | 7.15 | 1 |
"""SQLAlchemy database engine creation."""
import os
import sqlalchemy
from kokudaily.config import Config
CLOWDER_ENABLED = os.getenv("CLOWDER_ENABLED", "false")
if CLOWDER_ENABLED.lower() == "true":
from app_common_python import LoadedConfig, SmartAppConfig # noqa
def _create_engine_kwargs():
"""Create t... | project-koku/koku-daily | kokudaily/engine.py | .py | d70acdd23f99d14f | 7.15 | 1 |
#!/usr/bin/env -S uv run
# /// script
# requires-python = ">=3.11"
# dependencies = ["pyyaml"]
# ///
"""Derive slides_embed URLs for entries in _data/talks.yaml.
For each talk, find a Google Slides presentation URL — preferring the
slides_edit field, then a direct slides URL, then resolving a bit.ly /
j.mp slides alia... | mithro/mithro.github.io | scripts/enrich_talk_embeds.py | .py | 2cc8fb7fb210971f | 7 | 0 |
# /// script
# requires-python = ">=3.11"
# dependencies = ["pyyaml"]
# ///
"""Fetch all bitlinks for the mithro bit.ly group into _data/shortlinks.yaml.
Usage: BITLY_TOKEN=... uv run scripts/fetch_bitly.py
The token is never written anywhere; keep it out of the repo and shell history
(e.g. `read -s BITLY_TOKEN && exp... | mithro/mithro.github.io | scripts/fetch_bitly.py | .py | aa1bfa23a8890a12 | 7 | 0 |
import logging
import os
import boto3
from botocore.exceptions import ClientError
from nise.report import aws_create_report
from sources.source import Source
LOG = logging.getLogger(__name__)
class AWS(Source):
"""Defining the AWS source class."""
BUCKET = "bucket"
REPORT_PREFIX = "report_prefix"
... | project-koku/nise-populator | nise-populator/sources/aws.py | .py | f6c52daf3962e4b1 | 7 | 0 |
import logging
import os
from azure.core.exceptions import HttpResponseError
from azure.core.exceptions import ResourceExistsError
from azure.storage.blob import BlobServiceClient
from nise.report import azure_create_report
from sources.source import Source
LOG = logging.getLogger(__name__)
class Azure(Source):
... | project-koku/nise-populator | nise-populator/sources/azure.py | .py | f06714e91b8af121 | 7 | 0 |
import logging
import os
from nise.report import gcp_create_report
from sources.source import Source
LOG = logging.getLogger(__name__)
class GCP(Source):
"""Defining the GCP source class."""
BUCKET = "bucket"
REPORT_PREFIX = "report_prefix"
REPORT_NAME = "report_name"
ETAG = "etag"
def __... | project-koku/nise-populator | nise-populator/sources/gcp.py | .py | 04af9ea848659220 | 7 | 0 |
import logging
import os
from datetime import timedelta
from nise.report import ocp_create_report
from sources.source import Source
LOG = logging.getLogger(__name__)
class OCP(Source):
"""Defining the OCP source class."""
CLUSTER_ID = "cluster_id"
def __init__(self, **kwargs):
"""Initialize t... | project-koku/nise-populator | nise-populator/sources/ocp.py | .py | 603dc4f286a17ee8 | 7 | 0 |
import os
from abc import ABC
from abc import abstractmethod
from datetime import datetime
import yaml
from utils import get_static_file_path
from utils import load_yaml_file
class Source(ABC):
"""Defining an abstract class for sources."""
STATIC_FILE = "static-file"
@abstractmethod
def __init__(s... | project-koku/nise-populator | nise-populator/sources/source.py | .py | a77dc97a7106757e | 7 | 0 |
import logging
import os
from sources.aws import AWS
from sources.azure import Azure
from sources.gcp import GCP
from sources.ocp import OCP
LOG = logging.getLogger(__name__)
class SourceFactory:
"""Create sources from provided source configuration."""
def __init__(self, source_config):
"""Initiali... | project-koku/nise-populator | nise-populator/sources/source_factory.py | .py | 7355b585f1f62b42 | 7 | 0 |
import os
import yaml
def load_yaml_file(filename):
"""Local data from yaml file."""
yamlfile = None
if filename:
try:
with open(filename) as yaml_file:
yamlfile = yaml.safe_load(yaml_file)
except TypeError:
yamlfile = yaml.safe_load(filename)
r... | project-koku/nise-populator | nise-populator/utils.py | .py | aa3122f13e3ebae4 | 7 | 0 |
# Copyright 2019-2026 SURF.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | workfloworchestrator/oauth2-lib | oauth2_lib/async_api_client.py | .py | 189cb9f18a05906b | 7.3 | 3 |
# Copyright 2019-2026 SURF.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | workfloworchestrator/oauth2-lib | oauth2_lib/fastapi.py | .py | e5322696aa2bebb7 | 7.3 | 3 |
import json
from http import HTTPStatus
from unittest import mock
import pytest
import urllib3
from urllib3_mock import Responses
from oauth2_lib.async_api_client import AsyncAuthMixin
EXPIRED_TOKEN = "expired token" # noqa: S105
VALID_TOKEN = "valid token" # noqa: S105
BASE_URL = "http://my-api"
class ApiExce... | workfloworchestrator/oauth2-lib | tests/test_async_api_client.py | .py | e3920a004c77b851 | 7.8 | 3 |
import math
import random
import time
from typing import List
from tests.test_data.constants import index_definition
def create_items(db, ns, items: list):
""" Create items
"""
for item in items:
db.item.insert(ns, item)
def get_ns_items(db, ns_name):
""" Get all items via sql query
"""... | Restream/reindexer-py | pyreindexer/tests/helpers/base_helper.py | .py | a5fb3431d8147b76 | 7.89 | 5 |
# -*- coding: utf-8 -*-
import logging
import os
import sys
from datetime import *
class OneLineExceptionFormatter(logging.Formatter):
""" One line log output
https://docs.python.org/2/howto/logging-cookbook.html#logging-cookbook
"""
def formatException(self, exc_info):
result = super(OneLine... | Restream/reindexer-py | pyreindexer/tests/helpers/log_helper.py | .py | e49033d5c4715f49 | 7.89 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.