id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
14,956 | import argparse
import csv
import os.path as osp
from multiprocessing import Pool
import mmcv
from mmengine.config import Config
from mmengine.fileio import FileClient, dump
def get_metas_from_csv_style_ann_file(ann_file):
data_infos = []
cp_filename = None
with open(ann_file, 'r') as f:
reader = c... | null |
14,957 | import argparse
import csv
import os.path as osp
from multiprocessing import Pool
import mmcv
from mmengine.config import Config
from mmengine.fileio import FileClient, dump
def get_metas_from_txt_style_ann_file(ann_file):
with open(ann_file) as f:
lines = f.readlines()
i = 0
data_infos = []
wh... | null |
14,958 | import argparse
import csv
import os.path as osp
from multiprocessing import Pool
import mmcv
from mmengine.config import Config
from mmengine.fileio import FileClient, dump
def get_image_metas(data_info, img_prefix):
file_client = FileClient(backend='disk')
filename = data_info.get('filename', None)
if fi... | null |
14,959 | import argparse
import os
from mmengine import Config, DictAction
from mmdet.utils import replace_cfg_vals, update_data_root
def parse_args():
parser = argparse.ArgumentParser(description='Print the whole config')
parser.add_argument('config', help='config file path')
parser.add_argument(
'--save-p... | null |
14,960 | import argparse
import os.path as osp
import numpy as np
from mmengine.fileio import dump, load
from mmengine.utils import mkdir_or_exist, track_parallel_progress
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'--data-root',
type=str,
help='The data root of co... | null |
14,961 | import argparse
import os.path as osp
import numpy as np
from mmengine.fileio import dump, load
from mmengine.utils import mkdir_or_exist, track_parallel_progress
def split_coco(data_root, out_dir, percent, fold):
def multi_wrapper(args):
return split_coco(*args) | null |
14,962 | from argparse import ArgumentParser, Namespace
from pathlib import Path
from tempfile import TemporaryDirectory
from mmengine.config import Config
from mmengine.utils import mkdir_or_exist
The provided code snippet includes necessary dependencies for implementing the `mmdet2torchserve` function. Write a Python functio... | Converts MMDetection model (config + checkpoint) to TorchServe `.mar`. Args: config_file: In MMDetection config format. The contents vary for each task repository. checkpoint_file: In MMDetection checkpoint format. The contents vary for each task repository. output_folder: Folder where `{model_name}.mar` will be create... |
14,963 | from argparse import ArgumentParser, Namespace
from pathlib import Path
from tempfile import TemporaryDirectory
from mmengine.config import Config
from mmengine.utils import mkdir_or_exist
def parse_args():
parser = ArgumentParser(
description='Convert MMDetection models to TorchServe `.mar` format.')
... | null |
14,964 | import json
import multiprocessing
import os
import sys
from itertools import product
from math import ceil
import cv2
import numpy as np
class PatchGenerator(object):
def __init__(self, info, type='normal', data_dir='/home/liwenxi/panda/raw/PANDA/image_train',
save_img_path='/home/liwenxi/pan... | null |
14,965 | import json
import multiprocessing
import os
import sys
from itertools import product
from math import ceil
import cv2
import numpy as np
class PatchGenerator(object):
def __init__(self, info, type='normal', data_dir='/home/liwenxi/panda/raw/PANDA/image_train',
save_img_path='/home/liwenxi/panda/ra... | null |
14,966 | import warnings
from pathlib import Path
from typing import Optional, Sequence, Union
import numpy as np
import torch
import torch.nn as nn
from mmcv.ops import RoIPool
from mmcv.transforms import Compose
from mmengine.config import Config
from mmengine.runner import load_checkpoint
from mmdet.evaluation import get_cla... | Initialize a detector from config file. Args: config (str, :obj:`Path`, or :obj:`mmengine.Config`): Config file path, :obj:`Path`, or the config object. checkpoint (str, optional): Checkpoint path. If left as None, the model will not load any weights. palette (str): Color palette used for visualization. If palette is s... |
14,967 | import warnings
from pathlib import Path
from typing import Optional, Sequence, Union
import numpy as np
import torch
import torch.nn as nn
from mmcv.ops import RoIPool
from mmcv.transforms import Compose
from mmengine.config import Config
from mmengine.runner import load_checkpoint
from mmdet.evaluation import get_cla... | Inference image(s) with the detector. Args: model (nn.Module): The loaded detector. imgs (str, ndarray, Sequence[str/ndarray]): Either image files or loaded images. test_pipeline (:obj:`Compose`): Test pipeline. Returns: :obj:`DetDataSample` or list[:obj:`DetDataSample`]: If imgs is a list or tuple, the same length lis... |
14,968 | import warnings
from pathlib import Path
from typing import Optional, Sequence, Union
import numpy as np
import torch
import torch.nn as nn
from mmcv.ops import RoIPool
from mmcv.transforms import Compose
from mmengine.config import Config
from mmengine.runner import load_checkpoint
from mmdet.evaluation import get_cla... | Async inference image(s) with the detector. Args: model (nn.Module): The loaded detector. img (str | ndarray): Either image files or loaded images. Returns: Awaitable detection results. |
14,969 | import os
import torch
import torch.distributed as dist
def load_checkpoint(config, model, optimizer, lr_scheduler, logger):
logger.info(f"==============> Resuming form {config.MODEL.RESUME}....................")
if config.MODEL.RESUME.startswith('https'):
checkpoint = torch.hub.load_state_dict_from_ur... | null |
14,970 | import os
import torch
import torch.distributed as dist
def load_pretrained(config, model, logger):
logger.info(f"==============> Loading weight {config.MODEL.PRETRAINED} for fine-tuning......")
checkpoint = torch.load(config.MODEL.PRETRAINED, map_location='cpu')
state_dict = checkpoint['model']
# del... | null |
14,971 | import os
import torch
import torch.distributed as dist
def save_checkpoint(config, epoch, model, max_accuracy, optimizer, lr_scheduler, logger):
save_state = {'model': model.state_dict(),
'optimizer': optimizer.state_dict(),
'lr_scheduler': lr_scheduler.state_dict(),
... | null |
14,972 | import os
import torch
import torch.distributed as dist
def auto_resume_helper(output_dir):
checkpoints = os.listdir(output_dir)
checkpoints = [ckpt for ckpt in checkpoints if ckpt.endswith('pth')]
print(f"All checkpoints founded in {output_dir}: {checkpoints}")
if len(checkpoints) > 0:
latest_... | null |
14,973 | import os
import time
import random
import argparse
import datetime
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils import accuracy, AverageMeter
from config import get_config
f... | null |
14,974 | import os
import time
import random
import argparse
import datetime
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils import accuracy, AverageMeter
from config import get_config
f... | null |
14,975 | import os
import time
import random
import argparse
import datetime
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils import accuracy, AverageMeter
from config import get_config
f... | null |
14,976 | import os
import time
import random
import argparse
import datetime
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils import accuracy, AverageMeter
from config import get_config
f... | null |
14,977 | import glob
import os
import shutil
import time
import random
import argparse
import datetime
import PIL.Image
import cv2
import matplotlib.pyplot as plt
import matplotlib.cm as CM
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import tqdm
from timm.loss import Lab... | null |
14,978 | import glob
import os
import shutil
import time
import random
import argparse
import datetime
import PIL.Image
import cv2
import matplotlib.pyplot as plt
import matplotlib.cm as CM
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import tqdm
from timm.loss import Lab... | null |
14,979 | import glob
import os
import shutil
import time
import random
import argparse
import datetime
import PIL.Image
import cv2
import matplotlib.pyplot as plt
import matplotlib.cm as CM
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import tqdm
from timm.loss import Lab... | null |
14,980 | import io
import os
import time
import torch.distributed as dist
import torch.utils.data as data
from PIL import Image
from .zipreader import is_zip_path, ZipReader
def find_classes(dir):
classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
classes.sort()
class_to_idx = {classes[i]... | null |
14,981 | import io
import os
import time
import torch.distributed as dist
import torch.utils.data as data
from PIL import Image
from .zipreader import is_zip_path, ZipReader
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
... | null |
14,982 | import io
import os
import time
import torch.distributed as dist
import torch.utils.data as data
from PIL import Image
from .zipreader import is_zip_path, ZipReader
def make_dataset_with_ann(ann_file, img_prefix, extensions):
images = []
with open(ann_file, "r") as f:
contents = f.readlines()
f... | null |
14,983 | import io
import os
import time
import torch.distributed as dist
import torch.utils.data as data
from PIL import Image
from .zipreader import is_zip_path, ZipReader
def pil_loader(path):
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
if isinstance(path, bytes):... | null |
14,984 | import os
import torch
import numpy as np
import torch.distributed as dist
from torchvision import datasets, transforms
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.data import Mixup
from timm.data import create_transform
from .cached_image_folder import CachedImageFolder
from .... | null |
14,985 | import torch
from timm.scheduler.cosine_lr import CosineLRScheduler
from timm.scheduler.step_lr import StepLRScheduler
from timm.scheduler.scheduler import Scheduler
class LinearLRScheduler(Scheduler):
def __init__(self,
optimizer: torch.optim.Optimizer,
t_initial: int,
... | null |
14,986 | import glob
import os.path
import PIL.Image as Image
import tqdm
import multiprocessing
import time
def run_mp(img_path, dst_path):
img = Image.open(img_path)
img = img.crop((48, 48, 720, 720))
img.save(dst_path)
def deamon_thread(q):
print("I love work!")
while not q.empty():
img_path, dst... | null |
14,987 | import glob
import os
import shutil
import time
import random
import argparse
import datetime
import PIL.Image
import cv2
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import tqdm
from timm.loss import LabelSmoothingCrossEntropy, So... | null |
14,988 | from torch import optim as optim
def set_weight_decay(model, skip_list=(), skip_keywords=()):
has_decay = []
no_decay = []
for name, param in model.named_parameters():
if not param.requires_grad:
continue # frozen weights
if len(param.shape) == 1 or name.endswith(".bias") or (na... | Build optimizer, set weight decay of normalization to 0 by default. |
14,989 | import glob
import os
import shutil
import time
import random
import argparse
import datetime
import PIL.Image
import cv2
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import tqdm
from timm.loss import LabelSmoothingCrossEntropy, So... | null |
14,990 | import glob
import os
import tqdm
import PIL.ImageFile
import PIL.Image
import multiprocessing
import time
def deamon_thread(q):
print("I love work!")
while not q.empty():
img_path = q.get()
name = os.path.basename(img_path)
if 'test' not in img_path:
continue
print(... | null |
14,991 | import os
import sys
import logging
import functools
from termcolor import colored
def create_logger(output_dir, dist_rank=0, name=''):
# create logger
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
logger.propagate = False
# create formatter
fmt = '[%(asctime)s %(name)s] (%(f... | null |
14,994 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
import numpy as np
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
import torchvision.models as models
The provided code snippet includes necessary dependencies for implementing the `window_... | Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) |
14,995 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
import numpy as np
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
import torchvision.models as models
The provided code snippet includes necessary dependencies for implementing the `window_... | Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) |
14,996 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
The provided code snippet includes necessary dependencies for implementing the `window_partition` function. Write a Python function `def windo... | Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) |
14,997 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
The provided code snippet includes necessary dependencies for implementing the `window_reverse` function. Write a Python function `def window_... | Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) |
15,000 | from .swin_transformer import SwinTransformer
from .swin_mlp import SwinMLP
from .swin_transformer_v2 import SwinTransformerV2
from .swin_transformer_resnet import SwinTransformerRes
class SwinTransformer(nn.Module):
""" Swin Transformer backbone.
A PyTorch impl of : `Swin Transformer: Hierarchical Vision ... | null |
15,002 | from __future__ import annotations
import asyncio
import msgspec
from typing import Any
The provided code snippet includes necessary dependencies for implementing the `prefixed_send` function. Write a Python function `async def prefixed_send(stream: asyncio.StreamWriter, buffer: bytes) -> None` to solve the following ... | Write a length-prefixed buffer to the stream |
15,003 | from __future__ import annotations
import asyncio
import msgspec
from typing import Any
The provided code snippet includes necessary dependencies for implementing the `prefixed_recv` function. Write a Python function `async def prefixed_recv(stream: asyncio.StreamReader) -> bytes` to solve the following problem:
Read ... | Read a length-prefixed buffer from the stream |
15,004 | import json
import time
import orjson
import requests
import simdjson
import ujson
import msgspec
def query_msgspec(data: bytes) -> list[tuple[int, str]]:
# Use Struct types to define the JSON schema. For efficiency we only define
# the fields we actually need.
class Package(msgspec.Struct):
name: ... | null |
15,005 | import json
import time
import orjson
import requests
import simdjson
import ujson
import msgspec
def query_orjson(data: bytes) -> list[tuple[int, str]]:
repo_data = orjson.loads(data)
return sorted(
((p["size"], p["name"]) for p in repo_data["packages"].values()), reverse=True
)[:10] | null |
15,006 | import json
import time
import orjson
import requests
import simdjson
import ujson
import msgspec
def query_json(data: bytes) -> list[tuple[int, str]]:
repo_data = json.loads(data)
return sorted(
((p["size"], p["name"]) for p in repo_data["packages"].values()), reverse=True
)[:10] | null |
15,007 | import json
import time
import orjson
import requests
import simdjson
import ujson
import msgspec
def query_ujson(data: bytes) -> list[tuple[int, str]]:
repo_data = ujson.loads(data)
return sorted(
((p["size"], p["name"]) for p in repo_data["packages"].values()), reverse=True
)[:10] | null |
15,008 | import json
import time
import orjson
import requests
import simdjson
import ujson
import msgspec
def query_simdjson(data: bytes) -> list[tuple[int, str]]:
repo_data = simdjson.Parser().parse(data)
return sorted(
((p["size"], p["name"]) for p in repo_data["packages"].values()), reverse=True
)[:10] | null |
15,009 | from typing import Any
import msgspec
class PyProject(Base):
build_system: BuildSystem | None = None
project: Project | None = None
tool: dict[str, dict[str, Any]] = {}
The provided code snippet includes necessary dependencies for implementing the `decode` function. Write a Python function `def decode(data... | Decode a ``pyproject.toml`` file from TOML |
15,010 | from typing import Any
import msgspec
class PyProject(Base):
build_system: BuildSystem | None = None
project: Project | None = None
tool: dict[str, dict[str, Any]] = {}
The provided code snippet includes necessary dependencies for implementing the `encode` function. Write a Python function `def encode(msg:... | Encode a ``PyProject`` object to TOML |
15,011 | from time import perf_counter
def bench(name, template):
N_classes = 100
source = "\n".join(template.format(n=i) for i in range(N_classes))
code_obj = compile(source, "__main__", "exec")
# Benchmark defining new types
N = 200
start = perf_counter()
for _ in range(N):
ns = {}
... | null |
15,012 | from time import perf_counter
def format_table(results):
columns = (
"",
"import (μs)",
"create (μs)",
"equality (μs)",
"order (μs)",
)
def f(n):
return "N/A" if n is None else f"{n:.2f}"
rows = []
for name, *times in results:
rows.append((f... | null |
15,013 | import gc
import sys
import time
import msgspec
def sizeof(x, _seen=None):
"""Get the recursive sizeof for an object (memoized).
Not generic, works on types used in this benchmark.
"""
if _seen is None:
_seen = set()
_id = id(x)
if _id in _seen:
return 0
_seen.add(_id)
si... | null |
15,014 | import gc
import sys
import time
import msgspec
def format_table(results):
columns = ("", "GC time (ms)", "Memory Used (MiB)")
rows = []
for name, t, mem in results:
rows.append((f"**{name}**", f"{t:.2f}", f"{mem:.2f}"))
widths = tuple(max(max(map(len, x)), len(c)) for x, c in zip(zip(*rows),... | null |
15,015 | from __future__ import annotations
import enum
import dataclasses
import datetime
from typing import Literal
from mashumaro.mixins.orjson import DataClassORJSONMixin
def encode(x):
return x.to_json() | null |
15,016 | from __future__ import annotations
import enum
import dataclasses
import datetime
from typing import Literal
from mashumaro.mixins.orjson import DataClassORJSONMixin
class Directory(DataClassORJSONMixin):
def decode(msg):
return Directory.from_json(msg) | null |
15,017 | import argparse
import json
import tempfile
from ..generate_data import make_filesystem_data
import sys
import subprocess
LIBRARIES = ["msgspec", "mashumaro", "cattrs", "pydantic"]
def parse_list(value):
libs = [lib.strip() for lib in value.split(",")]
for lib in libs:
if lib not in LIBRARIES:
... | null |
15,018 | from __future__ import annotations
import enum
import datetime
from typing import Literal
import attrs
import cattrs.preconf.orjson
converter = cattrs.preconf.orjson.make_converter(omit_if_default=True)
def encode(obj):
return converter.dumps(obj) | null |
15,019 | from __future__ import annotations
import enum
import datetime
from typing import Literal
import attrs
import cattrs.preconf.orjson
class Directory:
name: str
created_by: str
created_at: datetime.datetime
updated_by: str | None = None
updated_at: datetime.datetime | None = None
contents: list[Fi... | null |
15,020 | from __future__ import annotations
import enum
import datetime
from typing import Literal, Annotated
import pydantic
def encode(obj):
return obj.model_dump_json(exclude_defaults=True) | null |
15,021 | from __future__ import annotations
import enum
import datetime
from typing import Literal, Annotated
import pydantic
class Directory(pydantic.BaseModel):
type: Literal["directory"] = "directory"
name: str
created_by: str
created_at: datetime.datetime
updated_by: str | None = None
updated_at: dat... | null |
15,022 | from __future__ import annotations
import enum
import datetime
from typing import Literal, Annotated
import pydantic
def encode(obj):
return obj.json(exclude_defaults=True) | null |
15,023 | from __future__ import annotations
import enum
import datetime
from typing import Literal, Annotated
import pydantic
class Directory(pydantic.BaseModel):
type: Literal["directory"] = "directory"
name: str
created_by: str
created_at: datetime.datetime
updated_by: str | None = None
updated_at: dat... | null |
15,024 | import io
import zipfile
import requests
The provided code snippet includes necessary dependencies for implementing the `get_latest_noarch_wheel_size` function. Write a Python function `def get_latest_noarch_wheel_size(library)` to solve the following problem:
Get the total uncompressed size of the latest noarch wheel... | Get the total uncompressed size of the latest noarch wheel |
15,025 | import io
import zipfile
import requests
The provided code snippet includes necessary dependencies for implementing the `get_latest_manylinux_wheel_size` function. Write a Python function `def get_latest_manylinux_wheel_size(library)` to solve the following problem:
Get the total uncompressed size of the latest Python... | Get the total uncompressed size of the latest Python 3.10 manylinux x86_64 wheel for the library |
15,026 | from __future__ import annotations
import sys
import dataclasses
import json
import timeit
import importlib.metadata
from typing import Any, Literal, Callable
from .generate_data import make_filesystem_data
import msgspec
class Directory(msgspec.Struct, kw_only=True, omit_defaults=True, tag="directory"):
name: str
... | null |
15,027 | from __future__ import annotations
import sys
import dataclasses
import json
import timeit
import importlib.metadata
from typing import Any, Literal, Callable
from .generate_data import make_filesystem_data
import msgspec
class Directory(msgspec.Struct, kw_only=True, omit_defaults=True, tag="directory"):
class Benchmar... | null |
15,028 | import datetime
import random
import string
class Generator:
UTC = datetime.timezone.utc
DATE_2018 = datetime.datetime(2018, 1, 1, tzinfo=UTC)
DATE_2023 = datetime.datetime(2023, 1, 1, tzinfo=UTC)
PERMISSIONS = ["READ", "WRITE", "READ_WRITE"]
NAMES = [
"alice",
"ben",
"carol"... | null |
15,029 | import collections
import sys
import typing
def get_type_hints(obj):
return _get_type_hints(obj, include_extras=True) | null |
15,030 | import collections
import sys
import typing
if Required is None and _AnnotatedAlias is None:
# No extras available, so no `include_extras`
get_type_hints = _get_type_hints
else:
def get_class_annotations(obj):
def get_typeddict_info(obj):
if isinstance(obj, type):
cls = obj
else:
cls = ... | null |
15,031 | import collections
import sys
import typing
def get_class_annotations(obj):
"""Get the annotations for a class.
This is similar to ``typing.get_type_hints``, except:
- We maintain it
- It leaves extras like ``Annotated``/``ClassVar`` alone
- It resolves any parametrized generics in the class mro. Th... | null |
15,032 | import collections
import sys
import typing
The provided code snippet includes necessary dependencies for implementing the `rebuild` function. Write a Python function `def rebuild(cls, kwargs)` to solve the following problem:
Used to unpickle Structs with keyword-only fields
Here is the function:
def rebuild(cls, kw... | Used to unpickle Structs with keyword-only fields |
15,033 | import errno
import os
import re
import subprocess
import sys
HANDLERS = {}
The provided code snippet includes necessary dependencies for implementing the `register_vcs_handler` function. Write a Python function `def register_vcs_handler(vcs, method)` to solve the following problem:
Create decorator to mark a method a... | Create decorator to mark a method as the handler of a VCS. |
15,034 | import errno
import os
import re
import subprocess
import sys
The provided code snippet includes necessary dependencies for implementing the `run_command` function. Write a Python function `def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None)` to solve the following problem:
Call the g... | Call the given command(s). |
15,035 | import errno
import os
import re
import subprocess
import sys
The provided code snippet includes necessary dependencies for implementing the `git_get_keywords` function. Write a Python function `def git_get_keywords(versionfile_abs)` to solve the following problem:
Extract version information from the given file.
Her... | Extract version information from the given file. |
15,036 | import errno
import os
import re
import subprocess
import sys
def get_keywords():
"""Get the keywords needed to look up the version information."""
# these strings will be replaced by git during git-archive.
# setup.py/versioneer.py will grep for the variable names, so they must
# each be defined on a l... | Get version information or return default if unable to do so. |
15,037 | import datetime as _datetime
from typing import Any, Callable, Optional, Type, TypeVar, Union, overload, Literal
from . import (
DecodeError as _DecodeError,
convert as _convert,
to_builtins as _to_builtins,
)
__all__ = ("encode", "decode")
def __dir__():
return __all__ | null |
15,038 | import datetime as _datetime
from typing import Any, Callable, Optional, Type, TypeVar, Union, overload, Literal
from . import (
DecodeError as _DecodeError,
convert as _convert,
to_builtins as _to_builtins,
)
def _import_tomli_w():
try:
import tomli_w # type: ignore
return tomli_w
... | Serialize an object as TOML. Parameters ---------- obj : Any The object to serialize. enc_hook : callable, optional A callable to call for objects that aren't supported msgspec types. Takes the unsupported object and should return a supported object, or raise a ``NotImplementedError`` if unsupported. order : {None, 'de... |
15,039 | import datetime as _datetime
from typing import Any, Callable, Optional, Type, TypeVar, Union, overload, Literal
from . import (
DecodeError as _DecodeError,
convert as _convert,
to_builtins as _to_builtins,
)
def decode(
buf: Union[bytes, str],
*,
strict: bool = True,
dec_hook: Optional[Ca... | null |
15,040 | import datetime as _datetime
from typing import Any, Callable, Optional, Type, TypeVar, Union, overload, Literal
from . import (
DecodeError as _DecodeError,
convert as _convert,
to_builtins as _to_builtins,
)
T = TypeVar("T")
def decode(
buf: Union[bytes, str],
*,
type: Type[T] = ...,
stri... | null |
15,041 | import datetime as _datetime
from typing import Any, Callable, Optional, Type, TypeVar, Union, overload, Literal
from . import (
DecodeError as _DecodeError,
convert as _convert,
to_builtins as _to_builtins,
)
def decode(
buf: Union[bytes, str],
*,
type: Any = ...,
strict: bool = True,
... | null |
15,042 | import datetime as _datetime
from typing import Any, Callable, Optional, Type, TypeVar, Union, overload, Literal
from . import (
DecodeError as _DecodeError,
convert as _convert,
to_builtins as _to_builtins,
)
def _import_tomllib():
try:
import tomllib # type: ignore
return tomllib
... | Deserialize an object from TOML. Parameters ---------- buf : bytes-like or str The message to decode. type : type, optional A Python type (in type annotation form) to decode the object as. If provided, the message will be type checked and decoded as the specified type. Defaults to `Any`, in which case the message will ... |
15,043 | from __future__ import annotations
from typing import Any
from . import NODEFAULT, Struct, field
from ._core import ( # noqa
Factory as _Factory,
StructConfig,
asdict,
astuple,
replace,
force_setattr,
)
from ._utils import get_class_annotations as _get_class_annotations
__all__ = (
"FieldIn... | null |
15,044 | from __future__ import annotations
from typing import Any
from . import NODEFAULT, Struct, field
from ._core import ( # noqa
Factory as _Factory,
StructConfig,
asdict,
astuple,
replace,
force_setattr,
)
from ._utils import get_class_annotations as _get_class_annotations
class FieldInfo(Struct):... | Get information about the fields in a Struct. Parameters ---------- type_or_instance: A struct type or instance. Returns ------- tuple[FieldInfo] |
15,047 | from __future__ import annotations
import re
import textwrap
from collections.abc import Iterable
from typing import Any, Optional, Callable
from . import inspect as mi, to_builtins
def schema_components(
types: Iterable[Any],
*,
schema_hook: Optional[Callable[[type], dict[str, Any]]] = None,
ref_templa... | Generate a JSON Schema for a given type. Any schemas for (potentially) shared components are extracted and stored in a top-level ``"$defs"`` field. If you want to generate schemas for multiple types, or to have more control over the generated schema you may want to use ``schema_components`` instead. Parameters --------... |
15,048 | from __future__ import annotations
import re
import textwrap
from collections.abc import Iterable
from typing import Any, Optional, Callable
from . import inspect as mi, to_builtins
def _get_doc(t: mi.Type) -> str:
assert hasattr(t, "cls")
cls = getattr(t.cls, "__origin__", t.cls)
doc = getattr(cls, "__doc... | null |
15,049 | from __future__ import annotations
import datetime
import decimal
import enum
import uuid
from collections.abc import Iterable
from typing import (
Any,
Final,
Literal,
Tuple,
Type as typing_Type,
TypeVar,
Union,
)
import msgspec
from msgspec import NODEFAULT, UNSET, UnsetType as _UnsetType
... | null |
15,050 | from __future__ import annotations
import datetime
import decimal
import enum
import uuid
from collections.abc import Iterable
from typing import (
Any,
Final,
Literal,
Tuple,
Type as typing_Type,
TypeVar,
Union,
)
import msgspec
from msgspec import NODEFAULT, UNSET, UnsetType as _UnsetType
... | Get information about a msgspec-compatible type. Note that if you need to inspect multiple types it's more efficient to call `multi_type_info` once with a sequence of types than calling `type_info` multiple times. Parameters ---------- type: type The type to get info about. Returns ------- Type Examples -------- >>> ms... |
15,051 | from __future__ import annotations
import datetime
import decimal
import enum
import uuid
from collections.abc import Iterable
from typing import (
Any,
Final,
Literal,
Tuple,
Type as typing_Type,
TypeVar,
Union,
)
import msgspec
from msgspec import NODEFAULT, UNSET, UnsetType as _UnsetType
... | null |
15,052 | from __future__ import annotations
import datetime
import decimal
import enum
import uuid
from collections.abc import Iterable
from typing import (
Any,
Final,
Literal,
Tuple,
Type as typing_Type,
TypeVar,
Union,
)
import msgspec
from msgspec import NODEFAULT, UNSET, UnsetType as _UnsetType
... | null |
15,053 | from __future__ import annotations
import datetime
import decimal
import enum
import uuid
from collections.abc import Iterable
from typing import (
Any,
Final,
Literal,
Tuple,
Type as typing_Type,
TypeVar,
Union,
)
import msgspec
from msgspec import NODEFAULT, UNSET, UnsetType as _UnsetType
... | null |
15,054 | from __future__ import annotations
import datetime
import decimal
import enum
import uuid
from collections.abc import Iterable
from typing import (
Any,
Final,
Literal,
Tuple,
Type as typing_Type,
TypeVar,
Union,
)
import msgspec
from msgspec import NODEFAULT, UNSET, UnsetType as _UnsetType
... | null |
15,055 | from __future__ import annotations
import datetime
import decimal
import enum
import uuid
from collections.abc import Iterable
from typing import (
Any,
Final,
Literal,
Tuple,
Type as typing_Type,
TypeVar,
Union,
)
import msgspec
from msgspec import NODEFAULT, UNSET, UnsetType as _UnsetType
... | null |
15,056 | from __future__ import annotations
import datetime
import decimal
import enum
import uuid
from collections.abc import Iterable
from typing import (
Any,
Final,
Literal,
Tuple,
Type as typing_Type,
TypeVar,
Union,
)
import msgspec
from msgspec import NODEFAULT, UNSET, UnsetType as _UnsetType
... | null |
15,057 | from __future__ import annotations
import datetime
import decimal
import enum
import uuid
from collections.abc import Iterable
from typing import (
Any,
Final,
Literal,
Tuple,
Type as typing_Type,
TypeVar,
Union,
)
import msgspec
from msgspec import NODEFAULT, UNSET, UnsetType as _UnsetType
... | null |
15,058 | from __future__ import annotations
import datetime
import decimal
import enum
import uuid
from collections.abc import Iterable
from typing import (
Any,
Final,
Literal,
Tuple,
Type as typing_Type,
TypeVar,
Union,
)
import msgspec
from msgspec import NODEFAULT, UNSET, UnsetType as _UnsetType
... | null |
15,060 | import datetime as _datetime
from typing import Any, Callable, Optional, Type, TypeVar, Union, overload, Literal
from . import (
DecodeError as _DecodeError,
convert as _convert,
to_builtins as _to_builtins,
)
def _import_pyyaml(name):
try:
import yaml # type: ignore
except ImportError:
... | Serialize an object as YAML. Parameters ---------- obj : Any The object to serialize. enc_hook : callable, optional A callable to call for objects that aren't supported msgspec types. Takes the unsupported object and should return a supported object, or raise a ``NotImplementedError`` if unsupported. order : {None, 'de... |
15,064 | import datetime as _datetime
from typing import Any, Callable, Optional, Type, TypeVar, Union, overload, Literal
from . import (
DecodeError as _DecodeError,
convert as _convert,
to_builtins as _to_builtins,
)
def _import_pyyaml(name):
try:
import yaml # type: ignore
except ImportError:
... | Deserialize an object from YAML. Parameters ---------- buf : bytes-like or str The message to decode. type : type, optional A Python type (in type annotation form) to decode the object as. If provided, the message will be type checked and decoded as the specified type. Defaults to `Any`, in which case the message will ... |
15,065 | import math
import os
import textwrap
n_shifts, shifts, n_powers, powers = gen_hpd_tables()
def gen_hpd_tables():
log2log10 = math.log(2) / math.log(10)
shifts = ["0x0000"]
powers = []
for i in range(1, 61):
offset = len(powers)
assert offset <= 0x07FF
num_new_digits = int(log2l... | null |
15,066 | import math
import os
import textwrap
def gen_row(e):
z = 1 << 2048
if e >= 0:
exp = 10**e
z = z * exp
else:
exp = 10 ** (-e)
z = z // exp
n = -2048
while z >= (1 << 128):
z = z >> 1
n += 1
h = hex(z)[2:]
assert len(h) == 32
approx_n =... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.