repo_name stringlengths 7 71 | file_path stringlengths 5 118 | context list | import_statement stringlengths 45 12.5k | token_num int64 641 99.4k | cropped_code stringlengths 44 17k | all_code stringlengths 43 754k | next_line stringlengths 2 330 | gold_snippet_index int64 0 68 | created_at stringlengths 25 25 | level stringclasses 9
values |
|---|---|---|---|---|---|---|---|---|---|---|
zju3dv/nr_in_a_room | optim/patch_perceptual.py | [
{
"identifier": "perceptual_model",
"path": "models/perceptual_model.py",
"snippet": "class VGG16_for_Perceptual(nn.Module):\nclass CLIP_for_Perceptual(nn.Module):\n def __init__(self, requires_grad=False, n_layers=[2, 4, 14, 21]):\n def forward(self, x):\n def perceptual_loss(\n self,\n... | import torch
import numpy as np
import cv2
from models import perceptual_model
from models.perceptual_model import get_perceptual_loss, VGG16_for_Perceptual
from typing import List, Optional, Any, Dict, Union | 1,380 |
# import lpips
# loss_fn_vgg = lpips.LPIPS(net="vgg").cuda()
def get_mask_bbox(mask):
# crop image
true_indices = np.nonzero(mask)
min_h, min_w = np.min(true_indices[0]), np.min(true_indices[1])
max_h, max_w = np.max(true_indices[0]), np.max(true_indices[1])
# print(min_h, min_w)
# print(max... |
# import lpips
# loss_fn_vgg = lpips.LPIPS(net="vgg").cuda()
def get_mask_bbox(mask):
# crop image
true_indices = np.nonzero(mask)
min_h, min_w = np.min(true_indices[0]), np.min(true_indices[1])
max_h, max_w = np.max(true_indices[0]), np.max(true_indices[1])
# print(min_h, min_w)
# print(max... | perceptual_net: VGG16_for_Perceptual, | 2 | 2023-10-15 08:41:29+00:00 | 2k |
ShramanPramanick/VoLTA | Multimodal_Fine_Grained/maskrcnn_benchmark/modeling/roi_heads/mask_head/mask_head.py | [
{
"identifier": "make_roi_mask_feature_extractor",
"path": "Multimodal_Fine_Grained/maskrcnn_benchmark/modeling/roi_heads/mask_head/roi_mask_feature_extractors.py",
"snippet": "def make_roi_mask_feature_extractor(cfg):\n func = _ROI_MASK_FEATURE_EXTRACTORS[cfg.MODEL.ROI_MASK_HEAD.FEATURE_EXTRACTOR]\n... | import torch
from torch import nn
from maskrcnn_benchmark.structures.bounding_box import BoxList
from .roi_mask_feature_extractors import make_roi_mask_feature_extractor
from .roi_mask_predictors import make_roi_mask_predictor
from .inference import make_roi_mask_post_processor
from .loss import make_roi_mask_loss_eval... | 801 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
def keep_only_positive_boxes(boxes):
"""
Given a set of BoxList containing the `labels` field,
return a set of BoxList for which `labels > 0`.
Arguments:
boxes (list of BoxList)
"""
assert isinstance(boxes, (lis... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
def keep_only_positive_boxes(boxes):
"""
Given a set of BoxList containing the `labels` field,
return a set of BoxList for which `labels > 0`.
Arguments:
boxes (list of BoxList)
"""
assert isinstance(boxes, (lis... | self.post_processor = make_roi_mask_post_processor(cfg) | 2 | 2023-10-23 04:07:08+00:00 | 2k |
earthcube-lab/textnoisr | tests/textnoisr/test_noise_dataset.py | [
{
"identifier": "noise",
"path": "textnoisr/noise.py",
"snippet": "class CharNoiseAugmenter:\n _AVAILABLE_ACTIONS = (\"insert\", \"swap\", \"substitute\", \"delete\")\n def __init__(\n self,\n noise_level: float,\n actions: tuple[str, ...] = _AVAILABLE_ACTIONS,\n charac... | from math import isclose
from datasets import load_dataset as hf_load_dataset
from evaluate import load
from textnoisr import noise, noise_dataset
import pytest | 851 |
ABS_TOLERANCE = 1.5e-2
REL_TOLERANCE = 1.5e-2
@pytest.fixture()
def dataset100_text():
return hf_load_dataset("rotten_tomatoes", split="train")
@pytest.fixture()
def dataset100(dataset100_text):
def split_tokens(item):
item["tokens"] = item["text"].split(" ")
return item
return datas... |
ABS_TOLERANCE = 1.5e-2
REL_TOLERANCE = 1.5e-2
@pytest.fixture()
def dataset100_text():
return hf_load_dataset("rotten_tomatoes", split="train")
@pytest.fixture()
def dataset100(dataset100_text):
def split_tokens(item):
item["tokens"] = item["text"].split(" ")
return item
return datas... | noise.CharNoiseAugmenter(noise_level=noise_level, actions=actions, seed=42), | 0 | 2023-10-18 19:28:34+00:00 | 2k |
oven-lab/tuya_cloud_map_extractor | custom_components/tuya_cloud_map_extractor/tuya_vacuum_map_extractor/tuya.py | [
{
"identifier": "ServerError",
"path": "custom_components/tuya_cloud_map_extractor/tuya_vacuum_map_extractor/const.py",
"snippet": "class ServerError(Exception):\n pass"
},
{
"identifier": "ClientIDError",
"path": "custom_components/tuya_cloud_map_extractor/tuya_vacuum_map_extractor/const... | import datetime
import hmac
import requests
from .const import ServerError, ClientIDError, ClientSecretError, DeviceIDError | 749 |
def _get_sign(client_id: str, secret_key: str, url: str, t: int, token: str):
empty_hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
signstr = client_id + token + t + "GET" + "\n" + empty_hash + "\n" + "" + "\n" + url
return hmac.new(
secret_key.encode(), msg=signstr.encod... |
def _get_sign(client_id: str, secret_key: str, url: str, t: int, token: str):
empty_hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
signstr = client_id + token + t + "GET" + "\n" + empty_hash + "\n" + "" + "\n" + url
return hmac.new(
secret_key.encode(), msg=signstr.encod... | raise DeviceIDError("Invalid Device ID") | 3 | 2023-10-22 10:48:25+00:00 | 2k |
mlbio-epfl/hume | hume.py | [
{
"identifier": "parse_args",
"path": "argparser.py",
"snippet": "def parse_args(args):\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--phi1_path', \n type=str,\n required=True,\n help=\"Path to the embeddings in ... | import os
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import learn2learn as l2l
import numpy as np
from tqdm import tqdm
from argparser import parse_args
from activations import Sparsemax
from utils import fix_seed, get_cv_score, check_both_none_or_not_none
from metrics import clust... | 1,573 |
def run(args=None):
args = parse_args(args)
device = torch.device(args.device)
fix_seed(args.seed)
if not os.path.exists(args.exp_path):
os.makedirs(args.exp_path)
phi1 = np.load(args.phi1_path).astype(np.float32)
phi2 = np.load(args.phi2_path).astype(np.float32)
|
def run(args=None):
args = parse_args(args)
device = torch.device(args.device)
fix_seed(args.seed)
if not os.path.exists(args.exp_path):
os.makedirs(args.exp_path)
phi1 = np.load(args.phi1_path).astype(np.float32)
phi2 = np.load(args.phi2_path).astype(np.float32) | assert check_both_none_or_not_none(args.phi1_path_val, args.phi2_path_val) | 4 | 2023-10-20 15:32:06+00:00 | 2k |
MaxDude132/django-register-field | tests/models.py | [
{
"identifier": "Register",
"path": "django_register/base.py",
"snippet": "class Register:\n def __init__(self):\n self._key_to_class = {}\n self._class_to_key = {}\n\n def register(self, klass, db_key=None):\n if db_key is None:\n try:\n db_key = kla... | from dataclasses import dataclass
from django.db import models
from django_register import Register, RegisterChoices, RegisterField | 1,542 | # Standard libraries
# Django
# django_register
@dataclass(unsafe_hash=True)
class CountryInfo:
population: int
capital: str
class CountryChoices(RegisterChoices):
CANADA = CountryInfo(population=37_742_154, capital="Ottawa")
FRANCE = CountryInfo(population=65_273_511, capital="Paris")
GERMANY... | # Standard libraries
# Django
# django_register
@dataclass(unsafe_hash=True)
class CountryInfo:
population: int
capital: str
class CountryChoices(RegisterChoices):
CANADA = CountryInfo(population=37_742_154, capital="Ottawa")
FRANCE = CountryInfo(population=65_273_511, capital="Paris")
GERMANY... | food_register = Register() | 0 | 2023-10-23 18:11:08+00:00 | 2k |
hsouri/bob-classification | medical_chexpert/util/datasets.py | [
{
"identifier": "GaussianBlur",
"path": "medical_chexpert/util/custom_transforms.py",
"snippet": "class GaussianBlur(object):\n \"\"\"Gaussian blur augmentation in SimCLR https://arxiv.org/abs/2002.05709\"\"\"\n\n def __init__(self, sigma=[.1, 2.]):\n self.sigma = sigma\n\n def __call__(... | import os
import PIL
import torch
from torchvision import datasets, transforms
from timm.data import create_transform
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from util.dataloader_med import RetinaDataset, Augmentation, Node21, ChestX_ray14, Covidx, CheXpert
from .custom_transforms im... | 897 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------
# References:
# DeiT: https://github.com/facebookresearch/deit
#... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------
# References:
# DeiT: https://github.com/facebookresearch/deit
#... | transforms.RandomApply([GaussianBlur([.1, 2.])], p=0.5), | 0 | 2023-10-20 16:28:17+00:00 | 2k |
Salz0/telegram_flea | middlewares/message_logging_middleware.py | [
{
"identifier": "Message",
"path": "models.py",
"snippet": "class Message(BaseModel):\n \"\"\"The model for the Telegram message.\"\"\"\n\n from_user: fields.ForeignKeyRelation[User] = fields.ForeignKeyField(\n \"bot.User\", related_name=\"messages\"\n )\n id = fields.IntField(pk=True... | from aiogram import types
from aiogram.dispatcher.middlewares import BaseMiddleware
from arrow import arrow
from models import Message, User
from utils.loguru_logging import logger | 977 | """The middleware to log all the incoming messages into the database."""
class MessagesLoggingMiddleware(BaseMiddleware):
"""The middleware class, inherited from `BaseMiddleware`."""
@staticmethod
async def _save_message(msg: types.Message) -> Message:
"""Save the message into the database."""
... | """The middleware to log all the incoming messages into the database."""
class MessagesLoggingMiddleware(BaseMiddleware):
"""The middleware class, inherited from `BaseMiddleware`."""
@staticmethod
async def _save_message(msg: types.Message) -> Message:
"""Save the message into the database."""
... | logger.info( | 2 | 2023-10-19 17:28:55+00:00 | 2k |
RobertCsordas/moe_layer | triton_src/moe_layer/moe_layer_simple.py | [
{
"identifier": "cvmm",
"path": "triton_src/moe_layer/cvmm.py",
"snippet": "def cvmm(x: torch.Tensor, sel: Union[torch.Tensor, CVMMSel], keys: torch.Tensor):\n if not isinstance(sel, CVMMSel):\n sel = cvmm_prepare_sel(sel, keys.shape[0])\n\n return CVMM.apply(x, sel.sel_index, sel.sel, keys... | import torch
import torch.distributed
import torch.nn.functional as F
import math
from typing import Tuple, List, Optional
from .cvmm import cvmm, cvmm_prepare_sel2, CVMMSel | 1,330 |
def dist_logsumexp(x: torch.Tensor, dim: int, keepdim: bool = False) -> torch.Tensor:
# Calculate numerically stable distributed logsumexp
xmax = x.max(dim=dim, keepdim=True).values
torch.distributed.all_reduce(xmax, op=torch.distributed.ReduceOp.MAX)
xe = (x - xmax).exp().sum(dim=dim, keepdim=True)
... |
def dist_logsumexp(x: torch.Tensor, dim: int, keepdim: bool = False) -> torch.Tensor:
# Calculate numerically stable distributed logsumexp
xmax = x.max(dim=dim, keepdim=True).values
torch.distributed.all_reduce(xmax, op=torch.distributed.ReduceOp.MAX)
xe = (x - xmax).exp().sum(dim=dim, keepdim=True)
... | scores = cvmm(input, index, self.keys) | 0 | 2023-10-16 11:00:47+00:00 | 2k |
meanii/downly | downly/plugins/logger.py | [
{
"identifier": "Downly",
"path": "downly/downly.py",
"snippet": "class Downly(Client):\n \"\"\"\n Downly 🦉\n \"\"\"\n def __init__(self):\n name = self.__class__.__name__.lower()\n\n self.telegram = telegram\n\n super().__init__(\n name,\n api_id=... | from pyrogram import filters, Client
from pyrogram.types import Message
from pyrogram.enums import ChatType
from downly.downly import Downly
from downly.utils.b_logger import b_logger
from downly.database.users_sql import update_user, update_chat | 853 |
@Downly.on_message(filters.private | filters.group | filters.channel, group=2)
@b_logger
async def logger(client: Client, message: Message):
# check if a message is command then do nothing
if message.chat.type == ChatType.GROUP or message.chat.type == ChatType.SUPERGROUP:
update_chat(str(message.cha... |
@Downly.on_message(filters.private | filters.group | filters.channel, group=2)
@b_logger
async def logger(client: Client, message: Message):
# check if a message is command then do nothing
if message.chat.type == ChatType.GROUP or message.chat.type == ChatType.SUPERGROUP:
update_chat(str(message.cha... | update_user(message.from_user.id, message.from_user.username) | 2 | 2023-10-17 16:21:31+00:00 | 2k |
hnesk/flipper-raw-rfid | flipper_raw_rfid/bits.py | [
{
"identifier": "batched",
"path": "flipper_raw_rfid/utils.py",
"snippet": "def batched(iterable: Iterable[Any], n: int) -> Iterable[tuple[Any, ...]]:\n # batched('ABCDEFG', 3) --> ABC DEF G\n if n < 1:\n raise ValueError('n must be at least one')\n it = iter(iterable)\n while batch :... | import re
import numpy
import numpy.typing as npt
from flipper_raw_rfid.utils import batched, Peak | 1,177 | """
Utilities for working with bitstreams
"""
def decode_lengths(pads: npt.NDArray[numpy.int64], peaks: list[Peak]) -> tuple[npt.NDArray[numpy.int8], int]:
"""
Loops through pulses and durations and matches them to peaks
Checks for the length of the peak as a multiple of the first peak and adds as many 1/... | """
Utilities for working with bitstreams
"""
def decode_lengths(pads: npt.NDArray[numpy.int64], peaks: list[Peak]) -> tuple[npt.NDArray[numpy.int8], int]:
"""
Loops through pulses and durations and matches them to peaks
Checks for the length of the peak as a multiple of the first peak and adds as many 1/... | for pair in batched(manchester, 2): | 0 | 2023-10-20 13:06:00+00:00 | 2k |
xingchenshanyao/YOLOP-E | lib/dataset/DemoDataset.py | [
{
"identifier": "clean_str",
"path": "lib/utils/utils.py",
"snippet": "def clean_str(s):\n # Cleans a string by replacing special characters with underscore _\n return re.sub(pattern=\"[|@#!¡·$€%&()=?¿^*;:,¨´><+]\", repl=\"_\", string=s)"
},
{
"identifier": "letterbox_for_img",
"path":... | import glob
import os
import random
import shutil
import time
import cv2
import math
import numpy as np
import torch
from pathlib import Path
from threading import Thread
from PIL import Image, ExifTags
from torch.utils.data import Dataset
from tqdm import tqdm
from ..utils import letterbox_for_img, clean_str | 1,417 |
img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.dng']
vid_formats = ['.mov', '.avi', '.mp4', '.mpg', '.mpeg', '.m4v', '.wmv', '.mkv']
class LoadImages: # for inference
def __init__(self, path, img_size=640):
p = str(Path(path)) # os-agnostic
p = os.path.abspath(p) # absolut... |
img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.dng']
vid_formats = ['.mov', '.avi', '.mp4', '.mpg', '.mpeg', '.m4v', '.wmv', '.mkv']
class LoadImages: # for inference
def __init__(self, path, img_size=640):
p = str(Path(path)) # os-agnostic
p = os.path.abspath(p) # absolut... | img, ratio, pad = letterbox_for_img(img0, new_shape=self.img_size, auto=True) | 1 | 2023-10-24 02:08:25+00:00 | 2k |
godisboy0/nonebot-adapter-wcf | adapters/wechatferry/api.py | [
{
"identifier": "ApiNotAvailable",
"path": "adapters/wechatferry/exception.py",
"snippet": "class ApiNotAvailable(BaseApiNotAvailable, WechatFerryAdapterException):\n \"\"\"API 连接不可用\"\"\""
},
{
"identifier": "UserInfo",
"path": "adapters/wechatferry/basemodel.py",
"snippet": "class U... | from wcferry import Wcf
from typing import Any
from .exception import ApiNotAvailable
from concurrent.futures import ThreadPoolExecutor
from .basemodel import UserInfo
from .sqldb import database
from .utils import file_md5, logger
from .config import AdapterConfig
import asyncio | 1,546 | """
所有的 api 都定义在这里。
call_api 的所有方法最终都会调用这里的方法。
"""
"""
发现绝大多数插件都是为 onebot.v11 所写,为了更好的复用(白嫖),这里也用 onebot.v11 中相关的数据结构。
参数约定:
to_wx_id: 群聊时为群聊id, 非群聊时为用户id
"""
user_cache = {}
md5_executor = ThreadPoolExecutor(max_workers=1)
class API:
| """
所有的 api 都定义在这里。
call_api 的所有方法最终都会调用这里的方法。
"""
"""
发现绝大多数插件都是为 onebot.v11 所写,为了更好的复用(白嫖),这里也用 onebot.v11 中相关的数据结构。
参数约定:
to_wx_id: 群聊时为群聊id, 非群聊时为用户id
"""
user_cache = {}
md5_executor = ThreadPoolExecutor(max_workers=1)
class API:
| def __init__(self, wcf: Wcf, config: AdapterConfig): | 4 | 2023-10-22 10:52:27+00:00 | 2k |
R1999RC-official/Reverse1999ResonanceCalculator | python/python_env/Lib/site-packages/setuptools/config/_apply_pyprojecttoml.py | [
{
"identifier": "SetuptoolsWarning",
"path": "python/python_env/Lib/site-packages/setuptools/warnings.py",
"snippet": "class SetuptoolsWarning(UserWarning):\n \"\"\"Base class in ``setuptools`` warning hierarchy.\"\"\"\n\n @classmethod\n def emit(\n cls,\n summary: Optional[str] =... | import logging
import os
from collections.abc import Mapping
from email.headerregistry import Address
from functools import partial, reduce
from itertools import chain
from types import MappingProxyType
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Set,
Tuple,
... | 1,434 | """Translation layer between pyproject config and setuptools distribution and
metadata objects.
The distribution and metadata objects are modeled after (an old version of)
core metadata, therefore configs in the format specified for ``pyproject.toml``
need to be processed before being applied.
**PRIVATE MODULE**: API... | """Translation layer between pyproject config and setuptools distribution and
metadata objects.
The distribution and metadata objects are modeled after (an old version of)
core metadata, therefore configs in the format specified for ``pyproject.toml``
need to be processed before being applied.
**PRIVATE MODULE**: API... | SetuptoolsDeprecationWarning.emit( | 1 | 2023-10-24 06:48:58+00:00 | 2k |
Summaw/genCraft-imageGen | main.py | [
{
"identifier": "write",
"path": "modules/write/write.py",
"snippet": "def write(text: str, case: str) -> None:\r\n current_time = time.strftime(\"%H:%M:%S\", time.localtime())\r\n switcher = {\r\n 'info': _write_info,\r\n 'success': _write_success,\r\n 'error': _write_error\r... | import time
import asyncio
import requests
from modules.write.write import write
from modules.tasks.login import login_attempt
from modules.tasks.generateImage import generate_image
| 1,328 |
async def start():
loginRequest = await login_attempt()
if loginRequest == 'False':
write("There was a problem logging in.", "error")
else:
write(f"Session ID: {loginRequest}", 'info')
|
async def start():
loginRequest = await login_attempt()
if loginRequest == 'False':
write("There was a problem logging in.", "error")
else:
write(f"Session ID: {loginRequest}", 'info')
| await generate_image(loginRequest)
| 2 | 2023-10-20 20:56:32+00:00 | 2k |
mentpy/mentpy | mentpy/gradients/grad.py | [
{
"identifier": "fd_gradient",
"path": "mentpy/gradients/_finite_difference.py",
"snippet": "def fd_gradient(f, x, h=1e-5, type=\"central\"):\n if type not in [\"central\", \"forward\", \"backward\"]:\n raise UserWarning(\n f\"Expected type to be 'central', 'forward', or 'backward' ... | import numpy as np
from ._finite_difference import fd_gradient, fd_hessian
from ._parameter_shift import psr_gradient, psr_hessian | 1,328 | # Copyright 2023 Luis Mantilla
#
# Licensed under the Apache License, Version 2.0.
# See <http://www.apache.org/licenses/LICENSE-2.0> for details.
"""Module that contains functions to calculate gradients of cost functions."""
__all__ = ["get_gradient", "get_hessian"]
def get_gradient(cost, x, method="parameter-shift... | # Copyright 2023 Luis Mantilla
#
# Licensed under the Apache License, Version 2.0.
# See <http://www.apache.org/licenses/LICENSE-2.0> for details.
"""Module that contains functions to calculate gradients of cost functions."""
__all__ = ["get_gradient", "get_hessian"]
def get_gradient(cost, x, method="parameter-shift... | return psr_gradient(cost, x, *args, **kwargs) | 2 | 2023-10-18 18:29:42+00:00 | 2k |
rnag/cert-hero | cert_hero/cli.py | [
{
"identifier": "certs_please",
"path": "cert_hero/cert_hero.py",
"snippet": "def certs_please(\n hostnames: list[str] | tuple[str] | set[str],\n context: ssl.SSLContext = None,\n num_threads: int = 25,\n user_agent: str | None = _DEFAULT_USER_AGENT,\n) -> dict[str, CertHero]:\n \"\"\"\n ... | import argparse
import sys
from . import certs_please, set_expired | 1,297 | """Console script for cert_hero."""
def main():
"""Console script for cert_hero."""
parser = argparse.ArgumentParser(prog='ch', description='Retrieve the SSL certificate(s) for one or more given host')
parser.add_argument('hosts', nargs='*')
args = parser.parse_args()
host_to_cert = certs_please... | """Console script for cert_hero."""
def main():
"""Console script for cert_hero."""
parser = argparse.ArgumentParser(prog='ch', description='Retrieve the SSL certificate(s) for one or more given host')
parser.add_argument('hosts', nargs='*')
args = parser.parse_args()
host_to_cert = certs_please... | set_expired(host_to_cert) | 1 | 2023-10-16 19:02:05+00:00 | 2k |
KosinskiLab/pyTME | tme/matching_optimization.py | [
{
"identifier": "rigid_transform",
"path": "tme/matching_utils.py",
"snippet": "def rigid_transform(\n coordinates: NDArray,\n rotation_matrix: NDArray,\n out: NDArray,\n translation: NDArray,\n use_geometric_center: bool = False,\n coordinates_mask: NDArray = None,\n out_mask: NDAr... | from typing import Tuple, Dict
from abc import ABC, abstractmethod
from numpy.typing import NDArray
from scipy.optimize import (
differential_evolution,
LinearConstraint,
basinhopping,
)
from scipy.ndimage import laplace
from scipy.spatial import KDTree
from .matching_utils import rigid_transform, euler_to_... | 1,363 | """ Implements various methods for non-exhaustive template matching
based on numerical optimization.
Copyright (c) 2023 European Molecular Biology Laboratory
Author: Valentin Maurer <valentin.maurer@embl-hamburg.de>
"""
class MatchCoordinatesToDensity(ABC):
"""
A class to template match coord... | """ Implements various methods for non-exhaustive template matching
based on numerical optimization.
Copyright (c) 2023 European Molecular Biology Laboratory
Author: Valentin Maurer <valentin.maurer@embl-hamburg.de>
"""
class MatchCoordinatesToDensity(ABC):
"""
A class to template match coord... | rigid_transform( | 0 | 2023-10-20 13:46:01+00:00 | 2k |
hookla/DreamTeamGPT | dream_team_gpt/main.py | [
{
"identifier": "Meeting",
"path": "dream_team_gpt/meeting.py",
"snippet": "class Meeting:\n idea: str\n config: Path = None\n\n def __post_init__(self) -> None:\n \"\"\"Create agents\"\"\"\n client_factory = ai_client_factory(\n AIClientConfig(\n client_... | from dataclasses import dataclass
from pathlib import Path
from dotenv import load_dotenv
from dream_team_gpt.meeting import Meeting
from dream_team_gpt.utils import configure_logging
import os
import click | 655 |
@click.command()
@click.option(
"--idea",
"-i",
type=str,
required=True,
help="your idea for the team to discuss. Please use double quotes",
)
@click.option(
"--config",
"-c",
type=click.Path(exists=True),
default=None,
help="yaml file with team personalities details",
)
@cli... |
@click.command()
@click.option(
"--idea",
"-i",
type=str,
required=True,
help="your idea for the team to discuss. Please use double quotes",
)
@click.option(
"--config",
"-c",
type=click.Path(exists=True),
default=None,
help="yaml file with team personalities details",
)
@cli... | configure_logging(verbose) | 1 | 2023-10-18 22:45:50+00:00 | 2k |
amrahhh/sqla_async_orm_queries | examples/test.py | [
{
"identifier": "Model",
"path": "sqla_async_orm_queries/models.py",
"snippet": "class Model(Base):\n __abstract__ = True\n\n @classmethod\n async def create(cls, data: dict):\n async with SessionLocal() as session:\n try:\n data = cls(**data)\n s... | import asyncio
from sqlalchemy import Column, String, Integer, and_
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqla_async_orm_queries import Model, init_session | 836 |
# create your engine
engine = create_async_engine(
"postgresql+asyncpg://test_user:12345@localhost/test_db",
echo=True,
)
# create your SessionLocal
SessionLocal = async_sessionmaker(
expire_on_commit=True,
class_=AsyncSession,
bind=engine,
)
|
# create your engine
engine = create_async_engine(
"postgresql+asyncpg://test_user:12345@localhost/test_db",
echo=True,
)
# create your SessionLocal
SessionLocal = async_sessionmaker(
expire_on_commit=True,
class_=AsyncSession,
bind=engine,
)
| class Test(Model): | 0 | 2023-10-17 09:42:44+00:00 | 2k |
MeetingAgent/MeetingAgent-Core | meeting_buddy.py | [
{
"identifier": "MyTTS",
"path": "voice_cloning/clone.py",
"snippet": "class MyTTS:\n def __init__(self):\n # Get device\n self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n self.tts = TTS(\"tts_models/en/ljspeech/tacotron2-DDC\")\n self.use_default_speak... | import pyaudio
import wave
import whisper
import threading
import time
import pygame
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.switch import Switch
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.uix.textinput import TextIn... | 1,587 | # Audio Processing
# GUI
install_twisted_reactor()
# gtts text to speech
# personalized voice text to speech
# Local
recording = False
audio_thread = None
def get_audio() -> None:
global recording
recording = True
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44... | # Audio Processing
# GUI
install_twisted_reactor()
# gtts text to speech
# personalized voice text to speech
# Local
recording = False
audio_thread = None
def get_audio() -> None:
global recording
recording = True
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44... | query = gpt_3_5_turbo_16k_answer(messages=messages) | 2 | 2023-10-18 06:50:56+00:00 | 2k |
KaichengGroup/FUSE-Flow | FUSE_Flow/other_modules/adaptive_unet.py | [
{
"identifier": "AEInit",
"path": "FUSE_Flow/other_modules/utils.py",
"snippet": "class AEInit(str, Enum):\n zero = 'zero'\n xavier = 'xavier'\n\n @classmethod\n def get_values(cls):\n return tuple(map(lambda c: c.value, cls))"
},
{
"identifier": "ConvBlock",
"path": "FUSE... | import math
import pytorch_lightning as pl
import torch
from torch import nn
from FUSE_Flow.other_modules.utils import AEInit
from .conv_modules.conv_block import ConvBlock
from .gated_resnet import UpsampleBlock, DownsampleBlock | 1,391 |
class AdaptiveUNet(pl.LightningModule):
"""SR network architecture that uses Residual-in-Residual Dense Blocks.
Implement Figure (3) in ESRGAN paper.
Parameters
----------
d_x : int
Priority dimension (height or width) of input chosen for downstream comparisons.
d_y : int
Pr... |
class AdaptiveUNet(pl.LightningModule):
"""SR network architecture that uses Residual-in-Residual Dense Blocks.
Implement Figure (3) in ESRGAN paper.
Parameters
----------
d_x : int
Priority dimension (height or width) of input chosen for downstream comparisons.
d_y : int
Pr... | 3, 1, 1, AEInit.xavier, attention_type, attn_red_ratio)] + | 0 | 2023-10-19 06:49:31+00:00 | 2k |
zytedata/zyte-spider-templates | zyte_spider_templates/spiders/ecommerce.py | [
{
"identifier": "document_enum",
"path": "zyte_spider_templates/documentation.py",
"snippet": "def document_enum(func):\n return func"
},
{
"identifier": "BaseSpider",
"path": "zyte_spider_templates/spiders/base.py",
"snippet": "class BaseSpider(scrapy.Spider):\n custom_settings: D... | from enum import Enum
from typing import Any, Callable, Dict, Iterable, Optional, Union
from pydantic import Field
from scrapy import Request
from scrapy.crawler import Crawler
from scrapy_poet import DummyResponse
from scrapy_spider_metadata import Args
from zyte_common_items import ProbabilityRequest, Product, Produc... | 1,014 |
@document_enum
class EcommerceCrawlStrategy(str, Enum):
full: str = "full"
"""Follow most links within the domain of URL in an attempt to discover and
extract as many products as possible."""
navigation: str = "navigation"
"""Follow pagination, subcategories, and product detail pages."""
p... |
@document_enum
class EcommerceCrawlStrategy(str, Enum):
full: str = "full"
"""Follow most links within the domain of URL in an attempt to discover and
extract as many products as possible."""
navigation: str = "navigation"
"""Follow pagination, subcategories, and product detail pages."""
p... | class EcommerceSpiderParams(BaseSpiderParams): | 2 | 2023-10-18 10:58:44+00:00 | 2k |
Bio-OS/bio-mate | bio_mate/BaseWidget.py | [
{
"identifier": "gen_data_url_img",
"path": "bio_mate/defs.py",
"snippet": "def gen_data_url_img(img_path: Path):\n base64_utf8_str = base64.b64encode(img_path.read_bytes()).decode(\"utf-8\")\n ext = str(img_path).split(\".\")[-1]\n data_url = f\"data:image/{ext};base64,{base64_utf8_str}\"\n\n ... | from ipywidgets import DOMWidget
from traitlets import Bool, Unicode, Dict, Int
from bio_mate.defs import gen_data_url_img, get_img, list_files, prepare_plot_env
import json
import warnings
import subprocess | 848 |
module_name = "bio-mate"
module_version = "1.0.0"
class BaseWidget(DOMWidget):
_model_name = Unicode("BaseWidgetModel").tag(sync=True)
_model_module = Unicode(module_name).tag(sync=True)
_model_module_version = Unicode(module_version).tag(sync=True)
_view_name = Unicode("BaseWidgetView").tag(sync=T... |
module_name = "bio-mate"
module_version = "1.0.0"
class BaseWidget(DOMWidget):
_model_name = Unicode("BaseWidgetModel").tag(sync=True)
_model_module = Unicode(module_name).tag(sync=True)
_model_module_version = Unicode(module_version).tag(sync=True)
_view_name = Unicode("BaseWidgetView").tag(sync=T... | content["response"] = {"status": "ok", "result": get_img(self.type)} | 1 | 2023-10-19 02:15:54+00:00 | 2k |
iamarunbrahma/llm-prompt-testing | metrics.py | [
{
"identifier": "get_embeddings",
"path": "utils.py",
"snippet": "@retry(wait=wait_random_exponential(min=3, max=90), stop=stop_after_attempt(6))\r\ndef get_embeddings(text, embedding_model=\"text-embedding-ada-002\"):\r\n response = openai.Embedding.create(\r\n model=embedding_model,\r\n ... | from collections import Counter
from numpy.linalg import norm
from utils import get_embeddings, get_chat_completion
import evaluate
import streamlit as st
import traceback
import numpy as np
| 1,122 |
class Metrics:
def __init__(self, question, context, answer, config, strictness=1):
self.question = question
self.context = context
self.answer = answer
self.strictness = strictness
config["model_name"] = "gpt-3.5-turbo"
self.config = config
def ro... |
class Metrics:
def __init__(self, question, context, answer, config, strictness=1):
self.question = question
self.context = context
self.answer = answer
self.strictness = strictness
config["model_name"] = "gpt-3.5-turbo"
self.config = config
def ro... | question_vec = np.asarray(get_embeddings(self.question.strip()))
| 0 | 2023-10-24 17:37:07+00:00 | 2k |
AVAniketh0905/fluidspy | fluidspylib/fluidspy/numerical/methods/finite_differential.py | [
{
"identifier": "CompositeBoundary",
"path": "fluidspylib/fluidspy/numerical/boundary/composite.py",
"snippet": "class CompositeBoundary:\n children: List[Direction]\n\n def __init__(self, *args) -> None:\n self.children = list(args)\n\n def init_apply(self):\n for child in self.c... | from abc import ABC
from abc import abstractmethod
from typing import List
from ..boundary.composite import CompositeBoundary
from ..dim import Dimension
from ..material_properties import MaterialProperties
from ..material_properties import ThermalProperties
from ..state import SimulationState
from ..step import Step
f... | 1,020 |
class FiniteDifferentialMethod(ABC):
def __init__(
self,
state: SimulationState,
dim: Dimension,
properties: ThermalProperties,
|
class FiniteDifferentialMethod(ABC):
def __init__(
self,
state: SimulationState,
dim: Dimension,
properties: ThermalProperties, | boundary_conditions: CompositeBoundary, | 0 | 2023-10-21 06:55:58+00:00 | 2k |
zorrobyte/esp32-universal-diesel-heater-controller | main.py | [
{
"identifier": "stateMachine",
"path": "states/stateMachine.py",
"snippet": "def log(message, level=2):\ndef handle_state(current_state, switch_value, exhaust_temp, output_temp):"
},
{
"identifier": "emergencyStop",
"path": "states/emergencyStop.py",
"snippet": "def log(message, level=1... | import machine
import _thread
import hardwareConfig as config
import utime
import webserver
from machine import Timer
from states import stateMachine, emergencyStop
from lib import sensors, networking, fanPID | 1,091 | ####################################################################
# WARNING #
####################################################################
# This code is provided "AS IS" without warranty of any kind. #
# Use of this code in any form acknowledges ... | ####################################################################
# WARNING #
####################################################################
# This code is provided "AS IS" without warranty of any kind. #
# Use of this code in any form acknowledges ... | config.current_state, config.emergency_reason = stateMachine.handle_state( | 0 | 2023-10-24 14:50:47+00:00 | 2k |
suliman-99/django-seeding | django_seeding/seeder_registry.py | [
{
"identifier": "Seeder",
"path": "django_seeding/seeders.py",
"snippet": "class Seeder():\n \"\"\" \n The `Seeder` class provides a minimal class which may be used\n for writing custom seeding implementations.\n \n Required:\n seed:\n `seed()` as <method>\n\n Additio... | import sys
import importlib.util
from pathlib import Path
from django.apps import apps
from django.conf import settings
from .seeders import Seeder
from .models import AppliedSeeder | 1,236 |
class SeederRegistry:
"""
The `SeederRegistry` class apply registered seeders when the server is run.
seeder registering is doing by:
@SeederRegistry.register as <decorator>
or
SeederRegistry.register(<seeder-class>) as <method>
"""
seeders = []
@classmethod
d... |
class SeederRegistry:
"""
The `SeederRegistry` class apply registered seeders when the server is run.
seeder registering is doing by:
@SeederRegistry.register as <decorator>
or
SeederRegistry.register(<seeder-class>) as <method>
"""
seeders = []
@classmethod
d... | if not issubclass(seeder, Seeder): | 0 | 2023-10-24 17:00:49+00:00 | 2k |
cfs-energy/cfspopcon | cfspopcon/helpers.py | [
{
"identifier": "Algorithms",
"path": "cfspopcon/named_options.py",
"snippet": "class Algorithms(Enum):\n \"\"\"Select which top-level algorithm to run.\"\"\"\n\n predictive_popcon = auto()\n two_point_model_fixed_fpow = auto()\n two_point_model_fixed_qpart = auto()\n two_point_model_fixe... | from typing import Any, Union
from .named_options import (
Algorithms,
ConfinementScaling,
Impurity,
LambdaQScaling,
MomentumLossFunction,
ProfileForm,
RadiationMethod,
ReactionType,
)
import xarray as xr | 1,324 | """Constructors and helper functions."""
def convert_named_options(key: str, val: Any) -> Any: # noqa: PLR0911, PLR0912
"""Given a 'key' matching a named_option, return the corresponding Enum value."""
if key == "algorithms":
return Algorithms[val]
elif key == "energy_confinement_scaling":
... | """Constructors and helper functions."""
def convert_named_options(key: str, val: Any) -> Any: # noqa: PLR0911, PLR0912
"""Given a 'key' matching a named_option, return the corresponding Enum value."""
if key == "algorithms":
return Algorithms[val]
elif key == "energy_confinement_scaling":
... | return ProfileForm[val] | 5 | 2023-10-19 16:58:23+00:00 | 2k |
yifei-he/GOAT | experiments.py | [
{
"identifier": "ot_ablation",
"path": "ot_util.py",
"snippet": "def ot_ablation(size, mode):\n ns, nt = size, size\n plan = np.zeros((ns, nt))\n ran = np.arange(ns*nt)\n np.random.shuffle(ran)\n idx = ran[:size]\n\n for i in idx:\n row = i // nt\n col = i-i//nt * nt\n ... | import torch
import torch.optim as optim
import copy
import argparse
import random
import torch.backends.cudnn as cudnn
import time
from model import *
from train_model import *
from util import *
from ot_util import ot_ablation
from da_algo import *
from ot_util import generate_domains
from dataset import * | 1,057 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def get_source_model(args, trainset, testset, n_class, mode, encoder=None, epochs=50, verbose=True):
print("Start training source model")
model = Classifier(encoder, MLP(mode=mode, n_class=n_class, hidden=1024)).to(device)
optimizer ... |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def get_source_model(args, trainset, testset, n_class, mode, encoder=None, epochs=50, verbose=True):
print("Start training source model")
model = Classifier(encoder, MLP(mode=mode, n_class=n_class, hidden=1024)).to(device)
optimizer ... | all_domains += generate_domains(generated_domains, encoded_intersets[i], encoded_intersets[i+1]) | 1 | 2023-10-20 16:41:00+00:00 | 2k |
ansible/django-ansible-base | ansible_base/tests/unit/serializers/test_common.py | [
{
"identifier": "AuthenticatorMap",
"path": "ansible_base/models/authenticator_map.py",
"snippet": "class AuthenticatorMap(NamedCommonModel):\n class Meta:\n app_label = 'ansible_base'\n # If the map type is a team then we must have an org/team\n constraints = [\n mode... | import pytest
from ansible_base.models import AuthenticatorMap
from ansible_base.serializers.common import CommonModelSerializer
from ansible_base.utils.encryption import ENCRYPTED_STRING
from test_app.models import EncryptionModel
from test_app.serializers import EncryptionTestSerializer | 1,413 |
@pytest.mark.django_db
def test_representation_of_encrypted_fields():
model = EncryptionModel.objects.create()
|
@pytest.mark.django_db
def test_representation_of_encrypted_fields():
model = EncryptionModel.objects.create() | serializer = EncryptionTestSerializer() | 4 | 2023-10-20 13:20:12+00:00 | 2k |
zhudotexe/kani-vision | kani/ext/vision/engines/openai/models.py | [
{
"identifier": "ImagePart",
"path": "kani/ext/vision/parts.py",
"snippet": "class ImagePart(MessagePart, abc.ABC):\n \"\"\"Base class for all image message parts.\n\n Generally, you shouldn't construct this directly - instead, use one of the classmethods to initialize the image from\n a file p... | from typing import Annotated, Literal, Union
from pydantic import Field
from kani.engines.openai.models import OpenAIChatMessage
from kani.models import BaseModel, ChatMessage, ChatRole
from ...parts import ImagePart, RemoteURLImagePart | 1,114 |
# note: `type` does not have default since we use `.model_dump(..., exclude_defaults=True)`
class OpenAIText(BaseModel):
type: Literal["text"]
text: str
@classmethod
def from_text(cls, data: str):
return cls(type="text", text=data)
class OpenAIImage(BaseModel):
type: Literal["image_ur... |
# note: `type` does not have default since we use `.model_dump(..., exclude_defaults=True)`
class OpenAIText(BaseModel):
type: Literal["text"]
text: str
@classmethod
def from_text(cls, data: str):
return cls(type="text", text=data)
class OpenAIImage(BaseModel):
type: Literal["image_ur... | if isinstance(part, RemoteURLImagePart): | 1 | 2023-10-20 16:21:03+00:00 | 2k |
line/Skeleton-Temporal-Action-Localization | evaluation/eval.py | [
{
"identifier": "getClassificationMAP",
"path": "evaluation/classificationMAP.py",
"snippet": "def getClassificationMAP(confidence, labels):\n \"\"\" confidence and labels are of dimension n_samples x n_label \"\"\"\n\n AP = []\n for i in range(np.shape(labels)[1]):\n AP.append(getAP(con... | import numpy as np
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from .classificationMAP import getClassificationMAP as cmAP
from .detectionMAP import getSingleStreamDetectionMAP as dsmAP
from .detectionMAP import getTwoStreamDetectionMAP as dtmAP
from .utils import write_results_to_e... | 1,385 |
def ss_eval(epoch, dataloader, args, logger, model, device):
vid_preds = []
frm_preds = []
vid_lens = []
labels = []
for num, sample in enumerate(dataloader):
if (num + 1) % 100 == 0:
print("Testing test data point %d of %d" % (num + 1, len(dataloader)))
features = s... |
def ss_eval(epoch, dataloader, args, logger, model, device):
vid_preds = []
frm_preds = []
vid_lens = []
labels = []
for num, sample in enumerate(dataloader):
if (num + 1) % 100 == 0:
print("Testing test data point %d of %d" % (num + 1, len(dataloader)))
features = s... | write_results_to_file(args, dmap, cmap, epoch) | 4 | 2023-10-20 05:38:16+00:00 | 2k |
n-thumann/xbox-cloud-statistics | backend/xbox_cloud_statistics/main.py | [
{
"identifier": "Game",
"path": "backend/xbox_cloud_statistics/models.py",
"snippet": "class Game(Model):\n id: str\n title: str\n image_url: str\n subscriptions: Subscription\n\n def to_dict(self) -> dict:\n return {\"id\": self.id, \"title\": self.title, \"image_url\": self.image... | import asyncio
import itertools
import httpx
from pathlib import Path
from xbox_cloud_statistics.client import XBoxCloudClient
from xbox_cloud_statistics.config import Config
from xbox_cloud_statistics.io.cli import CLI
from xbox_cloud_statistics.io.json import JSON
from .models import (
Game,
Measurement,
... | 669 |
def run():
asyncio.run(main())
async def main():
config = Config()
results = Results()
async with httpx.AsyncClient(http2=True) as http_client:
client = XBoxCloudClient(http_client, config.client_id, config.client_secret)
if config.f2p_token:
await run_measurements(
... |
def run():
asyncio.run(main())
async def main():
config = Config()
results = Results()
async with httpx.AsyncClient(http2=True) as http_client:
client = XBoxCloudClient(http_client, config.client_id, config.client_secret)
if config.f2p_token:
await run_measurements(
... | times: list[Measurement | Exception] = await asyncio.gather( | 1 | 2023-10-22 13:05:00+00:00 | 2k |
albu-org/aiotp | aiotp/totp/totp.py | [
{
"identifier": "OTP",
"path": "aiotp/core/otp.py",
"snippet": "class OTP(AbstractOTP):\n def __init__(\n self,\n secret: str,\n digit: int = 5,\n algorithm: algorithms = 'sha1'\n ) -> None:\n assert 0 < digit < 11\n assert algorithm.lower() in ('sha1', 's... | import hmac
import datetime
import unicodedata
from typing import Optional
from urllib.parse import quote, urlencode, urlparse
from ..core import OTP
from ..utils import conversion
from ..typing import algorithms
from ..abstracts import AbstractTOTP | 711 |
class TOTP(AbstractTOTP, OTP):
def __init__(
self,
secret: str,
digits: int = 5,
interval: int = 60,
algorithm: algorithms = 'sha1',
) -> None:
self.interval = interval
super().__init__(secret, digits, algorithm)
async def __aenter__(self) -> 'TOT... |
class TOTP(AbstractTOTP, OTP):
def __init__(
self,
secret: str,
digits: int = 5,
interval: int = 60,
algorithm: algorithms = 'sha1',
) -> None:
self.interval = interval
super().__init__(secret, digits, algorithm)
async def __aenter__(self) -> 'TOT... | return await self._generate(await conversion(dt, self.interval)) | 1 | 2023-10-20 18:51:22+00:00 | 2k |
brandonrobertz/reason-act-sqlite-py | llm_sql_queries.py | [
{
"identifier": "DB_PATH",
"path": "actions.py",
"snippet": "DB_PATH = \"example.db\""
},
{
"identifier": "load_db",
"path": "actions.py",
"snippet": "def load_db(path):\n assert os.path.exists(path), f\"Database doesn't exist: {path}\"\n db = sqlite_utils.Database(path)\n retur... | import json
import os
import re
import sys
import sqlite3
from llama_cpp import Llama
from actions import (
DB_PATH, load_db,
tables, schema, help, sql_query
) | 971 |
try:
except ModuleNotFoundError:
print("llama_cpp not installed, continuing without")
# Larger context sizes will reduce quality, but some models
# support large contexts better than others.
#CONTEXT_SIZE=2048
CONTEXT_SIZE=2048*2
# how many tokens to allow the model to output in a sigle go w/o stopping
MAX_TOKE... |
try:
except ModuleNotFoundError:
print("llama_cpp not installed, continuing without")
# Larger context sizes will reduce quality, but some models
# support large contexts better than others.
#CONTEXT_SIZE=2048
CONTEXT_SIZE=2048*2
# how many tokens to allow the model to output in a sigle go w/o stopping
MAX_TOKE... | db = load_db(DB_PATH) | 1 | 2023-10-15 04:30:30+00:00 | 2k |
sehyun03/MulActSeg | tools/label_assignment_tensor.py | [
{
"identifier": "RegionCityscapesTensor",
"path": "dataloader/region_cityscapes_tensor.py",
"snippet": "class RegionCityscapesTensor(RegionCityscapes):\n\n def __init__(self, args, root, datalist, split='train', transform=None, region_dict=\"dataloader/init_data/cityscapes/train.dict\"):\n sup... | import os
import sys
import argparse
import numpy as np
import dataloader.ext_transforms as et
from tqdm import tqdm
from dataloader.region_cityscapes_tensor import RegionCityscapesTensor
from dataloader.utils import DataProvider | 1,591 | sys.path.append(os.path.abspath('.'))
def get_parser():
# Training configurations
parser = argparse.ArgumentParser(description='')
parser.add_argument('--nseg', type=int, default=2048, help='# superpixel component for slic')
parser.add_argument('--save_data_dir', help='superpixel directory root')
... | sys.path.append(os.path.abspath('.'))
def get_parser():
# Training configurations
parser = argparse.ArgumentParser(description='')
parser.add_argument('--nseg', type=int, default=2048, help='# superpixel component for slic')
parser.add_argument('--save_data_dir', help='superpixel directory root')
... | region_dataset = RegionCityscapesTensor(args, | 0 | 2023-10-24 09:19:58+00:00 | 2k |
upiterbarg/hihack | models/flat_transformer.py | [
{
"identifier": "generate_square_subsequent_mask",
"path": "models/transformer_lstm.py",
"snippet": "def generate_square_subsequent_mask(sz: int, device: str = \"cpu\") -> torch.Tensor:\n mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)\n mask = (\n mask.float()\n .masked... | import json
import numpy as np
import os
import pathlib
import pdb
import sys
import torch
from nle import nethack
from nle.nethack.actions import ACTIONS as A
from torch import nn
from torch.nn import functional as F
from .transformer_lstm import (
generate_square_subsequent_mask,
PositionalEncoding
)
from cha... | 1,449 |
base_path = pathlib.Path().resolve()
sys.path.insert(0, os.path.join(base_path, '..', 'dungeonsdata-neurips2022/experiment_code/hackrl/models'))
class FlatTransformer(nn.Module):
def __init__(self, shape, action_space, flags, device):
super(FlatTransformer, self).__init__()
self.flags ... |
base_path = pathlib.Path().resolve()
sys.path.insert(0, os.path.join(base_path, '..', 'dungeonsdata-neurips2022/experiment_code/hackrl/models'))
class FlatTransformer(nn.Module):
def __init__(self, shape, action_space, flags, device):
super(FlatTransformer, self).__init__()
self.flags ... | core_mask = generate_square_subsequent_mask(T, core_input.device) | 0 | 2023-10-23 15:44:32+00:00 | 2k |
kulkansecurity/gitverify | gitverify.py | [
{
"identifier": "gh_api",
"path": "include/gh_api.py",
"snippet": "GITHUB_API_URL = \"https://api.github.com/repos/\"\nGITHUB_TOKEN = os.environ.get(\"GH_ACCESS_TOKEN\", None)\ndef github_request_json(url):\ndef fetch_domains_from_code(repository):\ndef fetch_repository(github_url):\ndef fetch_contribut... | import os, sys
from include import gh_api, output, arg_parser
from modules import verify_metadata
from modules import verify_contributors
from modules import verify_domains
from modules import verify_issues_prs | 1,180 | #!/usr/bin/env python3
if __name__ == "__main__":
args = arg_parser.parse_arguments()
output_obj = output.Output(verbose=args.verbose, outfile=args.outfile, outformat=args.format)
print("""
░██████╗░██╗████████╗██╗░░░██╗███████╗██████╗░██╗███████╗██╗░░░██╗
██╔════╝░██║╚══██╔══╝██║░░░██║██╔════╝██╔══██╗██... | #!/usr/bin/env python3
if __name__ == "__main__":
args = arg_parser.parse_arguments()
output_obj = output.Output(verbose=args.verbose, outfile=args.outfile, outformat=args.format)
print("""
░██████╗░██╗████████╗██╗░░░██╗███████╗██████╗░██╗███████╗██╗░░░██╗
██╔════╝░██║╚══██╔══╝██║░░░██║██╔════╝██╔══██╗██... | contributors = verify_contributors.run(repository, output_obj) | 4 | 2023-10-24 15:39:55+00:00 | 2k |
nmathey/finasync | finasync/realt.py | [
{
"identifier": "GNOSIS_API_TOKENLIST_URI",
"path": "finasync/constants.py",
"snippet": "GNOSIS_API_TOKENLIST_URI = (\n \"https://blockscout.com/xdai/mainnet/api?module=account&action=tokenlist&address=\"\n)"
},
{
"identifier": "REALT_API_TOKENLIST_URI",
"path": "finasync/constants.py",
... | import requests
import re
import json
import time
import os
import logging
from pathlib import Path
from datetime import datetime, timedelta
from json.decoder import JSONDecodeError
from finary_uapi.user_real_estates import (
get_user_real_estates,
delete_user_real_estates,
update_user_real_estates,
add... | 881 |
def get_realt_token_details(realt_token_contractAdress):
Now_Time = datetime.today()
RealT_OfflineTokensList_Path = Path(REALT_OFFLINE_TOKENS_LIST)
RealT_OfflineTokensList_Path.touch(exist_ok=True)
with open(RealT_OfflineTokensList_Path) as json_file:
try:
RealT_OfflineTokensLis... |
def get_realt_token_details(realt_token_contractAdress):
Now_Time = datetime.today()
RealT_OfflineTokensList_Path = Path(REALT_OFFLINE_TOKENS_LIST)
RealT_OfflineTokensList_Path.touch(exist_ok=True)
with open(RealT_OfflineTokensList_Path) as json_file:
try:
RealT_OfflineTokensLis... | REALT_API_TOKENLIST_URI, headers=MyRealT_API_Header | 1 | 2023-10-24 00:32:05+00:00 | 2k |
biggzlar/plausible-uncertainties | evidential_regression/networks.py | [
{
"identifier": "DenseInverseGamma",
"path": "evidential_regression/layers.py",
"snippet": "class DenseInverseGamma(torch.nn.Module):\n \"\"\" Based on: https://github.com/aamini/evidential-deep-learning.\n \"\"\"\n def __init__(self, in_features, units=1):\n super(DenseInverseGamma, sel... | import torch
import torch.nn as nn
import numpy as np
from .layers import DenseInverseGamma, DenseInverseWishart | 897 |
class UnivariateDerNet(nn.Module):
def __init__(self):
super(UnivariateDerNet, self).__init__()
self.hidden = nn.Sequential(
nn.Linear(in_features=1, out_features=128),
# nn.ReLU6(),
# nn.Tanh(),
nn.Mish(),
nn.Linear(in_features=128, out_features=128),
# nn.ReLU6(),
# nn.Tanh(),
nn.Mish... |
class UnivariateDerNet(nn.Module):
def __init__(self):
super(UnivariateDerNet, self).__init__()
self.hidden = nn.Sequential(
nn.Linear(in_features=1, out_features=128),
# nn.ReLU6(),
# nn.Tanh(),
nn.Mish(),
nn.Linear(in_features=128, out_features=128),
# nn.ReLU6(),
# nn.Tanh(),
nn.Mish... | DenseInverseGamma(in_features=128, units=1) | 0 | 2023-10-19 08:44:08+00:00 | 2k |
t-ega/whatsapp-cloud-sdk | whatsapp_cloud_sdk/_formaters/message_formatter.py | [
{
"identifier": "JSONDict",
"path": "whatsapp_cloud_sdk/_utils/types.py",
"snippet": "class MessageTypes(Enum):\n IMAGE = \"image\"\n AUDIO = \"audio\"\n TEXT = \"text\"\n REACTION = \"reaction\"\n STICKER = \"sticker\"\n LOCATION = \"location\"\n UNKNOWN = \"unknown\""
},
{
... | from enum import Enum
from typing import List, Optional
from unicodedata import decimal
from whatsapp_cloud_sdk._utils.types import JSONDict
from whatsapp_cloud_sdk._validators.messages import ButtonContents | 884 | """This module contains custom formatting class and aliases for internal use within the library.
Warning:
Contents of this module are intended to be used internally by the library and *not* by the
user. Changes to this module are not considered breaking changes and may not be documented in
the changelog.
"... | """This module contains custom formatting class and aliases for internal use within the library.
Warning:
Contents of this module are intended to be used internally by the library and *not* by the
user. Changes to this module are not considered breaking changes and may not be documented in
the changelog.
"... | buttons: List[ButtonContents], | 1 | 2023-10-15 21:12:45+00:00 | 2k |
DTennant/GPC | data/imagenet.py | [
{
"identifier": "subsample_instances",
"path": "data/data_utils.py",
"snippet": "def subsample_instances(dataset, prop_indices_to_subsample=0.8):\n\n np.random.seed(0)\n subsample_indices = np.random.choice(range(len(dataset)), replace=False,\n size=(int(pro... | import torchvision
import numpy as np
import os
from copy import deepcopy
from data.data_utils import subsample_instances
from config import imagenet_root | 1,514 |
class ImageNetBase(torchvision.datasets.ImageFolder):
def __init__(self, root, transform):
super(ImageNetBase, self).__init__(root, transform)
self.uq_idxs = np.array(range(len(self)))
def __getitem__(self, item):
img, label = super().__getitem__(item)
uq_idx = self.uq_i... |
class ImageNetBase(torchvision.datasets.ImageFolder):
def __init__(self, root, transform):
super(ImageNetBase, self).__init__(root, transform)
self.uq_idxs = np.array(range(len(self)))
def __getitem__(self, item):
img, label = super().__getitem__(item)
uq_idx = self.uq_i... | imagenet_training_set = ImageNetBase(root=os.path.join(imagenet_root, 'train'), transform=train_transform) | 1 | 2023-10-23 18:23:22+00:00 | 2k |
camenduru/MiniGPT-v2-hf | minigpt4/models/base_model.py | [
{
"identifier": "download_cached_file",
"path": "minigpt4/common/dist_utils.py",
"snippet": "def download_cached_file(url, check_hash=True, progress=False):\n \"\"\"\n Download a file from a URL and cache it locally. If the file already exists, it is not downloaded again.\n If distributed, only... | import os
import logging
import contextlib
import numpy as np
import torch
import torch.nn as nn
from omegaconf import OmegaConf
from transformers import BertTokenizer, LlamaTokenizer
from transformers.models.llama.modeling_llama import LlamaForCausalLM
from peft import (
LoraConfig,
get_peft_model,
prepare... | 1,202 | """
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
class BaseModel(nn.Module):
"""Base class for models."""
def __init__(self):
... | """
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
class BaseModel(nn.Module):
"""Base class for models."""
def __init__(self):
... | return get_abs_path(cls.PRETRAINED_MODEL_CONFIG_DICT[model_type]) | 2 | 2023-10-15 19:54:22+00:00 | 2k |
deepghs/sdeval | sdeval/corrupt/aicorrupt.py | [
{
"identifier": "load_images",
"path": "sdeval/utils/images.py",
"snippet": "def _yield_images(images: ImagesTyping) -> Iterator[Image.Image]:\ndef load_images(images: ImagesTyping) -> List[Image.Image]:"
},
{
"identifier": "tqdm",
"path": "sdeval/utils/tqdm_.py",
"snippet": "def tqdm(*a... | import json
import numpy as np
from functools import lru_cache
from typing import Tuple, Optional, Mapping
from PIL import Image
from huggingface_hub import hf_hub_download
from imgutils.data import rgb_encode, ImageTyping, load_image
from imgutils.utils import open_onnx_model
from ..utils import ImagesTyping, load_ima... | 1,561 |
@lru_cache()
def _open_anime_aicop_meta(model_name: str):
"""
Open the meta information of the AI image corrupted detection model.
This function downloads and opens the meta information of the AI image corrupted detection model specified by the given model name using Hugging Face Hub.
:param model_na... | """
Overview:
AI image corrupt evaluation metrics.
"""
_DEFAULT_MODEL_NAME = 'caformer_s36_v0_focal'
@lru_cache()
def _open_anime_aicop_model(model_name: str):
"""
Open the AI image corrupted detection model.
This function downloads and opens the AI image corrupted detection model specified by the... | image_list = load_images(images) | 0 | 2023-10-18 03:35:52+00:00 | 2k |
WHUlwb/Assisted_learning | hrnet/hrnet.py | [
{
"identifier": "BN_MOMENTUM",
"path": "hrnet/backbone.py",
"snippet": "BN_MOMENTUM = 0.1\r"
},
{
"identifier": "hrnet_classification",
"path": "hrnet/backbone.py",
"snippet": "def hrnet_classification(backbone='hrnetv2_w18'):\r\n model = HighResolutionNet_Classification(num_classes=1... | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .backbone import BN_MOMENTUM, hrnet_classification
| 677 |
class HRnet_Backbone(nn.Module):
def __init__(self, in_channel, backbone = 'hrnetv2_w18'):
super(HRnet_Backbone, self).__init__()
self.model = hrnet_classification(backbone = backbone)
del self.model.incre_modules
del self.model.downsamp_modules
del self.model.... |
class HRnet_Backbone(nn.Module):
def __init__(self, in_channel, backbone = 'hrnetv2_w18'):
super(HRnet_Backbone, self).__init__()
self.model = hrnet_classification(backbone = backbone)
del self.model.incre_modules
del self.model.downsamp_modules
del self.model.... | nn.BatchNorm2d(last_inp_channels, momentum=BN_MOMENTUM),
| 0 | 2023-10-17 06:19:02+00:00 | 2k |
dagedarr/telegram-budget | handlers/change_info_handler.py | [
{
"identifier": "get_by_id",
"path": "core/crud.py",
"snippet": "async def get_by_id(\n model: ModelType,\n obj_id: int,\n session: AsyncSession\n) -> ModelType:\n \"\"\"\n Получение объекта по ID.\n\n Parameters:\n - model (ModelType): Тип модели SQLAlchemy.\n - obj_id (int): Ид... | from aiogram import F, Router
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery, Message
from sqlalchemy.ext.asyncio import AsyncSession
from core.crud import get_by_id, update
from filters import IsEndOnboardingFilter
from forms import RegistrationForm
from keyboards import set_info_ke... | 1,474 |
router = Router(name='change_info_router')
@router.callback_query(F.data == 'change_info')
async def change_info(callback: CallbackQuery):
"""Выводит Категории и Статистику и осльной функционал."""
await callback_message(
target=callback,
text='Изменить данные о себе',
|
router = Router(name='change_info_router')
@router.callback_query(F.data == 'change_info')
async def change_info(callback: CallbackQuery):
"""Выводит Категории и Статистику и осльной функционал."""
await callback_message(
target=callback,
text='Изменить данные о себе', | reply_markup=set_info_keyboard(), | 4 | 2023-10-23 17:30:24+00:00 | 2k |
nchen909/Pass-Tuning | evaluator/CodeBLEU/parser/DFG.py | [
{
"identifier": "remove_comments_and_docstrings",
"path": "evaluator/CodeBLEU/parser/utils.py",
"snippet": "def remove_comments_and_docstrings(source, lang):\n if lang in ['python']:\n \"\"\"\n Returns 'source' minus comments and docstrings.\n \"\"\"\n io_obj = StringIO(so... | from tree_sitter import Language, Parser
from .utils import (remove_comments_and_docstrings,
tree_to_token_index,
index_to_code_token,
tree_to_variable_index) | 1,245 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
def DFG_python(root_node,index_to_code,states):
assignment=['assignment','augmented_assignment','for_in_clause']
if_statement=['if_statement']
for_statement=['for_statement']
while_statement=['while_statement']
do_first_sta... | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
def DFG_python(root_node,index_to_code,states):
assignment=['assignment','augmented_assignment','for_in_clause']
if_statement=['if_statement']
for_statement=['for_statement']
while_statement=['while_statement']
do_first_sta... | indexs=tree_to_variable_index(name,index_to_code) | 3 | 2023-10-20 09:24:44+00:00 | 2k |
kavisha725/MBNSF | trajectory_estimation/mbnt.py | [
{
"identifier": "extract_clusters_dbscan",
"path": "utils/o3d_uitls.py",
"snippet": "def extract_clusters_dbscan(cloud, eps = 0.9, min_points=10, return_clusters= False, return_colored_pcd=False):\n pcl = copy.deepcopy(cloud)\n pcl = make_open3d_point_cloud(pcl)\n labels = np.array(\n ... | import os, glob
import argparse
import logging
import csv
import numpy as np
import torch
import sys
import pytorch3d.loss as p3dloss
from utils.general_utils import *
from utils.ntp_utils import *
from utils.o3d_uitls import extract_clusters_dbscan
from utils.sc_utils import spatial_consistency_loss | 1,338 | # Long-term trajectory estimation with MBNT.
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
logger = logging.getLogger(__name__)
def total_sc_loss(labels_t, label_ids, pc, pc_defored, d_thresh=0.03, max_points=3000):
loss_sc = None
for id in label_ids:
cluster = pc[labels_t == id]
... | # Long-term trajectory estimation with MBNT.
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
logger = logging.getLogger(__name__)
def total_sc_loss(labels_t, label_ids, pc, pc_defored, d_thresh=0.03, max_points=3000):
loss_sc = None
for id in label_ids:
cluster = pc[labels_t == id]
... | labels = extract_clusters_dbscan(pc_list[fid], eps = options.sc_cluster_eps, min_points=options.sc_cluster_min_points, return_clusters= False, return_colored_pcd=False) | 0 | 2023-10-16 07:21:12+00:00 | 2k |
cool-dev-guy/tkmoderngl | main.py | [
{
"identifier": "FramebufferImage",
"path": "tkmoderngl/framebuffer.py",
"snippet": "class FramebufferImage(ImageTk.PhotoImage):\n def __init__(self, master, ctx, size):\n super(FramebufferImage, self).__init__(Image.new('RGB', size, (0, 0, 0)))\n self.ctx = ctx\n self.fbo = self... | import tkinter as tk
import moderngl
import numpy as np
from tkmoderngl.framebuffer import FramebufferImage
from tkmoderngl.renderer import Canvas, PanTool | 1,014 | """
code from moderngl/examples
modified by : cool-dev-guy
"""
# the moderngl widget
class GlWidget(tk.Label):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.parent = args[0]
self._ctx = moderngl.create_standalone_context()
self._tkfbo = FramebufferImag... | """
code from moderngl/examples
modified by : cool-dev-guy
"""
# the moderngl widget
class GlWidget(tk.Label):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.parent = args[0]
self._ctx = moderngl.create_standalone_context()
self._tkfbo = FramebufferImag... | self._canvas = Canvas(self._ctx) | 1 | 2023-10-15 07:58:13+00:00 | 2k |
G3VV/Yank | index.py | [
{
"identifier": "start_token_thread",
"path": "util/spotify.py",
"snippet": "def start_token_thread():\n \n client_id = spotify_id\n client_secret = spotify_secret\n \n get_access_token(client_id, client_secret)"
},
{
"identifier": "start",
"path": "util/download.py",
"sni... | from quart import Quart, send_file
from util.spotify import start_token_thread
from util.download import start, start_playlist
from dotenv import load_dotenv
import threading
import re
import os
import json | 850 |
app = Quart(__name__)
load_dotenv()
port = os.environ.get("port")
@app.route('/track/<string:id>')
async def serve_audio(id):
filename = await start(id)
return await send_file(filename, mimetype='audio/mpeg')
@app.route('/')
async def serve_index():
return "online"
@app.route('/playlist/<string:id>')
a... |
app = Quart(__name__)
load_dotenv()
port = os.environ.get("port")
@app.route('/track/<string:id>')
async def serve_audio(id):
filename = await start(id)
return await send_file(filename, mimetype='audio/mpeg')
@app.route('/')
async def serve_index():
return "online"
@app.route('/playlist/<string:id>')
a... | filename = await start_playlist(id) | 2 | 2023-10-15 04:35:56+00:00 | 2k |
openfoodfacts/open-prices | app/models.py | [
{
"identifier": "Base",
"path": "app/db.py",
"snippet": ""
},
{
"identifier": "CurrencyEnum",
"path": "app/enums.py",
"snippet": "CURRENCIES = [(currency, currency) for currency in list_currencies()]\n NODE = \"NODE\"\n WAY = \"WAY\"\n RELATION = \"RELATION\"\n PRICE_TAG = \"... | from openfoodfacts import Flavor
from sqlalchemy import (
JSON,
BigInteger,
Boolean,
Column,
Date,
DateTime,
ForeignKey,
Integer,
Numeric,
String,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.sql... | 734 |
force_auto_coercion()
JSONVariant = JSON().with_variant(JSONB(), "postgresql")
class User(Base):
user_id = Column(String, primary_key=True, index=True)
token = Column(String, unique=True, index=True)
last_used = Column(DateTime(timezone=True))
price_count = Column(Integer, nullable=False, server_de... |
force_auto_coercion()
JSONVariant = JSON().with_variant(JSONB(), "postgresql")
class User(Base):
user_id = Column(String, primary_key=True, index=True)
token = Column(String, unique=True, index=True)
last_used = Column(DateTime(timezone=True))
price_count = Column(Integer, nullable=False, server_de... | type = Column(ChoiceType(ProofTypeEnum)) | 1 | 2023-10-21 14:02:15+00:00 | 2k |
krasnoukhov/homeassistant-smart-maic | custom_components/smart_maic/config_flow.py | [
{
"identifier": "DEVICE_NAME",
"path": "custom_components/smart_maic/const.py",
"snippet": "DEVICE_NAME = \"device_name\""
},
{
"identifier": "DEVICE_ID",
"path": "custom_components/smart_maic/const.py",
"snippet": "DEVICE_ID = \"devid\""
},
{
"identifier": "DEVICE_TYPE",
"pa... | import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from typing import Any
from homeassistant import config_entries
from homeassistant.components import mqtt
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import AbortFlow
from .const import (
... | 1,530 | """Config flow for Smart MAIC integration."""
from __future__ import annotations
_LOGGER = logging.getLogger(__name__)
USER_SCHEMA = vol.Schema(
{
vol.Required(IP_ADDRESS): cv.string,
vol.Required(PIN): cv.string,
vol.Required(DEVICE_NAME, default="Energy"): cv.string,
}
)
async ... | """Config flow for Smart MAIC integration."""
from __future__ import annotations
_LOGGER = logging.getLogger(__name__)
USER_SCHEMA = vol.Schema(
{
vol.Required(IP_ADDRESS): cv.string,
vol.Required(PIN): cv.string,
vol.Required(DEVICE_NAME, default="Energy"): cv.string,
}
)
async ... | coordinator = SmartMaicCoordinator(smart_maic, hass) | 7 | 2023-10-16 17:24:45+00:00 | 2k |
JoaoPedro9674/django-ledger | django_ledger/contrib/django_ledger_graphene/api.py | [
{
"identifier": "ChartOfAccountsModelType",
"path": "django_ledger/contrib/django_ledger_graphene/coa/schema.py",
"snippet": "class ChartOfAccountsModelType(DjangoObjectType):\n class Meta:\n model = ChartOfAccountModel\n fields = [\n 'uuid',\n 'slug',\n ... | import graphene
from django_ledger.contrib.django_ledger_graphene.coa.schema import ChartOfAccountsModelType
from django_ledger.contrib.django_ledger_graphene.entity.schema import EntityModelQuery, EntityModelType | 945 |
class Query(
EntityModelQuery,
# ChartOfAccountsModelQuery
# CustomerQuery,
# Bill_list_Query,
# Accountlist_Query,
# Bank_account_Query ,
# ChartOfAccountsQuery,
# UnitOfMeasureQuery,
# VendorsQuery,
# EntityUnitQuery,
# LedgerQuery,
# TransactionsQuery,
# ... |
class Query(
EntityModelQuery,
# ChartOfAccountsModelQuery
# CustomerQuery,
# Bill_list_Query,
# Accountlist_Query,
# Bank_account_Query ,
# ChartOfAccountsQuery,
# UnitOfMeasureQuery,
# VendorsQuery,
# EntityUnitQuery,
# LedgerQuery,
# TransactionsQuery,
# ... | ChartOfAccountsModelType | 0 | 2023-10-20 01:07:20+00:00 | 2k |
HLTCHKUST/InstructAlign | main_nlu_prompt.py | [
{
"identifier": "get_prompt",
"path": "nlu_prompt.py",
"snippet": "def get_prompt(prompt_lang):\n if prompt_lang == 'EN':\n return DATA_TO_EN_PROMPT\n elif prompt_lang == 'EN2':\n return DATA_TO_EN2_PROMPT\n elif prompt_lang == 'EN3':\n return DATA_TO_EN3_PROMPT\n elif p... | import os, sys
import csv
import pandas as pd
import torch
import torch.nn.functional as F
from os.path import exists
from numpy import argmax
from tqdm import tqdm
from sklearn.metrics import f1_score, accuracy_score
from nlu_prompt import get_prompt
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoM... | 1,378 | """nusacrowd zero-shot prompt.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Ru8DyS2ALWfRdkjOPHj-KNjw6Pfa44Nd
"""
#!pip install git+https://github.com/IndoNLP/nusa-crowd.git@release_exp
#!pip install transformers
#!pip install sentencepiece
... | """nusacrowd zero-shot prompt.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Ru8DyS2ALWfRdkjOPHj-KNjw6Pfa44Nd
"""
#!pip install git+https://github.com/IndoNLP/nusa-crowd.git@release_exp
#!pip install transformers
#!pip install sentencepiece
... | nlu_datasets = load_nlu_tasks() | 3 | 2023-10-24 07:46:05+00:00 | 2k |
ambient-innovation/django-migration-zero | tests/services/test_deployment.py | [
{
"identifier": "InvalidMigrationTreeError",
"path": "django_migration_zero/exceptions.py",
"snippet": "class InvalidMigrationTreeError(RuntimeError):\n pass"
},
{
"identifier": "MigrationZeroConfigurationManager",
"path": "django_migration_zero/managers.py",
"snippet": "class Migrati... | from logging import Logger
from unittest import mock
from django.test import TestCase
from django.utils import timezone
from freezegun import freeze_time
from django_migration_zero.exceptions import InvalidMigrationTreeError
from django_migration_zero.managers import MigrationZeroConfigurationManager
from django_migrat... | 1,158 |
@freeze_time("2023-06-26")
class DatabasePreparationServiceTest(TestCase):
config: MigrationZeroConfiguration
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.service = DatabasePreparationService()
cls.config, _ = MigrationZeroConfiguration.objects.get_or_create... |
@freeze_time("2023-06-26")
class DatabasePreparationServiceTest(TestCase):
config: MigrationZeroConfiguration
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.service = DatabasePreparationService()
cls.config, _ = MigrationZeroConfiguration.objects.get_or_create... | @mock.patch.object(MigrationZeroConfigurationManager, "fetch_singleton", return_value=None) | 1 | 2023-10-18 12:51:36+00:00 | 2k |
Lucchetto/model_converter | src/api.py | [
{
"identifier": "setup_pub_key",
"path": "src/licensing.py",
"snippet": "def setup_pub_key() -> (rsa.RSAPublicKey | None):\n str = os.environ.get('LICENSING_PUB_KEY')\n if str:\n logging.info(\"LICENSING_PUB_KEY defined, Play Store licensing validation will be performed\")\n key = se... | from enum import Enum
from flask import Flask, Response, jsonify, request, send_file
from src.licensing import setup_pub_key, validate_license
from .converter import UnsupportedModelArch, convert_pth_to_onnx
import logging
import os
import uuid | 972 |
class ApiErrorReason(Enum):
UNSUPPORTED_ARCH = "UNSUPPORTED_ARCH"
INVALID_LICENSE = 'INVALID_LICENSE'
UNSUPPORTED_FORMAT = 'UNSUPPORTED_FORMAT'
UNKNOWN = 'UNKNOWN'
def api_error(reason: ApiErrorReason):
if reason == ApiErrorReason.INVALID_LICENSE:
status_code = 401
else:
stat... |
class ApiErrorReason(Enum):
UNSUPPORTED_ARCH = "UNSUPPORTED_ARCH"
INVALID_LICENSE = 'INVALID_LICENSE'
UNSUPPORTED_FORMAT = 'UNSUPPORTED_FORMAT'
UNKNOWN = 'UNKNOWN'
def api_error(reason: ApiErrorReason):
if reason == ApiErrorReason.INVALID_LICENSE:
status_code = 401
else:
stat... | pub_key = setup_pub_key() | 0 | 2023-10-18 18:18:55+00:00 | 2k |
hpsaturn/pilauncher | main.py | [
{
"identifier": "GuiManager",
"path": "gui.py",
"snippet": "class GuiManager():\n def __init__(self):\n self.am = AppManager()\n self.wlevel = 0\n self.showApp()\n\n def showApp(self):\n if self.wlevel == 0:\n print(self.am.getCurrentApp().name)\n ... | import time
import subprocess
import threading
import RPi.GPIO as GPIO
from gui import GuiManager
from display import Display | 1,214 |
BTNLFT = 23
BTNRGT = 6
onAppStatusTask = False
onSystemStatsTask = False
isBtnRgtPresed = False
isBtnLftPresed = False
onStats = False
# GUI Apps Manager
gui = GuiManager()
cfg = gui.getConfig()
|
BTNLFT = 23
BTNRGT = 6
onAppStatusTask = False
onSystemStatsTask = False
isBtnRgtPresed = False
isBtnLftPresed = False
onStats = False
# GUI Apps Manager
gui = GuiManager()
cfg = gui.getConfig() | dsp = Display() | 1 | 2023-10-23 20:21:51+00:00 | 2k |
CAMeL-Lab/camel_parser | src/initialize_disambiguator/disambiguator_interface.py | [
{
"identifier": "log",
"path": "src/logger.py",
"snippet": "def log(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n try:\n\n start_time = time.time()\n result = func(*args, **kwargs)\n end_time = time.time()\n \n with ... | from typing import Union
from camel_tools.morphology.database import MorphologyDB
from camel_tools.morphology.analyzer import Analyzer
from camel_tools.disambig.bert import BERTUnfactoredDisambiguator
from src.logger import log
from src.initialize_disambiguator.bert_disambiguator import create_bert_disambiguator
from s... | 693 |
def set_up_analyzer(morphology_db: str) -> Analyzer:
# used to initialize an Analyzer with ADD_PROP backoff
# db = MorphologyDB.builtin_db('calima-msa-s31')
db_type = None if morphology_db == 'r13' else morphology_db
db = MorphologyDB.builtin_db(db_name=db_type)
return Analyzer(db=db, backoff='AD... |
def set_up_analyzer(morphology_db: str) -> Analyzer:
# used to initialize an Analyzer with ADD_PROP backoff
# db = MorphologyDB.builtin_db('calima-msa-s31')
db_type = None if morphology_db == 'r13' else morphology_db
db = MorphologyDB.builtin_db(db_name=db_type)
return Analyzer(db=db, backoff='AD... | model = create_bert_disambiguator(analyzer) | 1 | 2023-10-21 10:39:28+00:00 | 2k |
JerBouma/FinancePortfolio | financeportfolio/portfolio_controller.py | [
{
"identifier": "excel_model",
"path": "financeportfolio/excel_model.py",
"snippet": "def create_portfolio_performance_excel_report(\n writer: pd.ExcelWriter, dataset: pd.DataFrame, sheet_name: str, currency: str = \"$\"\n):\ndef create_transactions_performance_excel_report(\n writer: pd.ExcelWrit... | import pandas as pd
from financetoolkit import Toolkit
from financeportfolio import excel_model, helpers, portfolio_model
| 1,298 | """Portfolio Module"""
# pylint: disable=too-many-instance-attributes,abstract-class-instantiated,
# pylint: disable=too-few-public-methods,protected-access,too-many-lines
class Portfolio:
"""
A class for managing and analyzing your portfolio.
This class provides functionality for loadin... | """Portfolio Module"""
# pylint: disable=too-many-instance-attributes,abstract-class-instantiated,
# pylint: disable=too-few-public-methods,protected-access,too-many-lines
class Portfolio:
"""
A class for managing and analyzing your portfolio.
This class provides functionality for loadin... | configuration_file = helpers.download_yaml_configuration(example=True)
| 1 | 2023-10-15 09:16:04+00:00 | 2k |
S2-group/UPISAS | UPISAS/tests/upisas/test_exemplar.py | [
{
"identifier": "DockerImageNotFoundOnDockerHub",
"path": "UPISAS/exceptions.py",
"snippet": "class DockerImageNotFoundOnDockerHub(UPISASException):\n pass"
},
{
"identifier": "Exemplar",
"path": "UPISAS/exemplar.py",
"snippet": "class Exemplar(ABC):\n \"\"\"\n A class which enc... | import unittest
from UPISAS.exceptions import DockerImageNotFoundOnDockerHub
from UPISAS.exemplar import Exemplar
from UPISAS.exemplars.demo_exemplar import DemoExemplar | 1,392 |
class TestExemplar(unittest.TestCase):
"""
Test cases for the Exemplar class using the DemoExemplar.
"""
def setUp(self):
self.exemplar = None
def tearDown(self):
if self.exemplar and self.exemplar.exemplar_container:
self.exemplar.stop_container()
def test_init_... |
class TestExemplar(unittest.TestCase):
"""
Test cases for the Exemplar class using the DemoExemplar.
"""
def setUp(self):
self.exemplar = None
def tearDown(self):
if self.exemplar and self.exemplar.exemplar_container:
self.exemplar.stop_container()
def test_init_... | self.exemplar = DemoExemplar(auto_start=False) | 2 | 2023-10-15 12:46:54+00:00 | 2k |
developerlin/excelchat-streamlit | Home.py | [
{
"identifier": "CustomChartsMiddleware",
"path": "middleware/base.py",
"snippet": "class CustomChartsMiddleware(ChartsMiddleware):\n def run(self, code: str) -> str:\n # code = super().run(code)\n\n processed = []\n for line in code.split(\"\\n\"):\n if line.find(\"pl... | import io
import logging
import uuid
import matplotlib
import pandas as pd
import streamlit as st
from pathlib import Path
from typing import Dict
from pandasai import SmartDataframe, Agent, Config
from pandasai.callbacks import StdoutCallback
from pandasai.helpers import Logger
from middleware.base import CustomCharts... | 1,300 |
logger = Logger()
matplotlib.rc_file("./.matplotlib/.matplotlibrc");
# page settings
st.set_page_config(page_title="Excel Chat", layout="wide")
st.header("What ExcelChat can do?")
st.text("ExcelChat is a lightweight data analysis app powered by LLM, showcasing how LLM can revolutionize the future"
"of dat... |
logger = Logger()
matplotlib.rc_file("./.matplotlib/.matplotlibrc");
# page settings
st.set_page_config(page_title="Excel Chat", layout="wide")
st.header("What ExcelChat can do?")
st.text("ExcelChat is a lightweight data analysis app powered by LLM, showcasing how LLM can revolutionize the future"
"of dat... | "generate_python_code": get_prompt_template() | 5 | 2023-10-20 00:58:45+00:00 | 2k |
ZiaWang/jqtrade | jqtrade/account/portfolio.py | [
{
"identifier": "OrderSide",
"path": "jqtrade/account/order.py",
"snippet": "class OrderSide(Enum):\n # 多仓\n long = \"long\"\n\n # 空仓\n short = \"short\"\n\n @classmethod\n def is_valid_side(cls, side):\n return side in cls.__members__\n\n @classmethod\n def get_side(cls, ... | from .order import OrderSide
from .api import UserPosition, UserPositionDict | 729 | # -*- coding: utf-8 -*-
class Portfolio(object):
""" 账户资金/持仓信息聚合类 """
def __init__(self, account):
self.__account = account
@property
def long_positions(self):
| # -*- coding: utf-8 -*-
class Portfolio(object):
""" 账户资金/持仓信息聚合类 """
def __init__(self, account):
self.__account = account
@property
def long_positions(self): | positions = UserPositionDict(OrderSide.long) | 0 | 2023-10-24 01:34:27+00:00 | 2k |
Glasgow-AI4BioMed/GenKIE | data/mm_data/vqa_gen_dataset.py | [
{
"identifier": "data_utils",
"path": "data/data_utils.py",
"snippet": "def infer_language_pair(path):\ndef collate_tokens(\n values,\n pad_idx,\n eos_idx=None,\n left_pad=False,\n move_eos_to_beginning=False,\n pad_to_length=None,\n pad_to_multiple=1,\n pad_to_bsz=None,\n):\n ... | from io import BytesIO
from torchvision import transforms
from PIL import Image, ImageFile
from data import data_utils
from data.ofa_dataset import OFADataset
import logging
import warnings
import numpy as np
import torch
import base64 | 1,291 | # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
ImageFile.LOAD_TRUNCATED_IMAGES = True
ImageFile.MAX_IMAGE_PIXELS = None
Image.MAX_IMAGE_PIXELS = None
logger = logging.getLogger(__name__)
warn... | # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
ImageFile.LOAD_TRUNCATED_IMAGES = True
ImageFile.MAX_IMAGE_PIXELS = None
Image.MAX_IMAGE_PIXELS = None
logger = logging.getLogger(__name__)
warn... | return data_utils.collate_tokens( | 0 | 2023-10-20 20:01:42+00:00 | 2k |
ArnaudParant/sel | tests/test_sel.py | [
{
"identifier": "elastic",
"path": "scripts/elastic.py",
"snippet": "def options():\ndef create_index(filepath, schema_filepath, index, overwrite=False):\ndef _delete_index(elastic, index):\ndef loads_ndjson(fd):\ndef insert(elastic, index, data):\ndef _create_index(elastic, index, schema_filepath):\nde... | import pytest
import json
import test_utils
from scripts import elastic
from sel import utils | 750 |
TEST_INDEX_FILE = "/tests/data/sample_2017.json"
TEST_SCHEMA_FILE = "/scripts/schema.json"
TEST_INDEX = "test_index"
class TestSEL:
@pytest.fixture(scope="function", autouse=True)
def init(self):
elastic.create_index(TEST_INDEX_FILE, TEST_SCHEMA_FILE, TEST_INDEX, overwrite=True)
def __clean... |
TEST_INDEX_FILE = "/tests/data/sample_2017.json"
TEST_SCHEMA_FILE = "/scripts/schema.json"
TEST_INDEX = "test_index"
class TestSEL:
@pytest.fixture(scope="function", autouse=True)
def init(self):
elastic.create_index(TEST_INDEX_FILE, TEST_SCHEMA_FILE, TEST_INDEX, overwrite=True)
def __clean... | expected = utils.get_lastest_sub_data(res["results"]["aggregations"][aggreg_key])["buckets"] | 1 | 2023-10-16 09:03:13+00:00 | 2k |
Qualcomm-AI-research/outlier-free-transformers | quantization/quantizers/uniform_quantizers.py | [
{
"identifier": "QuantizerBase",
"path": "quantization/quantizers/base_quantizers.py",
"snippet": "class QuantizerBase(nn.Module):\n def __init__(self, n_bits, *args, per_channel=False, act_quant=False, **kwargs):\n super().__init__(*args, **kwargs)\n self.n_bits = n_bits\n self.... | import torch
from quantization.quantizers.base_quantizers import QuantizerBase
from quantization.quantizers.quantizer_utils import (
QuantizerNotInitializedError,
round_ste_func,
scale_grad_func,
) | 918 | # Copyright (c) 2023 Qualcomm Technologies, Inc.
# All Rights Reserved.
class AsymmetricUniformQuantizer(QuantizerBase):
"""
PyTorch Module that implements Asymmetric Uniform Quantization using STE.
Quantizes its argument in the forward pass, passes the gradient 'straight
through' on the backward pas... | # Copyright (c) 2023 Qualcomm Technologies, Inc.
# All Rights Reserved.
class AsymmetricUniformQuantizer(QuantizerBase):
"""
PyTorch Module that implements Asymmetric Uniform Quantization using STE.
Quantizes its argument in the forward pass, passes the gradient 'straight
through' on the backward pas... | zero_point = round_ste_func(self.zero_float) | 1 | 2023-10-23 15:59:50+00:00 | 2k |
QgZhan/ESVAE | main_ann_ae.py | [
{
"identifier": "AverageMeter",
"path": "utils.py",
"snippet": "class AverageMeter(object):\r\n \"\"\"Computes and stores the average and current value\"\"\"\r\n def __init__(self):\r\n self.reset()\r\n\r\n def reset(self):\r\n self.val = 0\r\n self.avg = 0\r\n self.... | import os
import os.path
import numpy as np
import logging
import argparse
import pycuda.driver as cuda
import torch
import torchvision
import models.ann_ae as ann_ae
from torch.nn.utils import clip_grad_norm_
from torch.nn.utils import clip_grad_value_
from torch.utils.tensorboard import SummaryWriter
from... | 663 |
max_accuracy = 0
min_loss = 1000
def train(network, trainloader, opti, epoch):
|
max_accuracy = 0
min_loss = 1000
def train(network, trainloader, opti, epoch):
| loss_meter = AverageMeter()
| 0 | 2023-10-23 07:33:27+00:00 | 2k |
iesl/softmax_CPR_recommend | recbole/model/sequential_recommender/sasrec.py | [
{
"identifier": "SequentialRecommender",
"path": "recbole/model/abstract_recommender.py",
"snippet": "class SequentialRecommender(AbstractRecommender):\n \"\"\"\n This is a abstract sequential recommender. All the sequential model should implement This class.\n \"\"\"\n type = ModelType.SEQU... | import sys
import torch
import torch.nn.functional as F
import math
from torch import nn
from recbole.model.abstract_recommender import SequentialRecommender
from recbole.model.layers import TransformerEncoder
from recbole.model.loss import BPRLoss | 1,321 | # -*- coding: utf-8 -*-
# @Time : 2020/9/18 11:33
# @Author : Hui Wang
# @Email : hui.wang@ruc.edu.cn
"""
SASRec
################################################
Reference:
Wang-Cheng Kang et al. "Self-Attentive Sequential Recommendation." in ICDM 2018.
Reference:
https://github.com/kang205/SASRec
"""... | # -*- coding: utf-8 -*-
# @Time : 2020/9/18 11:33
# @Author : Hui Wang
# @Email : hui.wang@ruc.edu.cn
"""
SASRec
################################################
Reference:
Wang-Cheng Kang et al. "Self-Attentive Sequential Recommendation." in ICDM 2018.
Reference:
https://github.com/kang205/SASRec
"""... | class SASRec(SequentialRecommender): | 0 | 2023-10-21 16:31:44+00:00 | 2k |
timapage/pyqt6-yolov8 | src/models/detection/yolov8_detector_onnx.py | [
{
"identifier": "DetectorBase",
"path": "src/models/detection/detector_base.py",
"snippet": "class DetectorBase(YoloPredictorBase):\n def draw_results(image, model_results):\n FONT_SCALE = 1e-3 \n THICKNESS_SCALE = 6e-4 "
},
{
"identifier": "ModelError",
"path": "src... | import numpy as np
import cv2 as cv
from onnxruntime import InferenceSession
from src.models.detection.detector_base import DetectorBase, Model
from src.models.base.yolov8_base import ModelError
from src.utils.boxes import xywh2xyxy, multiclass_nms_class_agnostic
from src.utils.general import get_classes | 648 |
class YoloDetector(DetectorBase):
def __init__(self):
self._model = None
def init(self, model_path, class_txt_path, confidence_threshold=0.3, iou_threshold=0.45):
|
class YoloDetector(DetectorBase):
def __init__(self):
self._model = None
def init(self, model_path, class_txt_path, confidence_threshold=0.3, iou_threshold=0.45): | _class_names = get_classes(class_txt_path) | 4 | 2023-10-18 09:21:01+00:00 | 2k |
OthersideAI/self-operating-computer | operate/main.py | [
{
"identifier": "ANSI_BRIGHT_MAGENTA",
"path": "operate/utils/style.py",
"snippet": "ANSI_BRIGHT_MAGENTA = \"\\033[95m\" if supports_ansi() else \"\" # Bright magenta text"
},
{
"identifier": "main",
"path": "operate/dialog.py",
"snippet": "def main(model, terminal_prompt, voice_mode=Fa... | import argparse
from operate.utils.style import ANSI_BRIGHT_MAGENTA
from operate.dialog import main | 1,350 | """
Self-Operating Computer
"""
def main_entry():
parser = argparse.ArgumentParser(
description="Run the self-operating-computer with a specified model."
)
parser.add_argument(
"-m",
"--model",
help="Specify the model to use",
required=False,
default="gpt-4"... | """
Self-Operating Computer
"""
def main_entry():
parser = argparse.ArgumentParser(
description="Run the self-operating-computer with a specified model."
)
parser.add_argument(
"-m",
"--model",
help="Specify the model to use",
required=False,
default="gpt-4"... | main( | 1 | 2023-11-04 03:13:45+00:00 | 2k |
netease-youdao/EmotiVoice | frontend.py | [
{
"identifier": "g2p_cn",
"path": "frontend_cn.py",
"snippet": "def split_py(py):\ndef has_chinese_punctuation(text):\ndef has_english_punctuation(text):\ndef number_to_chinese(number):\ndef tn_chinese(text):\ndef g2p_cn(text):"
},
{
"identifier": "ROOT_DIR",
"path": "frontend_en.py",
"s... | import re
import sys
from frontend_cn import g2p_cn, re_digits, tn_chinese
from frontend_en import ROOT_DIR, read_lexicon, G2p, get_eng_phoneme
from os.path import isfile | 865 | # Copyright 2023, YOUDAO
#
# 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, s... | # Copyright 2023, YOUDAO
#
# 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, s... | g2p = G2p() | 1 | 2023-11-08 10:15:27+00:00 | 2k |
daveshap/OpenAI_Agent_Swarm | agents/tool_maker/tool_user.py | [
{
"identifier": "chat",
"path": "shared/utils.py",
"snippet": "def chat(client, thread, assistant, functions):\n while True:\n user_message = input(\"You: \")\n\n # add user message to thread\n thread_message = client.beta.threads.messages.create(\n thread.id,\n ... | import os
import json
from shared.utils import chat as chat_loop
from shared.openai_config import get_openai_client | 1,171 | """
Create an assistant using the tools from tool_creator using the assistant creation API
"""
client = get_openai_client()
def create_tool_user(assistant_details):
# create the assistant
tool_user = client.beta.assistants.create(**assistant_details["build_params"])
print(f"Created assistant {tool_use... | """
Create an assistant using the tools from tool_creator using the assistant creation API
"""
client = get_openai_client()
def create_tool_user(assistant_details):
# create the assistant
tool_user = client.beta.assistants.create(**assistant_details["build_params"])
print(f"Created assistant {tool_use... | chat_loop(client, thread, tool_user, functions) | 1 | 2023-11-07 23:12:05+00:00 | 2k |
S-LoRA/S-LoRA | slora/common/basemodel/layer_infer/base_layer_infer.py | [
{
"identifier": "mark_cost_time",
"path": "slora/utils/infer_utils.py",
"snippet": "def mark_cost_time(func_name):\n def inner_func(func):\n def time_func(*args, **kwargs):\n if dist.get_rank() in [0, 1] and is_show_cost_time:\n torch.cuda.synchronize()\n ... | from slora.utils.infer_utils import mark_cost_time
from slora.common.basemodel.infer_struct import InferStateInfo
from slora.common.basemodel.layer_weights.base_layer_weight import BaseLayerWeight | 707 |
class BaseLayerInfer:
def __init__(self) -> None:
pass
|
class BaseLayerInfer:
def __init__(self) -> None:
pass
| @mark_cost_time("pre context forward") # dont to remove this, will make performence down, did not know why | 0 | 2023-11-05 04:08:36+00:00 | 2k |
disler/multi-agent-postgres-data-analytics | postgres_da_ai_agent/modules/orchestrator.py | [
{
"identifier": "AgentInstruments",
"path": "postgres_da_ai_agent/agents/instruments.py",
"snippet": "class AgentInstruments:\n \"\"\"\n Base class for multli-agent instruments that are tools, state, and functions that an agent can use across the lifecycle of conversations\n \"\"\"\n\n def _... | import dataclasses
import json
import autogen
from typing import List, Optional, Tuple
from postgres_da_ai_agent.agents.instruments import AgentInstruments
from postgres_da_ai_agent.modules import llm
from postgres_da_ai_agent.types import Chat, ConversationResult | 705 |
class Orchestrator:
"""
Orchestrators manage conversations between multi-agent teams.
"""
def __init__(
self,
name: str,
agents: List[autogen.ConversableAgent],
|
class Orchestrator:
"""
Orchestrators manage conversations between multi-agent teams.
"""
def __init__(
self,
name: str,
agents: List[autogen.ConversableAgent], | instruments: AgentInstruments, | 0 | 2023-11-04 20:15:46+00:00 | 2k |
fleet-ai/context | utils/ai.py | [
{
"identifier": "OPENAI_MODELS",
"path": "constants/cli.py",
"snippet": "OPENAI_MODELS = [\n \"gpt-4-1106-preview\",\n \"gpt-4\",\n \"gpt-3.5-turbo\",\n \"gpt-3.5-turbo-16k\",\n]"
},
{
"identifier": "SYSTEM_PROMPT",
"path": "constants/ai.py",
"snippet": "SYSTEM_PROMPT = \"\"\... | import os
import json
import tiktoken
import openai
import requests
from openai import OpenAI
from constants.cli import OPENAI_MODELS
from constants.ai import SYSTEM_PROMPT, PROMPT, API_URL | 874 | # pylint: disable=W0707
# pylint: disable=W0719
def retrieve(query, k=10, filters=None):
"""Retrieves and returns dict.
Args:
query (str): User query to pass in
k (int, optional): number of results passed back. Defaults to 10.
filters (dict, optional): Filters to apply to the query.... | # pylint: disable=W0707
# pylint: disable=W0719
def retrieve(query, k=10, filters=None):
"""Retrieves and returns dict.
Args:
query (str): User query to pass in
k (int, optional): number of results passed back. Defaults to 10.
filters (dict, optional): Filters to apply to the query.... | url = f"{API_URL}/query" | 3 | 2023-11-02 07:07:13+00:00 | 2k |
OpenBMB/ProAgent | ProAgent/agent/gpt4_function.py | [
{
"identifier": "logger",
"path": "ProAgent/loggers/logs.py",
"snippet": "class JsonFileHandler(logging.FileHandler):\nclass JsonFormatter(logging.Formatter):\nclass Logger(metaclass=Singleton):\nclass TypingConsoleHandler(logging.StreamHandler):\nclass ConsoleHandler(logging.StreamHandler):\nclass Auto... | import logging
import json
from typing import List, Dict
from colorama import Fore, Style
from ProAgent.loggers.logs import logger
from ProAgent.agent.utils import _chat_completion_request | 849 |
class OpenAIFunction():
def __init__(self):
pass
def parse(self, **args):
"""
Parses the given arguments by making a chat completion request.
Args:
**args: The keyword arguments to be passed to the chat completion request.
Returns:
Tuple: A t... |
class OpenAIFunction():
def __init__(self):
pass
def parse(self, **args):
"""
Parses the given arguments by making a chat completion request.
Args:
**args: The keyword arguments to be passed to the chat completion request.
Returns:
Tuple: A t... | logger._log(f"{Fore.RED} Retry for the {retry_time}'th time{Style.RESET_ALL}") | 0 | 2023-11-03 01:20:14+00:00 | 2k |
LLaVA-VL/LLaVA-Plus-Codebase | serve/blip2grounding_worker.py | [
{
"identifier": "WORKER_HEART_BEAT_INTERVAL",
"path": "serve/constants.py",
"snippet": "WORKER_HEART_BEAT_INTERVAL = int(os.getenv(\"FASTCHAT_WORKER_HEART_BEAT_INTERVAL\", 45))"
},
{
"identifier": "ErrorCode",
"path": "serve/constants.py",
"snippet": "class ErrorCode(IntEnum):\n \"\"\... | import sys, os
import argparse
import asyncio
import dataclasses
import logging
import json
import os
import sys
import time
import threading
import uuid
import base64
import numpy as np
import requests
import groundingdino.datasets.transforms as T
import pycocotools.mask as mask_util
import torch
import torch.nn.funct... | 1,147 | """
A model worker executes the model.
"""
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
try:
except ImportError:
GB = 1 << 30
now_file_name = os.__file__
logdir = "logs/workers/"
os.makedirs(logdir, exist_ok=True)
logfile = os.path.join(logdir, f"{now_file_name}.log")
worker_id = str(uuid... | """
A model worker executes the model.
"""
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
try:
except ImportError:
GB = 1 << 30
now_file_name = os.__file__
logdir = "logs/workers/"
os.makedirs(logdir, exist_ok=True)
logfile = os.path.join(logdir, f"{now_file_name}.log")
worker_id = str(uuid... | logger = build_logger(now_file_name, logfile) | 3 | 2023-11-07 13:06:02+00:00 | 2k |
opendilab/LLMRiddles | llmriddles/questions/level2.py | [
{
"identifier": "register_question",
"path": "llmriddles/questions/question.py",
"snippet": "def register_question(text: Union[Mapping[str, str], str],\n checkers: Union[Mapping[str, SingleLangCheckerTyping], MultiLangCheckerTyping],\n name=Union[Mapping[str, st... | import re
import sympy
from typing import Optional, Tuple
from .question import register_question
from .math_tools import get_all_numbers | 679 |
CN_TEXT_1 = """
第二章第一题(质数长度),你需要提出一个字数是质数的问题,使回答的长度刚好是它的下一个质数。
"""
EN_TEXT_1 = """
For the first question in chapter 2, You need to come up with a question that has a prime number of words, so the answer's length is exactly the next prime number.
"""
def _is_prime(v):
return sympy.isprime(v)
def _next_prime(... |
CN_TEXT_1 = """
第二章第一题(质数长度),你需要提出一个字数是质数的问题,使回答的长度刚好是它的下一个质数。
"""
EN_TEXT_1 = """
For the first question in chapter 2, You need to come up with a question that has a prime number of words, so the answer's length is exactly the next prime number.
"""
def _is_prime(v):
return sympy.isprime(v)
def _next_prime(... | register_question( | 0 | 2023-11-07 03:09:55+00:00 | 2k |
codefuse-ai/CodeFuse-ModelCache | modelcache/manager/vector_data/manager.py | [
{
"identifier": "NotFoundError",
"path": "modelcache/utils/error.py",
"snippet": "class NotFoundError(CacheError):\n \"\"\"Raise when getting an unsupported store.\"\"\"\n def __init__(self, store_type, current_type_name):\n super().__init__(f\"Unsupported ${store_type}: {current_type_name}... | from modelcache.utils.error import NotFoundError, ParamError
from modelcache.manager.vector_data.milvus import Milvus
from modelcache.manager.vector_data.faiss import Faiss
from modelcache.manager.vector_data.chroma import Chromadb
from modelcache.manager.vector_data.hnsw... | 924 | # -*- coding: utf-8 -*-
TOP_K = 1
FAISS_INDEX_PATH = "faiss.index"
DIMENSION = 0
MILVUS_HOST = "localhost"
MILVUS_PORT = 19530
MILVUS_USER = ""
MILVUS_PSW = ""
MILVUS_SECURE = False
MILVUS_INDEX_PARAMS = {
"metric_type": "L2",
"index_type": "HNSW",
"params": {"M": 8, "efConstruction": 64},
}
COLLECTION_NA... | # -*- coding: utf-8 -*-
TOP_K = 1
FAISS_INDEX_PATH = "faiss.index"
DIMENSION = 0
MILVUS_HOST = "localhost"
MILVUS_PORT = 19530
MILVUS_USER = ""
MILVUS_PSW = ""
MILVUS_SECURE = False
MILVUS_INDEX_PARAMS = {
"metric_type": "L2",
"index_type": "HNSW",
"params": {"M": 8, "efConstruction": 64},
}
COLLECTION_NA... | raise NotFoundError("vector store", name) | 0 | 2023-11-01 01:56:10+00:00 | 2k |
ForceFledgling/proxyhub | tests/test_utils.py | [
{
"identifier": "BadStatusLine",
"path": "proxyhub/errors.py",
"snippet": "class BadStatusLine(Exception):\n errmsg = 'bad_status_line'"
},
{
"identifier": "get_all_ip",
"path": "proxyhub/utils.py",
"snippet": "def get_all_ip(page):\n # TODO: add IPv6 support\n return set(IPPatt... | import pytest
from proxyhub.errors import BadStatusLine
from proxyhub.utils import (
get_all_ip,
get_status_code,
parse_headers,
parse_status_line,
) | 747 |
def test_get_all_ip():
page = "abc127.0.0.1:80abc127.0.0.1xx127.0.0.2:8080h"
assert get_all_ip(page) == {'127.0.0.1', '127.0.0.2'}
def test_get_status_code():
assert get_status_code('HTTP/1.1 200 OK\r\n') == 200
assert get_status_code('<html>123</html>\r\n') == 400
assert get_status_code(b'HTTP... |
def test_get_all_ip():
page = "abc127.0.0.1:80abc127.0.0.1xx127.0.0.2:8080h"
assert get_all_ip(page) == {'127.0.0.1', '127.0.0.2'}
def test_get_status_code():
assert get_status_code('HTTP/1.1 200 OK\r\n') == 200
assert get_status_code('<html>123</html>\r\n') == 400
assert get_status_code(b'HTTP... | assert parse_status_line('HTTP/1.1 200 OK') == { | 4 | 2023-11-05 13:28:57+00:00 | 2k |
WithSecureLabs/IceKube | icekube/cli.py | [
{
"identifier": "config",
"path": "icekube/config.py",
"snippet": "class Neo4j(TypedDict):\nclass Config(TypedDict):"
},
{
"identifier": "create_indices",
"path": "icekube/icekube.py",
"snippet": "def create_indices():\n for resource in api_resources():\n if \"list\" not in res... | import json
import logging
import typer
from pathlib import Path
from typing import Iterator, List, Optional, cast
from icekube.config import config
from icekube.icekube import (
create_indices,
enumerate_resource_kind,
generate_relationships,
purge_neo4j,
remove_attack_paths,
setup_attack_paths... | 1,369 |
app = typer.Typer()
IGNORE_DEFAULT = "events,componentstatuses"
@app.command()
def run(
ignore: str = typer.Option(
IGNORE_DEFAULT,
help="Names of resource types to ignore",
),
):
enumerate(ignore)
attack_path()
@app.command()
def enumerate(
ignore: str = typer.Option(
... |
app = typer.Typer()
IGNORE_DEFAULT = "events,componentstatuses"
@app.command()
def run(
ignore: str = typer.Option(
IGNORE_DEFAULT,
help="Names of resource types to ignore",
),
):
enumerate(ignore)
attack_path()
@app.command()
def enumerate(
ignore: str = typer.Option(
... | remove_attack_paths() | 5 | 2023-11-02 13:54:21+00:00 | 2k |
IAAR-Shanghai/UHGEval | tests/llm/test_api.py | [
{
"identifier": "Baichuan2_53B_Chat",
"path": "uhgeval/llm/api.py",
"snippet": "class Baichuan2_53B_Chat(BaseLLM):\n def request(self, query) -> str:\n import time\n url = conf.Baichuan2_53B_url\n api_key = conf.Baichuan2_53B_api_key\n secret_key = conf.Baichuan2_53B_secre... | import unittest
from uhgeval.llm.api import (
Baichuan2_53B_Chat,
GPT,
) | 831 | # @Author : Shichao Song
# @Email : song.shichao@outlook.com
class TestBaichuan253BChat(unittest.TestCase):
def setUp(self):
self.model = Baichuan2_53B_Chat(temperature=0.1)
def test_request(self):
query = "How are you?"
response = self.model.request(query)
self.assertIsIn... | # @Author : Shichao Song
# @Email : song.shichao@outlook.com
class TestBaichuan253BChat(unittest.TestCase):
def setUp(self):
self.model = Baichuan2_53B_Chat(temperature=0.1)
def test_request(self):
query = "How are you?"
response = self.model.request(query)
self.assertIsIn... | self.gpt35 = GPT(model_name='gpt-3.5-turbo', temperature=0.1) | 1 | 2023-11-06 11:46:22+00:00 | 2k |
mobiusml/hqq | examples/lora/train_hqq_lora_example.py | [
{
"identifier": "HQQModelForCausalLM",
"path": "hqq/engine/hf.py",
"snippet": "_HQQ_REGISTRY = {}\n\t_HQQ_REGISTRY = _HQQ_REGISTRY\nclass HQQModelForCausalLM(_Parent, HQQWrapper):\n\tdef __init__(self, *args, **kwargs):\n\tdef _make_quantizable(cls, model, quantized):\n\tdef _validate_params(cls, params... | from hqq.engine.hf import HQQModelForCausalLM, AutoTokenizer
from hqq.core.quantize import *
from hqq.core.peft import PeftUtils
from hqq.core.quantize import *
from datasets import load_dataset, Dataset
from tqdm import tqdm
from trl import SFTTrainer
import transformers
import numpy as np
import random | 1,458 | #Settings
######################################################################################
hf_auth = None #HuggingFace token
cache_path = '' #cache directory to store data
#Chose a model
model_id = "meta-llama/Llama-2-7b-hf"
#model_id = "meta-llama/Llama-2-13b-hf"
#model_id = "meta-llama/Llama-2-70b-hf... | #Settings
######################################################################################
hf_auth = None #HuggingFace token
cache_path = '' #cache directory to store data
#Chose a model
model_id = "meta-llama/Llama-2-7b-hf"
#model_id = "meta-llama/Llama-2-13b-hf"
#model_id = "meta-llama/Llama-2-70b-hf... | PeftUtils.add_lora(model, lora_params) | 1 | 2023-11-07 20:15:00+00:00 | 2k |
TheFunny/ArisuAutoSweeper | gui.py | [
{
"identifier": "logger",
"path": "module/logger/logger.py",
"snippet": "def empty_function(*args, **kwargs):\n def __init__(self, *args, func: Callable[[ConsoleRenderable], None] = None, **kwargs):\n def emit(self, record: logging.LogRecord) -> None:\n def handle(self, record: logging.LogRecor... | import threading
import argparse
import asyncio
import sys
import uvicorn
from multiprocessing import Event, Process
from module.logger import logger
from module.webui.setting import State
from module.logger.logger import console_hdlr | 750 |
def func(ev: threading.Event):
if sys.platform.startswith("win"):
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
|
def func(ev: threading.Event):
if sys.platform.startswith("win"):
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
| State.restart_event = ev | 1 | 2023-11-01 07:09:45+00:00 | 2k |
liuzhao1225/YouDub | youdub/tts_paddle.py | [
{
"identifier": "save_wav",
"path": "youdub/utils.py",
"snippet": "def save_wav(wav: np.ndarray, path: str, sample_rate: int = 24000) -> None:\n \"\"\"Save float waveform to a file using Scipy.\n\n Args:\n wav (np.ndarray): Waveform with float values in range [-1, 1] to save.\n path ... | import os, sys
import numpy as np
import json
import logging
from paddlespeech.cli.tts import TTSExecutor
from youdub.utils import save_wav, adjust_audio_length | 758 |
sys.path.append(os.getcwd())
class TTS_Clone:
def __init__(self, model_path="fastspeech2_male", voc='pwgan_male',device='gpu:0', language='mix'):
logging.info(f'Loading TTS model {model_path}...')
self.am = model_path
self.voc = voc
self.tts = TTSExecutor()
self.language... |
sys.path.append(os.getcwd())
class TTS_Clone:
def __init__(self, model_path="fastspeech2_male", voc='pwgan_male',device='gpu:0', language='mix'):
logging.info(f'Loading TTS model {model_path}...')
self.am = model_path
self.voc = voc
self.tts = TTSExecutor()
self.language... | wav_adjusted = adjust_audio_length(wav, os.path.join(folder, 'temp', f'zh_{i}.wav'), os.path.join( | 1 | 2023-11-02 08:21:31+00:00 | 2k |
dtiesling/flask-muck | tests/test.py | [
{
"identifier": "GuardianModel",
"path": "tests/app.py",
"snippet": "class GuardianModel(db.Model):\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n name = db.Column(db.String, nullable=False, unique=True)\n age = db.Column(db.Integer, nullable=True)\n family_id = db.Colu... | import json
import pytest
from unittest.mock import patch
from pydantic import BaseModel, ConfigDict
from flask_muck.exceptions import MuckImplementationError
from flask_muck.utils import (
get_url_rule,
get_fk_column,
get_query_filters_from_request_path,
get_join_models_from_parent_views,
)
from tests.... | 1,082 |
class TestBasicCrud:
def test_create(self, post, user):
response = post("/guardians/", json={"name": "Jill"})
parent = GuardianModel.query.one()
assert response == {"name": parent.name}
# Verify integrity errors are handled.
post("/guardians/", json={"name": "Jill"}, exp... |
class TestBasicCrud:
def test_create(self, post, user):
response = post("/guardians/", json={"name": "Jill"})
parent = GuardianModel.query.one()
assert response == {"name": parent.name}
# Verify integrity errors are handled.
post("/guardians/", json={"name": "Jill"}, exp... | monkeypatch.setattr(BaseApiView, "allowed_methods", {"GET"}) | 4 | 2023-11-07 03:44:49+00:00 | 2k |
BrianPugh/cyclopts | cyclopts/parameter.py | [
{
"identifier": "AnnotatedType",
"path": "cyclopts/_convert.py",
"snippet": "def _bool(s: str) -> bool:\ndef _int(s: str) -> int:\ndef _bytes(s: str) -> bytes:\ndef _bytearray(s: str) -> bytearray:\ndef _convert(type_, element, converter=None):\ndef get_origin_and_validate(type_: Type):\ndef resolve(typ... | import inspect
import attrs
from typing import Any, Callable, Optional, Tuple, Type, Union, cast, get_args, get_origin
from attrs import field, frozen
from cyclopts._convert import (
AnnotatedType,
convert,
get_origin_and_validate,
optional_to_tuple_converter,
resolve,
resolve_optional,
to_t... | 1,282 |
def _double_hyphen_validator(instance, attribute, values):
if not values:
return
for value in values:
if value is not None and not value.startswith("--"):
raise ValueError(f'{attribute.alias} value must start with "--".')
def _negative_converter(default: Tuple[str, ...]):
... |
def _double_hyphen_validator(instance, attribute, values):
if not values:
return
for value in values:
if value is not None and not value.startswith("--"):
raise ValueError(f'{attribute.alias} value must start with "--".')
def _negative_converter(default: Tuple[str, ...]):
... | converter: Callable = field(default=None, converter=attrs.converters.default_if_none(convert)) | 0 | 2023-11-03 02:24:25+00:00 | 2k |
RoboFlamingo/RoboFlamingo | open_flamingo/open_flamingo/src/flamingo_lm.py | [
{
"identifier": "GatedCrossAttentionBlock",
"path": "open_flamingo/open_flamingo/src/helpers.py",
"snippet": "class GatedCrossAttentionBlock(nn.Module):\n def __init__(\n self,\n *,\n dim,\n dim_visual,\n dim_head=64,\n heads=8,\n ff_mult=4,\n o... | import torch.nn as nn
import copy
from .helpers import GatedCrossAttentionBlock
from .utils import getattr_recursive, setattr_recursive | 1,188 |
class FlamingoLayer(nn.Module):
"""
FlamingoLayer is a wrapper around the GatedCrossAttentionBlock and DecoderLayer.
"""
def __init__(
self, gated_cross_attn_layer, decoder_layer, gradient_checkpointing=False, residual=False
):
super().__init__()
self.gated_cross_attn_layer... |
class FlamingoLayer(nn.Module):
"""
FlamingoLayer is a wrapper around the GatedCrossAttentionBlock and DecoderLayer.
"""
def __init__(
self, gated_cross_attn_layer, decoder_layer, gradient_checkpointing=False, residual=False
):
super().__init__()
self.gated_cross_attn_layer... | return getattr_recursive(self, self.decoder_layers_attr_name) | 1 | 2023-11-02 01:36:23+00:00 | 2k |
XinyuanLiao/ComplexNN | complexNN/nn.py | [
{
"identifier": "complexRelu",
"path": "complexNN/functional.py",
"snippet": "def complexRelu(inp):\n return torch.complex(relu(inp.real), relu(inp.imag))"
},
{
"identifier": "complexGelu",
"path": "complexNN/functional.py",
"snippet": "def complexGelu(inp):\n return torch.complex(... | import numpy as np
import torch
import torch.nn as nn
from complexNN.functional import complexRelu, complexGelu, complexTanh, complexSigmoid, complexMaxPool2d, \
complexAvgPool2d, complexAvgPool1d, complexDropout, complexDropout2d, complexElu, complexLeakyRelu, complexSoftmax | 1,087 |
class cRelu(nn.Module):
@staticmethod
def forward(inp):
return complexRelu(inp)
class cElu(nn.Module):
@staticmethod
def forward(inp):
return complexElu(inp)
class cLeakyRelu(nn.Module):
@staticmethod
def forward(inp):
return complexLeakyRelu(inp)
class cSoftmax(n... |
class cRelu(nn.Module):
@staticmethod
def forward(inp):
return complexRelu(inp)
class cElu(nn.Module):
@staticmethod
def forward(inp):
return complexElu(inp)
class cLeakyRelu(nn.Module):
@staticmethod
def forward(inp):
return complexLeakyRelu(inp)
class cSoftmax(n... | return complexSigmoid(inp) | 3 | 2023-11-02 04:52:23+00:00 | 2k |
sanmusen214/BAAH | modules/configs/MyConfig.py | [
{
"identifier": "defaultUserDict",
"path": "modules/configs/defaultSettings.py",
"snippet": ""
},
{
"identifier": "configname2screenshotname",
"path": "modules/configs/settingMaps.py",
"snippet": "def configname2screenshotname(configfilename):\n \"\"\"\n 根据config文件名,返回截图文件名\n co... | import json
import logging
import os
import time
from modules.configs.defaultSettings import defaultUserDict, defaultSoftwareDict
from modules.configs.settingMaps import configname2screenshotname | 702 |
# 程序入口应当先import这个类,然后调用parse_user_config方法解析该config实例
# 然后程序入口再import其他模块,在其他模块中import这个类,就可以直接使用这个类的实例了
class MyConfigger:
"""
维护config字典,包含软件config,用户任务config,语言包
"""
NOWVERSION="1.2.0"
USER_CONFIG_FOLDER="./BAAH_CONFIGS"
SOFTWARE_CONFIG_FOLDER="./DATA/CONFIGS"
LANGUAGE_PACKAGE_FOLDER=".... |
# 程序入口应当先import这个类,然后调用parse_user_config方法解析该config实例
# 然后程序入口再import其他模块,在其他模块中import这个类,就可以直接使用这个类的实例了
class MyConfigger:
"""
维护config字典,包含软件config,用户任务config,语言包
"""
NOWVERSION="1.2.0"
USER_CONFIG_FOLDER="./BAAH_CONFIGS"
SOFTWARE_CONFIG_FOLDER="./DATA/CONFIGS"
LANGUAGE_PACKAGE_FOLDER=".... | fromkey = defaultUserDict["PIC_PATH"]["m"]["from"] | 0 | 2023-11-09 22:28:39+00:00 | 2k |
lucidrains/gateloop-transformer | gateloop_transformer/simplified_gate_loop.py | [
{
"identifier": "RMSNorm",
"path": "gateloop_transformer/gateloop_transformer.py",
"snippet": "class RMSNorm(Module):\n def __init__(self, dim):\n super().__init__()\n self.scale = dim ** 0.5\n self.gamma = nn.Parameter(torch.ones(dim))\n\n def forward(self, x):\n retur... | from functools import partial
from torch import nn, Tensor
from torch.nn import Module
from typing import Tuple
from einops import rearrange, pack, unpack
from einops.layers.torch import Rearrange
from gateloop_transformer.gateloop_transformer import RMSNorm
from gateloop_transformer.associative_scan import associative... | 1,050 |
# plain pytorch non-fused associative scan
def exists(v):
return v is not None
def abs_clamp_eps(t, eps = 1e-20):
sign = torch.sign(t)
return sign * t.abs().clamp(min = eps)
# associative scan using heinsen sequences
# https://github.com/glassroom/heinsen_sequence
# graciously shared to the world by... |
# plain pytorch non-fused associative scan
def exists(v):
return v is not None
def abs_clamp_eps(t, eps = 1e-20):
sign = torch.sign(t)
return sign * t.abs().clamp(min = eps)
# associative scan using heinsen sequences
# https://github.com/glassroom/heinsen_sequence
# graciously shared to the world by... | a, kv = associative_scan(binary_operator, (a, kv)) | 1 | 2023-11-06 21:56:40+00:00 | 2k |
QingruZhang/PASTA | evaluation/data.py | [
{
"identifier": "env_utils",
"path": "evaluation/utils/env_utils.py",
"snippet": "ENV_DATA_DIR = \"CM_DATA_DIR\"\nENV_MODELS_DIR = \"CM_MODELS_DIR\"\nENV_RESULTS_DIR = \"CM_RESULTS_DIR\"\nDEFAULT_DATA_DIR = \"data\"\nDEFAULT_MODELS_DIR = \"models\"\nDEFAULT_RESULTS_DIR = \"results\"\ndef maybe_relative_... | import argparse
import csv
import json
import logging
import pickle
import random
import datasets
import numpy
import scipy.sparse
import spacy
import wget
from collections import defaultdict
from functools import cache
from itertools import chain
from pathlib import Path
from typing import Any, Sequence, TypedDict, ca... | 1,035 | """Datasets for evaluating context mediation in LMs."""
logger = logging.getLogger(__name__)
SUPPORTED_DATASETS = ("counterfact", "winoventi", "biosbias", "mcrae")
ROME_BASE_URL = "https://rome.baulab.info/data/dsets"
COUNTERFACT_URL = f"{ROME_BASE_URL}/counterfact.json"
ATTRIBUTE_SNIPPETS_URL = f"{ROME_BASE_URL}... | """Datasets for evaluating context mediation in LMs."""
logger = logging.getLogger(__name__)
SUPPORTED_DATASETS = ("counterfact", "winoventi", "biosbias", "mcrae")
ROME_BASE_URL = "https://rome.baulab.info/data/dsets"
COUNTERFACT_URL = f"{ROME_BASE_URL}/counterfact.json"
ATTRIBUTE_SNIPPETS_URL = f"{ROME_BASE_URL}... | id: StrSequence | 2 | 2023-11-06 05:36:05+00:00 | 2k |
Ljzd-PRO/KToolBox | ktoolbox/api/base.py | [
{
"identifier": "config",
"path": "ktoolbox/configuration.py",
"snippet": "class APIConfiguration(BaseModel):\nclass DownloaderConfiguration(BaseModel):\nclass PostStructureConfiguration(BaseModel):\nclass JobConfiguration(BaseModel):\nclass LoggerConfiguration(BaseModel):\nclass Configuration(BaseSetti... | from abc import ABC, abstractmethod
from typing import Literal, Generic, TypeVar, Optional, Callable
from urllib.parse import urlunparse
from loguru import logger
from pydantic import BaseModel, ValidationError, RootModel
from tenacity import RetryCallState, wait_fixed, retry_if_result
from tenacity.stop import stop_ba... | 768 |
__all__ = ["APITenacityStop", "APIRet", "BaseAPI"]
_T = TypeVar('_T')
class APITenacityStop(stop_base):
"""APIs Stop strategies"""
def __call__(self, retry_state: RetryCallState) -> bool:
if config.api.retry_times is None:
return stop_never(retry_state)
else:
retur... |
__all__ = ["APITenacityStop", "APIRet", "BaseAPI"]
_T = TypeVar('_T')
class APITenacityStop(stop_base):
"""APIs Stop strategies"""
def __call__(self, retry_state: RetryCallState) -> bool:
if config.api.retry_times is None:
return stop_never(retry_state)
else:
retur... | class APIRet(BaseRet[_T]): | 2 | 2023-11-06 15:24:12+00:00 | 2k |
jpjacobpadilla/Google-Colab-Selenium | google_colab_selenium/chromedriver.py | [
{
"identifier": "ColabSeleniumManager",
"path": "google_colab_selenium/colab_selenium_manager.py",
"snippet": "class ColabSeleniumManager:\n default_colab_options = [\n '--headless',\n '--no-sandbox',\n '--disable-dev-shm-usage',\n '--lang=en'\n ]\n\n _downloaded_chr... | from google_colab_selenium.colab_selenium_manager import ColabSeleniumManager
from google_colab_selenium.spinner import Spinner
from google_colab_selenium.exceptions import StartingChromeDriverError
from selenium.webdriver.chrome.options import Options
from selenium import webdriver | 1,448 |
class ChromeDriver(webdriver.Chrome):
"""
A thin wrapper around the Selenium Chrome Webdriver which makes it easy
to use in Google Colab Notebooks.
The ColabSeleniumManager class installs Google-Chrome-Stable and adds the
nessasary headers to use in a Colab Notebook.
The headers that are au... |
class ChromeDriver(webdriver.Chrome):
"""
A thin wrapper around the Selenium Chrome Webdriver which makes it easy
to use in Google Colab Notebooks.
The ColabSeleniumManager class installs Google-Chrome-Stable and adds the
nessasary headers to use in a Colab Notebook.
The headers that are au... | with Spinner('Initializing Chromedriver', done='Initialized Chromedriver'): | 1 | 2023-11-06 21:18:41+00:00 | 2k |
microsoft/monitors4codegen | tests/monitor_guided_decoding/test_numargs_monitor_java.py | [
{
"identifier": "create_test_context",
"path": "tests/test_utils.py",
"snippet": "@contextlib.contextmanager\ndef create_test_context(params: dict) -> Iterator[MultilspyContext]:\n \"\"\"\n Creates a test context for the given parameters.\n \"\"\"\n config = MultilspyConfig.from_dict(params)... | import torch
import transformers
import pytest
from pathlib import PurePath
from monitors4codegen.multilspy.language_server import SyncLanguageServer
from monitors4codegen.multilspy.multilspy_config import Language
from tests.test_utils import create_test_context, is_cuda_available
from transformers import AutoTokenize... | 792 | """
This file contains tests for Monitor-Guided Decoding for correct number of arguments in Java
"""
pytest_plugins = ("pytest_asyncio",)
@pytest.mark.asyncio
async def test_multilspy_java_clickhouse_highlevel_sinker_modified_numargs():
"""
Test the working of numargs_monitor with Java repository - clickhou... | """
This file contains tests for Monitor-Guided Decoding for correct number of arguments in Java
"""
pytest_plugins = ("pytest_asyncio",)
@pytest.mark.asyncio
async def test_multilspy_java_clickhouse_highlevel_sinker_modified_numargs():
"""
Test the working of numargs_monitor with Java repository - clickhou... | with create_test_context(params) as context: | 0 | 2023-11-04 21:49:04+00:00 | 2k |
bigai-nlco/langsuite | langsuite/envs/teach/libs/teach/dataset/episode.py | [
{
"identifier": "Initialization",
"path": "langsuite/envs/teach/libs/teach/dataset/initialization.py",
"snippet": "class Initialization:\n def __init__(\n self, time_start, agents=None, objects=None, custom_object_metadata=None\n ):\n self.time_start = time_start\n self.agents... | from collections import OrderedDict
from langsuite.envs.teach.libs.teach.dataset.initialization import Initialization
from langsuite.envs.teach.libs.teach.dataset.interaction import Interaction | 1,457 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
from __future__ import annotations
class Episode:
def __init__(
self,
episode_id,
world,
world_type,
commander_embodied,
initial_state=None,
interactions=... | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
from __future__ import annotations
class Episode:
def __init__(
self,
episode_id,
world,
world_type,
commander_embodied,
initial_state=None,
interactions=... | initial_state=Initialization.from_dict(episode_dict["initial_state"]) | 0 | 2023-11-01 01:47:00+00:00 | 2k |
tmlr-group/DeepInception | conversers.py | [
{
"identifier": "FALCON_PATH",
"path": "config.py",
"snippet": "FALCON_PATH = f\"{ROOT_PATH}/falcon-7b-instruct\""
},
{
"identifier": "LLAMA_PATH",
"path": "config.py",
"snippet": "LLAMA_PATH = f\"{ROOT_PATH}/Llama-2-7b-hf\""
},
{
"identifier": "TARGET_TEMP",
"path": "config.... | import torch
import common
from transformers import AutoModelForCausalLM, AutoTokenizer
from config import (FALCON_PATH, LLAMA_PATH, TARGET_TEMP, TARGET_TOP_P,
VICUNA_PATH)
from language_models import GPT, HuggingFace | 1,083 |
def load_attack_and_target_models(args):
targetLM = TargetLM(model_name = args.target_model,
max_n_tokens = args.target_max_n_tokens,
|
def load_attack_and_target_models(args):
targetLM = TargetLM(model_name = args.target_model,
max_n_tokens = args.target_max_n_tokens, | temperature = TARGET_TEMP, # init to 0 | 2 | 2023-11-07 12:47:47+00:00 | 2k |
radekd91/inferno | inferno/datasets/FaceAlignmentTools.py | [
{
"identifier": "bbox2point",
"path": "inferno/datasets/ImageDatasetHelpers.py",
"snippet": "def bbox2point(left, right, top, bottom, type='bbox'):\n ''' bbox from detector and landmarks are different\n '''\n if type == 'kpt68':\n old_size = (right - left + bottom - top) / 2 * 1.1\n ... | import numpy as np
import skvideo
import types
from pathlib import Path
from inferno.datasets.ImageDatasetHelpers import bbox2point, bbpoint_warp | 1,135 |
def align_face(image, landmarks, landmark_type, scale_adjustment, target_size_height, target_size_width=None,):
"""
Returns an image with the face aligned to the center of the image.
:param image: The full resolution image in which to align the face.
:param landmarks: The landmarks of the face in the... |
def align_face(image, landmarks, landmark_type, scale_adjustment, target_size_height, target_size_width=None,):
"""
Returns an image with the face aligned to the center of the image.
:param image: The full resolution image in which to align the face.
:param landmarks: The landmarks of the face in the... | img_warped, lmk_warped = bbpoint_warp(image, center, size, target_size_height, target_size_width, landmarks=landmarks) | 1 | 2023-11-07 20:13:32+00:00 | 2k |
hxz393/ConfigCenterComparer | module/get_query_sql.py | [
{
"identifier": "SQL_CONFIG_NACOS",
"path": "config/settings.py",
"snippet": "SQL_CONFIG_NACOS = \"\"\"\nSELECT\n data_id,\n group_id,\n content,\n gmt_modified\nFROM\n config_info\n\"\"\""
},
{
"identifier": "SQL_CONFIG_APOLLO_ID",
"path": "config/settings.py",
"snippet": "SQL_CONF... | import logging
from typing import Dict, Optional
from config.settings import SQL_CONFIG_NACOS, SQL_CONFIG_APOLLO_ID, SQL_CONFIG_APOLLO_NAME, APOLLO_NAME_LIST | 753 | """
此模块用于处理配置中心相关的查询,包括从不同的配置中心获取 SQL 查询语句。
本模块提供了 `get_query_sql` 函数,用于根据配置中心类型和 Apollo 应用名称获取对应的查询 SQL。支持从 Nacos 和 Apollo 配置中心获取数据。
:author: assassing
:contact: https://github.com/hxz393
:copyright: Copyright 2023, hxz393. 保留所有权利。
"""
logger = logging.getLogger(__name__)
def get_query_sql(config_main: Dict[str... | """
此模块用于处理配置中心相关的查询,包括从不同的配置中心获取 SQL 查询语句。
本模块提供了 `get_query_sql` 函数,用于根据配置中心类型和 Apollo 应用名称获取对应的查询 SQL。支持从 Nacos 和 Apollo 配置中心获取数据。
:author: assassing
:contact: https://github.com/hxz393
:copyright: Copyright 2023, hxz393. 保留所有权利。
"""
logger = logging.getLogger(__name__)
def get_query_sql(config_main: Dict[str... | elif config_center == 'Apollo' and apollo_name in APOLLO_NAME_LIST: | 3 | 2023-11-07 01:02:38+00:00 | 2k |
pytorch-labs/ao | torchao/quantization/smoothquant.py | [
{
"identifier": "dynamically_quantize_per_channel",
"path": "torchao/quantization/quant_primitives.py",
"snippet": "def dynamically_quantize_per_channel(x, quant_min, quant_max, target_dtype):\n # assumes symmetric quantization\n # assumes axis == 0\n # assumes dense memory format\n # TODO(f... | import torch
import torch.nn.functional as F
import torchao.quantization.quant_api as quant_api
from .quant_primitives import (
dynamically_quantize_per_channel,
quant_int8_dynamic_per_token_linear,
) | 1,488 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""
Testing out accuracy-only implementation of SmoothQuant
(https://arxiv.org/pdf/2211.10438.pdf)
Note: this is an applic... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""
Testing out accuracy-only implementation of SmoothQuant
(https://arxiv.org/pdf/2211.10438.pdf)
Note: this is an applic... | W_int_repr, W_scales, W_zps = dynamically_quantize_per_channel( | 0 | 2023-11-03 21:27:36+00:00 | 2k |
Subsets and Splits
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have consistent code formatting levels across multiple scales (2k, 4k, 8k, 12k) and reveals the structured formatting patterns within these repositories.
SQL Console for tianyang/repobench_python_v1.1
Compares cross-file and in-file code structure patterns across different complexity levels, revealing how file organization strategies vary with code size and potentially informing better code architecture decisions.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have complete performance data across all seven code complexity levels, revealing consistent benchmarking patterns across different code sizes.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that contain all 7 distinct quality levels (2k through 32k), revealing complete datasets that might be useful for comprehensive analysis.