text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
import os
import requests
def fetch_xml(pmc_id: str, db_name='pmc') -> str:
"""
https://www.ncbi.nlm.nih.gov/pmc/tools/get-full-text/
"""
efetch_url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi'
resp = requests.get(efetch_url, params={'db': db_name, 'id': pmc_id, 'rettype': 'xml'}... | jakelever/bioconverters | tests/util.py | .py | fca7ecb8921ceddc | 7 | 0 |
"""Support Disperse I/O.
The reader is based on a description of the structure using Kaitai (https://kaitai.io/).
"""
import numpy as np
import pandas as pd
from ..utilities.decorators import read_files
from ..utilities.custom_types import FloatArrayType, PathType
from .disperse_reader import DisperseReader
class ... | cphyc/astrophysics_toolset | astrophysics_toolset/io/disperse.py | .py | 74d6e8de12fe7e52 | 7.39 | 5 |
"""Useful decorators."""
import os
from functools import wraps
from typing import Callable
import numpy as np
from .exceptions import AstroToolsetNotSpatialError
class read_files: # noqa: N801
"""Decorator for functions that take a file as input.
Parameters:
-----------
N : int
List of th... | cphyc/astrophysics_toolset | astrophysics_toolset/utilities/decorators.py | .py | 247358840d649e6c | 7.39 | 5 |
"""Handle periodicity."""
import numpy as np
from .decorators import spatial
from .custom_types import FloatArrayType
@spatial
def wrap_coordinates(x: FloatArrayType, w: float = 1) -> FloatArrayType:
"""Wrap the position, taking into account periodicity.
Parameters:
-----------
x : 3D array
... | cphyc/astrophysics_toolset | astrophysics_toolset/utilities/periodicity.py | .py | 849a2da34f39c507 | 7.39 | 5 |
"""Scale bar from https://gist.github.com/dmeliza/3251476."""
# Adapted from mpl_toolkits.axes_grid1
# LICENSE: Python Software Foundation (http://docs.python.org/license.html)
import warnings
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import LineCollectio... | cphyc/astrophysics_toolset | astrophysics_toolset/visualization/plotting.py | .py | d1440aa110610c00 | 7.39 | 5 |
from typing import Any
from collections.abc import Callable
from tqdm import tqdm
import yt
from yt.data_objects.data_containers import YTDataContainer
from scipy.spatial import KDTree
import numpy as np
import networkx as nx
def watershed_split(G: nx.Graph, value_attr="density", min_value=0):
"""
Split the... | cphyc/astrophysics_toolset | astrophysics_toolset/yt/clump_finding.py | .py | 8496062a2ddaf136 | 7.39 | 5 |
"""Define useful functions for working with stars."""
from pathlib import Path
from typing import Literal, Optional
import joblib
import numpy as np
import yt
from scipy.interpolate import RegularGridInterpolator
from yt.utilities.on_demand_imports import NotAModule
location = Path("~/.cache/fsps").expanduser()
loca... | cphyc/astrophysics_toolset | astrophysics_toolset/yt/stars.py | .py | 72454257e778258b | 7.39 | 5 |
from ansible.plugins.callback.junit import (
CallbackModule as JunitCallbackModule,
)
from ansible.plugins.callback.junit import HostData
import os
import re
DOCUMENTATION = '''
callback: custom_junit
type: notification
short_description: TODO
description:
custom_junit generates an XML files... | infrawatch/feature-verification-tests | callback_plugins/custom_junit.py | .py | 48b2742006b6cfb9 | 7.3 | 3 |
from __future__ import (absolute_import, division, print_function)
# __metaclass__ = type
import os
import re
from ansible.plugins.callback import CallbackBase
DOCUMENTATION = '''
callback: log_to_file
type: notification
short_description: output logs to a file
description:
- This callback functi... | infrawatch/feature-verification-tests | callback_plugins/custom_logger.py | .py | ef1e9634c630173d | 7.3 | 3 |
#!/usr/bin/env python3
"""
Parse Loki JSON (or text) into [timestep, log_entry] pairs, then emit a YAML
summary: time, data_log, and rate (per-type Σ(price) and total Rating).
Same CLI as gen_synth_loki_metrics_totals.py (-j, -o, --debug).
"""
from __future__ import annotations
import argparse
import json
import sys
... | infrawatch/feature-verification-tests | roles/telemetry_chargeback/files/gen_db_summary.py | .py | 6b575c593ed1c4cc | 7.3 | 3 |
"""Generate synthetic Loki log data from a Jinja2 template."""
import logging
import argparse
import json
import sys
import yaml
from datetime import datetime, timezone, timedelta
from pathlib import Path
from typing import Dict, Any, List, Union
from jinja2 import Environment
def _apply_mutate(qty: float, mutate) ->... | infrawatch/feature-verification-tests | roles/telemetry_chargeback/files/gen_synth_loki_data.py | .py | ef18a2242fe2cde2 | 7.3 | 3 |
import logging
import os
import requests
import urllib.parse
from flask import json, Flask, request, jsonify, redirect
from qwc_services_core.auth import auth_manager, optional_auth, get_identity
from qwc_services_core.tenant_handler import TenantHandler, TenantPrefixMiddleware, TenantSessionInterface
from qwc_servic... | qwc-services/qwc-map-viewer | src/server.py | .py | c31fff6acf28a99e | 7.3 | 3 |
#!/usr/bin/env python
from __future__ import annotations
import logging
import sys
from typing import Any, cast
try:
from PySide6 import QtCore, QtGui, QtWidgets
except ImportError as exc:
sys.exit(
f"PIM_GUI_Calculator needs PySide6: {exc}\n"
"Python deps: uv sync --project python --extra ... | panjacek/PIM_Calculator | python/PIM_Calculator/pimQt.py | .py | fd5bacbf5e25b15e | 7.24 | 2 |
"""pytest-benchmark performance tests.
Run separately via `make test-perf`.
Default unit suite excludes these with `-m "not benchmark"`.
"""
from __future__ import annotations
import pytest
from pytest_benchmark.fixture import BenchmarkFixture
from PIM_Calculator.pim_calc import PIMCalc, PimTable
def make_tx_list... | panjacek/PIM_Calculator | python/PIM_Calculator/tests/test_perf.py | .py | 67d4dcb53c5c12b3 | 7.74 | 2 |
"""Module providing the ``upgrade-kernel`` and ``rebuild-kernel`` commands."""
from __future__ import annotations
from multiprocessing import cpu_count
from typing import TYPE_CHECKING
from bascom import setup_logging
from upkeep.decorators import umask
from upkeep.exceptions import KernelError
from upkeep.utils.kern... | Tatsh/upkeep | upkeep/commands/kernel.py | .py | d274eb94d558f187 | 7.35 | 4 |
"""Decorators."""
from __future__ import annotations
from functools import wraps
from os import umask as set_umask
from typing import TYPE_CHECKING, ParamSpec, TypeVar
if TYPE_CHECKING:
from collections.abc import Callable
__all__ = ('umask',)
P = ParamSpec('P')
T = TypeVar('T')
def umask(new_umask: int, *, r... | Tatsh/upkeep | upkeep/decorators.py | .py | a4e2b36ca1b35795 | 7.35 | 4 |
"""
Purpose:
This demo shows relational and native data access side-by-side in a Python
application connected to InterSystems IRIS.
A single DB-API connection serves both access models: SQL runs through its
cursors, and the same connection object backs the Native SDK.
To test:
Run the script to populate and retrieve ... | intersystems/quickstarts-multimodel-python | multimodelQS.py | .py | dea14391bbc93a81 | 7.39 | 5 |
from typing import Optional, Union, Dict, List
from pyMathBitPrecise.bit_utils import ValidityError
from copy import copy
class Array3t():
def __init__(self, element_t, size: int, name: Optional[str]=None):
self.element_t = element_t
self.size = int(size)
self.name = name
def __eq__... | Nic30/pyMathBitPrecise | pyMathBitPrecise/array3t.py | .py | 2d7cb15566539e38 | 7.39 | 5 |
from collections import OrderedDict
from typing import List, Optional
from pyMathBitPrecise.bits3t import Bits3val
class Enum3val():
def __init__(self, t, val, vld_mask):
self._dtype = t
self.val = val
self.vld_mask = vld_mask
def __copy__(self):
return self.__class__(self._... | Nic30/pyMathBitPrecise | pyMathBitPrecise/enum3t.py | .py | ab6475bfc2dd8fe8 | 7.39 | 5 |
from decimal import DecimalTuple
import math
from operator import lt, le, ge, gt, add, truediv, sub, mul
from typing import Union, Optional, Tuple
from pyMathBitPrecise.array3t import Array3t
from pyMathBitPrecise.bit_utils import ValidityError
from pyMathBitPrecise.bits3t import Bits3t
# from decimal import Decimal... | Nic30/pyMathBitPrecise | pyMathBitPrecise/floatt.py | .py | ff697ef7dc9cd4a6 | 7.39 | 5 |
#!/usr/bin/env python3
from datetime import datetime
import json
import os
import subprocess
import sys
import click
import requests
import toml
@click.group()
@click.option('--debug/--no-debug', default=False)
def cli(debug):
pass
@cli.group()
def account():
pass
@cli.group()
def config():
pass
@cli.... | O1ahmad/container-file-geth | scripts/geth-helper.py | .py | 84d8aeb9946974d8 | 7.39 | 5 |
"""herethere.everywhere.config"""
import os
from dataclasses import asdict, dataclass, fields
from os import environ
from typing import Any
from dotenv import dotenv_values, find_dotenv, set_key
class ConnectionConfigError(Exception):
"""Connection config error."""
def prefixed_key(*, key: str, prefix: str) -... | b3b/herethere | herethere/everywhere/config.py | .py | 8471bf46a352d818 | 7 | 0 |
"""Structured live-session execution helpers shared by the SSH server."""
import traceback
from dataclasses import dataclass
from typing import Any, TextIO
from herethere.everywhere.redirected_output import redirect_output
MAX_TRACEBACK_BYTES = 64 * 1024
@dataclass(frozen=True)
class LiveError:
"""Structured e... | b3b/herethere | herethere/everywhere/live.py | .py | 49a8edcb1d3a0b8f | 7 | 0 |
"""Async helpers for synchronous IPython magic methods.
The IPython magic API used by herethere is synchronous: methods such as
``%connect-there`` and foreground ``%there`` commands must return their result
before the magic call finishes. The underlying implementation is async because
SSH and SFTP operations are handl... | b3b/herethere | herethere/everywhere/loop.py | .py | 5df65e8b4fc87735 | 7 | 0 |
"""JSON-lines protocol helpers for structured live-session commands."""
import json
from dataclasses import dataclass
from typing import Any, Literal, TextIO
MAX_WORKER_OUTPUT_BYTES = 1024 * 1024
MAX_WORKER_OUTPUT_EVENTS = 16_384
WORKER_OUTPUT_TRUNCATION_MARKER = "[herethere: worker output truncated]\n"
StreamName = ... | b3b/herethere | herethere/everywhere/protocol.py | .py | dfa188ee7aaf0edc | 7 | 0 |
"""Bounded recent Python logging shared by the server and client."""
import logging
from collections import deque
from dataclasses import dataclass
RECENT_LOGS_RESPONSE_TYPE = "recent-logs"
RECENT_LOGS_PROTOCOL_VERSION = 1
RECENT_LOGS_FORMAT = "[%(levelname)s] %(asctime)s %(threadName)s %(name)s: %(message)s"
DEFAULT... | b3b/herethere | herethere/everywhere/recent_logs.py | .py | 7ccc1516855514dc | 7 | 0 |
"""herethere.everywhere.redirected_output"""
import sys
from collections.abc import Iterator
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TextIO
class RedirectedOutputWrapper:
"""Wrapper for I/O stream redirection."""
def __init__(self, stream: TextIO):
... | b3b/herethere | herethere/everywhere/redirected_output.py | .py | 60ea156ea84c01a0 | 7 | 0 |
"""Structured remote shell protocol definitions."""
from dataclasses import dataclass
SHELL_PROTOCOL_VERSION = 1
SHELL_STREAM_EVENT = "shell-stream"
SHELL_RESULT_EVENT = "shell-result"
MAX_SHELL_COMMAND_BYTES = 64 * 1024
@dataclass(frozen=True)
class ShellResult:
"""Completion status returned by a structured re... | b3b/herethere | herethere/everywhere/shell.py | .py | ccb04fab0b4e58da | 7 | 0 |
"""Remote value serialization helpers."""
import base64
import json
import pickle
from typing import Any
MAX_VALUE_PAYLOAD_SIZE = 32 * 1024 * 1024
class RemoteValueError(RuntimeError):
"""Raised when remote value computation fails."""
def __init__(self, error_type: str, message: str, traceback_text: str):
... | b3b/herethere | herethere/everywhere/values.py | .py | 8e5e4d7f427daa1b | 7 | 0 |
"""herethere.here.__main__"""
import asyncio
import logging
import asyncssh
from .config import ServerConfig
from .server import start_server
def configure_logging():
"""Configure logging for the command-line server."""
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelna... | b3b/herethere | herethere/here/__main__.py | .py | f5a94b16e0d707b6 | 7 | 0 |
"""here.magic"""
from IPython.core import magic_arguments
from IPython.core.magic import (
line_magic,
magics_class,
)
from IPython.core.magic_arguments import parse_argstring
from herethere.everywhere.loop import run_sync
from herethere.everywhere.magic import MagicEverywhere
from herethere.here import Serve... | b3b/herethere | herethere/here/magic.py | .py | 02484b7c3df37755 | 7 | 0 |
"""herethere.here.server"""
import asyncio
import inspect
import logging
import os
import threading
import traceback
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from functools import partial
from io import StringIO
from typing import Any
imp... | b3b/herethere | herethere/here/server.py | .py | 457086a2276e1dbd | 7 | 0 |
"""Shared shell subprocess execution and SSH protocol adapters."""
import asyncio
import base64
import contextlib
import os
import signal
from asyncio.subprocess import Process
from collections.abc import Callable
from typing import Protocol
import asyncssh
from herethere.everywhere.protocol import decode_request_ob... | b3b/herethere | herethere/here/shell.py | .py | fc6b4f120c3af98e | 7 | 0 |
"""Configuration for %%there ai."""
from dataclasses import dataclass
from pathlib import Path
from herethere.everywhere.config import load_prefixed_env, prefixed_key
@dataclass(frozen=True)
class AIConfig:
"""OpenAI-compatible provider configuration for %%there ai."""
base_url: str
model: str
api_... | b3b/herethere | herethere/there/ai/config.py | .py | 76169e2963b577d4 | 7 | 0 |
"""Prompt sections for %%there ai."""
from collections.abc import Iterable
from dataclasses import dataclass, field
from importlib.resources import files
DEFAULT_AI_TEMPLATE_RESOURCE = "prompts/default.md"
FIX_AI_TEMPLATE_RESOURCE = "prompts/fix.md"
DEFAULT_AI_PROMPT = "default"
FIX_AI_PROMPT = "fix"
class AIPrompt... | b3b/herethere | herethere/there/ai/prompts.py | .py | e2816c7f1e244d44 | 7 | 0 |
"""herethere.there.commands.core"""
import re
import time
from collections.abc import Callable
from dataclasses import dataclass
from functools import wraps
from typing import TextIO
import click
from herethere.everywhere.loop import run_background, run_sync
from herethere.there.client import Client
from herethere.t... | b3b/herethere | herethere/there/commands/core.py | .py | b23b072448ea5255 | 7 | 0 |
"""History of executable %%there Python cells."""
import time
from collections import deque
from dataclasses import dataclass
@dataclass(frozen=True)
class RecentThereCell:
"""A recently executed remote Python %%there cell."""
line: str
cell: str
timestamp: float
class RecentThereHistory:
"""B... | b3b/herethere | herethere/there/history.py | .py | ee0223184c2feb4d | 7 | 0 |
"""Local-only %%there command registry."""
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
from herethere.there.history import RecentThereHistory
@dataclass(frozen=True)
class LocalThereCommand:
"""Input for a local-only %%there command."""
line: str
cell: ... | b3b/herethere | herethere/there/local_commands.py | .py | a6ee110e3b19163e | 7 | 0 |
"""herethere.there.output"""
from collections import deque
from ipywidgets import Output
class LimitedOutput(Output): # pylint: disable=abstract-method
"""Widget to capture and display stdout and stderr.
Output is limited by a `maxlen` number of lines."""
def __init__(self, maxlen: int, *args, **kwarg... | b3b/herethere | herethere/there/output.py | .py | 30d3cf16bacbe280 | 7 | 0 |
import datetime as DT
import matplotlib.pylab as plt
from numpy.linalg import norm
import numpy as np
import skyfield.api as sfapi
from skyfield.api import wgs84
import skyfield.sgp4lib as sgp4lib
#from mats_planningtool.OrbitSimulator import Geoidlib
from scipy.optimize import minimize_scalar
from skyfield.positionli... | innosat-mats/MATS-planningtool | src/mats_planningtool/OrbitSimulator/MatsBana.py | .py | 48314145c4996661 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
Searches a *Science Mode Timeline* .json file for a given date and returns the scheduled mode and its settings.
A part of the Operational Planning Tool.
"""
import ephem
import json
import os
def get_mode(Mode_Timeline, date):
for x in range(len(Mode_Timeline)):
"Skip if fir... | innosat-mats/MATS-planningtool | src/mats_planningtool/TimelineAnalyzer/Core.py | .py | 01dc0a8b2a377950 | 7 | 0 |
__all__ = ['as_actor', 'consumer']
from collections import Counter, deque
from collections.abc import Callable, Generator, Hashable, Iterable, Iterator
from contextlib import AbstractContextManager
from functools import update_wrapper
from threading import Lock
try:
from wrapt import BaseObjectProxy as ObjectProx... | arquolo/glow | src/glow/_coro.py | .py | 726a1e2517c30c9a | 7.15 | 1 |
"""IceCream - Never use print() to debug again.
Ansgar Grunseid
grunseid.com
grunseid@gmail.com
Pavel Maevskikh
arquolo@gmail.com
License: MIT
pip install asttokens colorama executing numpy pygments
"""
__all__ = ['ic', 'ic_repr']
import ast
import inspect
import pprint
import shutil
import sys
from collections.a... | arquolo/glow | src/glow/_ic.py | .py | 584f188fc52c490e | 7.15 | 1 |
__all__ = [
'circle',
'imhash_hist',
'imresize',
'imresize_categorical',
'imrotate',
]
from pathlib import Path
import cv2
import numpy as np
import numpy.typing as npt
from PIL.Image import Image
type _U8 = npt.NDArray[np.uint8]
type _F32 = npt.NDArray[np.float32]
type _AnyImage = Path | str | I... | arquolo/glow | src/glow/_imutil.py | .py | 6b87b487247415dc | 7.15 | 1 |
__all__ = ['make_key']
from collections.abc import Hashable
from dataclasses import dataclass
_KWD_MARK = object()
@dataclass(frozen=True, slots=True)
class _HashedSeq:
"""Memorizes hash to not recompute it on cache search/update."""
items: tuple
hashvalue: int
def __eq__(self, value: object) -> b... | arquolo/glow | src/glow/_keys.py | .py | 34fc703f6147bc44 | 7.15 | 1 |
"""Patch builtin `print` function to be thread-safe and `tqdm`-compatible."""
__all__ = ['apply']
import builtins
from functools import update_wrapper, wraps
from threading import RLock
from ._import_hook import register_post_import_hook
from ._types import SupportsWrite
_print = builtins.print
_lock = RLock()
@w... | arquolo/glow | src/glow/_patch_print.py | .py | 45aca962133ebd0f | 7.15 | 1 |
"""Fix for strange bug in SciPy on Anaconda for Windows.
See:
https://stackoverflow.com/questions/15457786/ctrl-c-crashes-python-after-importing-scipy-stats
Combines both:
.. [https://stackoverflow.com/a/39021051]
.. [https://stackoverflow.com/a/44822794]
"""
__all__ = ['apply']
import ctypes
import os
import sys
i... | arquolo/glow | src/glow/_patch_scipy.py | .py | d1a694aeaa966e8c | 7.15 | 1 |
__all__ = ['cumsum', 'maximum_cumsum']
from collections import deque
from itertools import accumulate
from ._types import Get, Pipe, Unary
class _Pipe[In, Out](Pipe):
def __init__(self, zero: In, push: Unary[In], pop: Get[Out]) -> None:
self._zero = zero
self._push = push
self._pop = pop... | arquolo/glow | src/glow/_pipes.py | .py | ca05ca6d6f0c1fef | 7.15 | 1 |
__all__ = ['countable', 'mangle', 'repr_as_obj', 'si', 'si_bin']
from collections import Counter
from typing import cast
try:
from wrapt import BaseObjectProxy as ObjectProxy # wrapt>=2.0
except ImportError:
from wrapt import ObjectProxy
from ._types import Unary
def mangle() -> Unary[str, str | None]:
... | arquolo/glow | src/glow/_repr.py | .py | d145c340370a195d | 7.15 | 1 |
__all__ = ['Reusable']
import asyncio
import weakref
from dataclasses import dataclass, field
from functools import partial
from threading import Thread
from ._cache import memoize
from ._types import Get, Unary
@memoize()
def make_loop() -> asyncio.AbstractEventLoop:
loop = asyncio.new_event_loop()
Thread(... | arquolo/glow | src/glow/_reusable.py | .py | 0daf7b0a332437fb | 7.15 | 1 |
__all__ = ['sizeof']
import ctypes
import functools
import sys
from collections.abc import Callable, Collection
from ctypes import pythonapi
from enum import Enum
from inspect import isgetsetdescriptor, ismemberdescriptor
from numbers import Number
from types import FunctionType, ModuleType
import numpy as np
from .... | arquolo/glow | src/glow/_sizeof.py | .py | 62a21840307e73d3 | 7.15 | 1 |
__all__ = ['streaming']
import asyncio
import concurrent.futures as cf
import inspect
import threading
from collections.abc import Iterable
from functools import partial, update_wrapper
from logging import getLogger
from queue import Empty, SimpleQueue
from threading import Thread
from time import monotonic, sleep
fro... | arquolo/glow | src/glow/_streaming.py | .py | 0607d14943ff6d6d | 7.15 | 1 |
__all__ = ['export', 'get_wild_imports', 'import_tree']
import pkgutil
import sys
from collections.abc import Callable
from types import ModuleType
class ExportError(Exception):
pass
def export[F: Callable](obj: F) -> F:
"""Expose obj to __all__ in module parent to where it was defined.
Intellisense c... | arquolo/glow | src/glow/api/exporting.py | .py | 2c28a5464ce7245d | 7.15 | 1 |
__all__ = ['Sound']
from contextlib import ExitStack
from dataclasses import dataclass
from datetime import timedelta
from pathlib import Path
from queue import Queue
from threading import Event
from typing import Self
import numpy as np
import numpy.typing as npt
from tqdm.auto import tqdm
from .. import chunked
fr... | arquolo/glow | src/glow/io/_sound.py | .py | c5b29d315088b69d | 7.15 | 1 |
#!/usr/bin/env python3
"""
Elevation window: drift a 32x16 window slowly across the world and show the
elevation of the captured rectangle on an RGB LED matrix.
Elevation comes straight from the local ETOPO1 GeoTIFF (no server needed).
If the rgbmatrix library isn't installed (i.e. you're on a laptop, not the Pi)
the ... | mwweinberg/elevation_grid | elevation_window.py | .py | f7670adbee4e7faf | 7 | 0 |
import os
from pathlib import Path
import stat
import tempfile
import torch
from torch import nn
from .distributed import _rank
__all__ = ["ModelSaver", "load_pretrained"]
def load_pretrained(
net: nn.Module,
path_or_state_dict: str | Path | dict,
weights_only=True,
strict=False,
) -> nn.Module:
... | lzcn/torchutils | torchutils/checkpoint.py | .py | f73dd16e09787af6 | 7.39 | 5 |
from collections.abc import Callable
import functools
import os
from typing import TypeVar
import torch.distributed as dist
F = TypeVar("F", bound=Callable)
__all__ = ["rank_zero_only"]
def _rank() -> int:
"""Current global rank: torch.distributed if initialized, else the RANK env var."""
if dist.is_initia... | lzcn/torchutils | torchutils/distributed.py | .py | 9b44cae53c171148 | 7.39 | 5 |
import os
from pathlib import Path
__all__ = ["scan_files"]
def scan_files(
path: str | Path = "./",
suffix: str | tuple = (),
recursive: bool = False,
relpath: bool = False,
) -> list[str]:
"""Scan files under a path, skipping hidden entries (e.g. .DS_Store).
Args:
path: Target dire... | lzcn/torchutils | torchutils/filesystem.py | .py | 6eea71904f257c20 | 7.39 | 5 |
"""Capture intermediate features and gradients via context-manager hooks.
Example::
import torchutils as tu
with tu.FeatureHook(model, ["layer2", "layer3"]) as features:
output = model(x)
with tu.GradHook(model, ["layer1"]) as grads:
output.sum().backward()
"""
import torch
import torch... | lzcn/torchutils | torchutils/hooks.py | .py | 289de9f9ad77f6bb | 7.39 | 5 |
"""Logging setup for PyTorch training, with rank-zero deduplication.
Example::
import torchutils as tu
tu.setup_logger(level="INFO", log_file="train.log")
logging.getLogger(__name__).info("Emitted only on rank 0")
"""
import logging
from .distributed import _rank
__all__ = ["setup_logger"]
_DEFAULT_F... | lzcn/torchutils | torchutils/logger.py | .py | 32e38407b03dc662 | 7.39 | 5 |
# encoding: utf-8
'''👥 EDRN Collaborative Groups: models.'''
from datetime import datetime, timezone, timedelta
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models import F, ExpressionWrapper, DateTimeField, DurationField
from django.http import HttpRequest
f... | EDRN/P5 | src/edrn.collabgroups/src/edrn/collabgroups/models.py | .py | c69c6bba758f7e03 | 7 | 0 |
# encoding: utf-8
'''👥 EDRN Collaborative Groups: tests for committees.'''
from edrn.collabgroups.models import Committee, CommitteeEvent
from eke.knowledge.utils import aware_now
from wagtail.models import Site as WagtailSite
from wagtail.test.utils import WagtailPageTestCase
from wagtail.test.utils.form_data impo... | EDRN/P5 | src/edrn.collabgroups/tests/test_committees.py | .py | 44b50c17f58fd78e | 7.5 | 0 |
# encoding: utf-8
'''📐 EDRN metrics: data quality reports instantition.'''
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from edrn.metrics.models import ReportIndex, generate_report
from wagtail.models import Site, PageViewRestriction
class Command(BaseCommand):
... | EDRN/P5 | src/edrn.metrics/src/edrn/metrics/management/commands/installdataqualityreports.py | .py | 7faf37a3227f0fa6 | 7 | 0 |
# encoding: utf-8
'''📐 EDRN metrics: views.'''
from edrn.auth.views import logged_in_or_basicauth
from django.http import HttpRequest, HttpResponse, HttpResponseServerError, HttpResponseRedirect, HttpResponseForbidden
from .models import ReportIndex, generate_report
def _get_referrer(request: HttpRequest) -> str:... | EDRN/P5 | src/edrn.metrics/src/edrn/metrics/views.py | .py | 7eceab9f5ea39df8 | 7 | 0 |
# encoding: utf-8
'''📐 EDRN Metrics: tests for the Django models.'''
from edrn.metrics.models import DataQualityReport, ReportIndex
from wagtail.models import Site as WagtailSite
from wagtail.test.utils import WagtailPageTestCase
from wagtail.test.utils.form_data import nested_form_data
class ReportIndexTest(Wagt... | EDRN/P5 | src/edrn.metrics/tests/test_models.py | .py | 89dd4c18580c286e | 7.5 | 0 |
# encoding: utf-8
'''📐 EDRN Metrics: tests for report generation.'''
from edrn.metrics.models import DataQualityReport, ReportIndex, generate_report
from wagtail.models import Site as WagtailSite
from wagtail.test.utils import WagtailPageTestCase
from wagtail.test.utils.form_data import nested_form_data
class Rep... | EDRN/P5 | src/edrn.metrics/tests/test_reports.py | .py | 2825a47aac690ec6 | 7.5 | 0 |
# encoding: utf-8
'''🎨 EDRN Theme: Django tags.'''
from django import template
from django.template.context import Context
from django.utils.safestring import mark_safe
from edrnsite.controls.models import Informatics
from edrnsite.controls.models import SocialMediaLink
from importlib import import_module
from wagta... | EDRN/P5 | src/edrn.theme/src/edrn/theme/templatetags/edrn_theme_tags.py | .py | a9c742051cd3a14e | 7 | 0 |
# encoding: utf-8
'''😌 EDRN Site Content: metadata collection form.'''
from .base_forms import (
AbstractEDRNForm, pi_site_choices, discipline_choices, data_category_choices, ALL_USERS_DN,
protocol_choices, organ_choices
)
from .base_models import AbstractFormPage
from django_recaptcha.fields import ReCaptch... | EDRN/P5 | src/edrnsite.content/src/edrnsite/content/_metadata_collection_form.py | .py | 9fb63db349a6233e | 7 | 0 |
# encoding: utf-8
'''😌 EDRN Site Content: Django forms.'''
from .base_forms import AbstractEDRNForm
from .base_models import AbstractFormPage
from .tasks import send_email
from django_recaptcha.fields import ReCaptchaField
from django import forms
from django.conf import settings
from django.db import models
from w... | EDRN/P5 | src/edrnsite.content/src/edrnsite/content/_spec_ref_set_form.py | .py | 9874eafffc32217f | 7.5 | 0 |
# -*- coding: utf-8 -*-
from .main import *
from ..merge.overall_stats import merge_overall_stats
@cli.group()
def merge():
"""
Merges logs and csv files.
"""
pass
@merge.command()
@click.argument(
"input_stats",
nargs = -1,
type = click.Path(exists = True))
@click.option('--out', '-o', ... | ribosomeprofiling/RFCommands | rfcommands/cli/merge.py | .py | 0c884af147b23add | 7.15 | 1 |
"""
Gym module implementing the Finnish social security including earnings-related components,
e.g., the unemployment benefit
"""
import math
import gymnasium as gym
from gymnasium import spaces, logger, utils, error
from gymnasium.utils import seeding
import numpy as np
from fin_benefits import BenefitsEK
from .unemp... | ajtanskanen/econogym | gym_unemployment/envs/unemployment_ek_v0.py | .py | 39b6ec71b3355b4a | 7.15 | 1 |
"""
Gym module implementing the Finnish social security including earnings-related components,
e.g., the unemployment benefit
"""
import math
import gymnasium as gym
from gymnasium import spaces, logger, utils, error
from gymnasium.utils import seeding
import numpy as np
#from .benefits import *
from fin_benefits impo... | ajtanskanen/econogym | gym_unemployment/envs/unemployment_ek_v1.py | .py | ced0a9f886e5ae9d | 7.15 | 1 |
"""
Gym module implementing the Finnish social security including earnings-related components,
e.g., the unemployment benefit
"""
import math
import gymnasium as gym
from gymnasium import spaces, logger, utils, error
from gymnasium.utils import seeding
import numpy as np
from fin_benefits import BenefitsEK
from .unemp... | ajtanskanen/econogym | gym_unemployment/envs/unemployment_long_v0.py | .py | 60da49bca187f58b | 7.15 | 1 |
"""
Gym module implementing the Finnish social security including earnings-related components,
e.g., the unemployment benefit
"""
import math
import gymnasium as gym
from gymnasium import spaces, logger, utils, error
from gymnasium.utils import seeding
import numpy as np
#from .benefits import *
from fin_benefits impo... | ajtanskanen/econogym | gym_unemployment/envs/unemployment_porrastus_v1.py | .py | 5a8b3aa9d9e0a4c9 | 7.15 | 1 |
'''
Util functions
'''
import math
def compare_q_print(q,q2,omat='omat_',puoliso='puoliso_'):
'''
Helper function that prettyprints arrays
'''
for key in q:
if key in q and key in q2:
if not math.isclose(q[key],q2[key]):
print(f'{key}: {q[key]:.2f} vs {q2[key]:.2f... | ajtanskanen/econogym | gym_unemployment/envs/util.py | .py | f0955b907e12a712 | 7.15 | 1 |
# -*- coding:utf-8 -*-
# @author xupingmao
# @since 2026/07/13
# @description 创建临时项目目录(data/project/日期_项目名),并开启一个位于该目录的 shell
import os
import sys
import argparse
import time
import typing
import subprocess
def get_project_root() -> str:
"""获取 duck_rush 项目的根目录"""
# 当前文件位于 duck_rush/<category>/<name>.py
r... | xupingmao/duck-rush | duck_rush/build-tools/duck-create-tmp-project.py | .py | c14b87bb5ad8daef | 7 | 0 |
#!/usr/local/bin/python3
# -*- coding:utf-8 -*-
# @author xupingmao
# @since 2021/04/18 17:00:00
# @modified 2021/04/18 17:04:08
# @filename config-shell-path.py
import os
import sys
import argparse
HOME_PATH = os.environ["HOME"]
def find_bash_profile_path():
bash_profile = os.path.join(HOME_PATH, ".bash_profil... | xupingmao/duck-rush | duck_rush/config/config-shell-path.py | .py | b4f4ce1a0000e592 | 7 | 0 |
# -*- coding:utf-8 -*-
'''
Author: xupingmao
email: 578749341@qq.com
Date: 2024-09-02 00:06:21
LastEditors: xupingmao
LastEditTime: 2024-09-02 00:16:04
FilePath: /duck_rush/duck_rush/datetime/duck-time.py
Description: 时间转换工具
- 时间戳(秒/毫秒) -> 日期字符串
- 日期字符串 -> 时间戳
- 相对时间(+10m/-10m/now) -> 时间戳
输入同时支持参数和... | xupingmao/duck-rush | duck_rush/datetime/duck-time.py | .py | ea9072da239942e3 | 7 | 0 |
# -*- coding: utf-8 -*-
"""duck-vocab(命令行生词本)单元测试。
直接运行: python duck_rush/dict/test_duck_vocab.py
通过 importlib 加载带连字符的脚本模块,用临时数据文件验证
add / update / remove(delete) / list 的核心逻辑,避免污染用户数据。
"""
import argparse
import importlib.util
import os
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abs... | xupingmao/duck-rush | duck_rush/dict/test_duck_vocab.py | .py | 5161ed5494843aab | 7.5 | 0 |
__doc__ = """
Convert a CSV stream/file to a JSONL stream/file.
默认从标准输入读取 CSV,向标准输出写入 JSONL,便于管道使用:
cat data.csv | duck-csv-to-json > data.jsonl
也可通过 -i/-o 指定文件:
duck-csv-to-json -i data.csv -o data.jsonl
"""
import csv
import json
import sys
import argparse
import typing
def csv_to_jsonl(in_stream, out_s... | xupingmao/duck-rush | duck_rush/document/duck-csv-to-json.py | .py | 4198a90fb0bd66ff | 7 | 0 |
__doc__ = """
将 JSONL 文件转换为 CSV 文件
"""
import json
import csv
import sys
import os
from typing import List, Dict, Any
def jsonl_to_csv(jsonl_file: str, csv_file: str) -> bool:
"""
将JSONL文件转换为CSV文件
:param jsonl_file: JSONL文件路径
:param csv_file: CSV文件路径
:return: 转换是否成功
"""
try:
# 读取J... | xupingmao/duck-rush | duck_rush/document/duck-json-to-csv.py | .py | 52de547d17fd5c54 | 7 | 0 |
# -*- coding:utf-8 -*-
# @author xupingmao <578749341@qq.com>
# @since 2020/02/25 12:34:29
# @modified 2020/03/02 12:20:17
import sys
import argparse
import os
import time
import traceback
import json
import shutil
import subprocess
from typing import List, Optional
# 本文件负责触发 install/upgrade, 可能在 duck_utils 尚未安装或版本过旧(... | xupingmao/duck-rush | duck_rush/duck.py | .py | 8f87acd928185654 | 7 | 0 |
# -*- coding: utf-8 -*-
# @since 2018/02/10
# @modified 2020/10/11 13:25:42
# @author xupingmao <578749341@qq.com>
import sublime, sublime_plugin
import time
import os
# Sublime Text 2 的插件路径
# ~/Library/Application Support/Sublime Text 2/Packages/User
PYTHON_DOC_TEMPLATE = """# -*- coding:utf-8 -*-
# @author xupingm... | xupingmao/duck-rush | duck_rush/editor/sublime-text/update-update-time.py | .py | 7b7ef9621c0f93f1 | 7 | 0 |
import struct
import base64
def encode_base32(data: bytes) -> str:
encoded = base64.b32hexencode(data).decode('ascii')
return encoded.rstrip('=') # 移除填充字符
def decode_base32(encoded: str) -> bytes:
# 添加缺失的填充字符
padding = '=' * ((8 - len(encoded) % 8) % 8)
return base64.b32hexdecode(encoded + paddi... | xupingmao/duck-rush | duck_rush/encode/duck-encode-int64.py | .py | 14fef7331cf20a6c | 7 | 0 |
#!/usr/local/bin/python3
# -*- coding:utf-8 -*-
# @author xupingmao
# @since 2021/10/07 00:14:39
# @modified 2021/10/07 00:43:40
# @filename delete-empty-dirs.py
import argparse
import os
def is_empty_dir(dirname):
return os.path.isdir(dirname) and len(os.listdir(dirname)) == 0
def delete_empty_dirs(dirname=".",... | xupingmao/duck-rush | duck_rush/fs/delete-empty-dirs.py | .py | fe52fc1e2d09a7ea | 7 | 0 |
#!/usr/local/bin/python3
# -*- coding:utf-8 -*-
# @author xupingmao
# @since 2021/10/07 00:14:39
# @modified 2021/10/07 00:43:40
# @filename delete-empty-dirs.py
import argparse
import os
def is_empty_file(fpath):
try:
st = os.stat(fpath)
return st.st_size == 0
except:
return False
de... | xupingmao/duck-rush | duck_rush/fs/delete-empty-files.py | .py | 81f40ca358ee68a6 | 7 | 0 |
# encoding=utf-8
import os
import io
import hashlib
import argparse
import sys
import re
import fnmatch
def _ensure_unix_newline_stdout():
"""Windows 下 Python 会把写到 stdout 的 \\n 翻译成 \\r\\n,
当通过管道传给 xargs 时,文件名尾部会带上 \\r,导致
`xargs grep` 报 `No such file or directory`。
这里强制 stdout 只输出 \\n,保证 `duck-find | ... | xupingmao/duck-rush | duck_rush/fs/duck-find.py | .py | 0faeaa8c5bc70051 | 7 | 0 |
"""The parametrised ``ClientTestCase`` harness for the respx-mocked tier.
Importable by any respx module that wants one body over both transports (see
specs/04-testing.md, invariant 5, including the single-transport exemption): one
test body runs against **both** transports, because ``__init_subclass__`` emits
``<Name... | polyswarm/polyswarm-api | test/_client_harness.py | .py | 8a274d38f8a7412f | 7.85 | 4 |
"""Shared, transport-agnostic helpers for the live e2e test suites.
These give every data-creating test a *deterministic-per-test, unique-per-test*
namespace so the suite is self-contained and parallel-safe:
* deterministic per test -> the request is reproducible, so a recorded VCR
cassette replays (the unit CI jo... | polyswarm/polyswarm-api | test/_e2e_helpers.py | .py | 48476f35e98979f1 | 7.85 | 4 |
import asyncio
import logging
import os
import time
import pytest
_VCR_DIR = os.path.join(os.path.dirname(__file__), "vcr")
# Test log verbosity, controllable per-run via the TESTS_LOG_LEVEL env var
# (default INFO). At INFO the suite emits the useful app request/response lines
# but not the DEBUG firehose that bloa... | polyswarm/polyswarm-api | test/conftest.py | .py | 1140a77003813640 | 7.85 | 4 |
"""The one arm of ``exists()``'s status mapping the e2e stack cannot produce.
Everything else about this endpoint is asserted against the **real server**, on resources the
tests provision themselves — ``test_hash_existence_probe_against_the_real_server`` and its async
twin cover ``200`` (present) and ``204`` (absent),... | polyswarm/polyswarm-api | test/exists_probe_mapping_test.py | .py | b39e998ee20ed5b7 | 7.85 | 4 |
"""Tests for BaseJsonResource.jmespath().
Exercises the helper against synthetic content — the helper just delegates to
jmespath.search(expr, self.json), so we don't need a real API response.
"""
from polyswarm_api.core import BaseJsonResource
from polyswarm_api.resources import MetadataMapping
def _resource(conten... | polyswarm/polyswarm-api | test/jmespath_test.py | .py | 8d62c44cff2e1af4 | 7.85 | 4 |
"""Pure-unit request-shape tests for the ``KnownGood`` resource builders.
No HTTP at all (the pure-unit tier — see specs/04-testing.md): these pin the
request *construction* — which fields ride in the JSON body vs the query
string, that unset optionals are omitted rather than sent as explicit nulls,
and that DELETE ca... | polyswarm/polyswarm-api | test/known_good_test.py | .py | 371b25d094625fb9 | 7.85 | 4 |
##
# File: task_functions.py
# Author: James Smith
# Date: 21-Feb-2025
##
"""
Workflow task descriptors.
"""
__docformat__ = "google en"
__author__ = "James Smith"
__email__ = "james.smith@rcsb.org"
__license__ = "Apache 2.0"
import multiprocessing
import os
import shutil
import tempfile
import logging
from e... | rcsb/py-rcsb_workflow | rcsb/workflow/bcif/task_functions.py | .py | 967efa33340972e2 | 7.3 | 3 |
##
# File: ChemCompFileWorkflow.py
# Date: 10-Mar-2020 jdw
#
# Workflow wrapper -- chemical component file conversion generator --
#
# Updates:
#
##
__docformat__ = "google en"
__author__ = "John Westbrook"
__email__ = "jwest@rcsb.rutgers.edu"
__license__ = "Apache 2.0"
import logging
import os
from rcsb.utils.c... | rcsb/py-rcsb_workflow | rcsb/workflow/chem/ChemCompFileWorkflow.py | .py | bc4587a34ff389c1 | 7.3 | 3 |
##
# File: ChemCompImageWorkflow.py
# Date: 10-Mar-2020 jdw
#
# Workflow wrapper -- chemical component image generation --
#
# Updates:
#
##
__docformat__ = "google en"
__author__ = "John Westbrook"
__email__ = "jwest@rcsb.rutgers.edu"
__license__ = "Apache 2.0"
import logging
import os
from rcsb.utils.chem.OeDe... | rcsb/py-rcsb_workflow | rcsb/workflow/chem/ChemCompImageWorkflow.py | .py | 7111ebb4d949ff75 | 7.3 | 3 |
##
# File: ChemCompIndexWorkflow.py
# Date: 2-Jun-2020 jdw
#
# Workflow wrapper -- generate chemical component and BIRD search indices --
#
# Updates:
# 10-Jun-2020 jdw Hookup to ChemCompSearchWrapper()
##
__docformat__ = "google en"
__author__ = "John Westbrook"
__email__ = "jwest@rcsb.rutgers.edu"
__license__ ... | rcsb/py-rcsb_workflow | rcsb/workflow/chem/ChemCompSearchIndexWorkflow.py | .py | a3cd304afdfa104a | 7.3 | 3 |
##
# File: ProteinTargetSequenceExecutionWorkflow.py
# Author: J. Westbrook
# Date: 25-Jun-2021
#
# Updates:
# 3-Mar-2023 Standard args passed into workflow
# 21-Mar-2023 Allow backing up Pharos-targets to stash, more __init__ improvement
# 5-May-2023 Pass in fromDbPharos and reloadPharos parameters to expo... | rcsb/py-rcsb_workflow | rcsb/workflow/targets/ProteinTargetSequenceExecutionWorkflow.py | .py | aff796362ffac2e7 | 7.3 | 3 |
##
# File: PdbxLoaderFixture.py
# Author: J. Westbrook
# Date: 4-Sep-2019
# Version: 0.001
#
# Updates:
# 04-Feb-2025 mjt Copied this file over from rcsb.exdb
##
"""
Fixture for loading the chemical reference and pdbx_core collections in a loca mongo instance.
"""
__docformat__ = "google en"
__author__ = "Joh... | rcsb/py-rcsb_workflow | rcsb/workflow/tests/fixturePdbxLoader.py | .py | b793484e95a89121 | 7.8 | 3 |
##
#
# File: ChemCompFileWorkflowTests.py
# Author: jdw
# Date: 10-Mar-2020
# Version: 0.001
#
# Updates:
##
"""
A collection of tests chemical component file generation workflows
"""
__docformat__ = "google en"
__author__ = "John Westbrook"
__email__ = "jwest@rcsb.rutgers.edu"
__license__ = "Creative Commons A... | rcsb/py-rcsb_workflow | rcsb/workflow/tests/testChemCompFileWorkflow.py | .py | 2b446566c716f403 | 7.8 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.