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 |
|---|---|---|---|---|---|---|---|---|---|---|
AsuradaYuci/TF-CLIP | loss/make_loss.py | [
{
"identifier": "CrossEntropyLabelSmooth",
"path": "loss/softmax_loss.py",
"snippet": "class CrossEntropyLabelSmooth(nn.Module):\n \"\"\"Cross entropy loss with label smoothing regularizer.\n\n Reference:\n Szegedy et al. Rethinking the Inception Architecture for Computer Vision. CVPR 2016.\n ... | import torch.nn.functional as F
from .softmax_loss import CrossEntropyLabelSmooth, LabelSmoothingCrossEntropy
from .triplet_loss import TripletLoss
from .center_loss import CenterLoss | 1,474 | # encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
def make_loss(cfg, num_classes): # modified by gu
sampler = cfg.DATALOADER.SAMPLER
feat_dim = 2048
| # encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
def make_loss(cfg, num_classes): # modified by gu
sampler = cfg.DATALOADER.SAMPLER
feat_dim = 2048 | center_criterion = CenterLoss(num_classes=num_classes, feat_dim=feat_dim, use_gpu=True) # center loss | 3 | 2023-12-11 04:03:46+00:00 | 2k |
MarilynKeller/aitviewer-skel | aitviewer/models/smpl.py | [
{
"identifier": "CONFIG",
"path": "aitviewer/configuration.py",
"snippet": "CONFIG = Configuration()"
},
{
"identifier": "aa2rot_torch",
"path": "aitviewer/utils/so3.py",
"snippet": "def aa2rot_torch(rotation_vectors):\n \"\"\"\n Convert rotation vectors (angle-axis representation)... | import collections
import numpy as np
import smplx
import torch
import torch.nn as nn
import trimesh
from abc import ABC
from aitviewer.configuration import CONFIG as C
from aitviewer.utils.so3 import aa2rot_torch as aa2rot
from aitviewer.utils.so3 import rot2aa_torch as rot2aa
from aitviewer.utils.utils im... | 1,050 | # Copyright (C) 2023 ETH Zurich, Manuel Kaufmann, Velko Vechev, Dario Mylonopoulos
class SMPLLayer(nn.Module, ABC):
"""A wrapper for the various SMPL body models."""
def __init__(
self,
model_type="smpl",
gender="neutral",
num_betas=10,
device=None,
dtype=No... | # Copyright (C) 2023 ETH Zurich, Manuel Kaufmann, Velko Vechev, Dario Mylonopoulos
class SMPLLayer(nn.Module, ABC):
"""A wrapper for the various SMPL body models."""
def __init__(
self,
model_type="smpl",
gender="neutral",
num_betas=10,
device=None,
dtype=No... | C.smplx_models, | 0 | 2023-12-07 16:13:50+00:00 | 2k |
wukan1986/polars_ta | tests/numba_test.py | [
{
"identifier": "ts_co_kurtosis",
"path": "polars_ta/wq/time_series.py",
"snippet": "def ts_co_kurtosis(x: Expr, y: Expr, d: int = 5, ddof: int = 0) -> Expr:\n return map_batches([x, y], lambda xx: batches_i2_o1([x1.to_numpy() for x1 in xx], roll_co_kurtosis, d))"
},
{
"identifier": "nb_roll_... | import time
import numpy as np
import polars as pl
from numba import jit
from polars_ta.wq.time_series import ts_co_kurtosis
from polars_ta.utils.numba_ import nb_roll_sum, batches_i1_o1, roll_sum, roll_cov | 671 |
@jit(nopython=True, nogil=True, fastmath=True, cache=True)
def nb_sum(x):
return np.sum(x)
df = pl.DataFrame({'A': range(100000), 'B': range(100000)})
a = df.with_columns([
pl.col('A').rolling_sum(10).alias('a1'),
pl.col('A').rolling_map(lambda x: x.sum(), 10).alias('a2'),
pl.col('A').rolling_map(... |
@jit(nopython=True, nogil=True, fastmath=True, cache=True)
def nb_sum(x):
return np.sum(x)
df = pl.DataFrame({'A': range(100000), 'B': range(100000)})
a = df.with_columns([
pl.col('A').rolling_sum(10).alias('a1'),
pl.col('A').rolling_map(lambda x: x.sum(), 10).alias('a2'),
pl.col('A').rolling_map(... | ts_co_kurtosis(pl.col('A'), pl.col('B'), 10).alias('a8'), | 0 | 2023-12-12 11:44:52+00:00 | 2k |
facebookresearch/taskmet | taskmet.py | [
{
"identifier": "dense_nn",
"path": "utils.py",
"snippet": "def dense_nn(\n num_features,\n num_targets,\n num_layers,\n intermediate_size=10,\n activation=\"relu\",\n output_activation=\"sigmoid\",\n):\n if num_layers > 1:\n if intermediate_size is None:\n interme... | import torch
import torch.nn as nn
import numpy as np
import functorch
import torchopt
import random
from typing import List, Tuple, Dict, Union, Optional, Callable
from utils import dense_nn, View
from metric import Metric | 952 | # Copyright (c) Meta Platforms, Inc. and affiliates
class Predictor(nn.Module):
def __init__(self, args):
super().__init__()
| # Copyright (c) Meta Platforms, Inc. and affiliates
class Predictor(nn.Module):
def __init__(self, args):
super().__init__() | self.model = dense_nn() | 0 | 2023-12-07 22:23:01+00:00 | 2k |
kylemcdonald/i2i-realtime | offline_renderer.py | [
{
"identifier": "chunks",
"path": "utils/itertools.py",
"snippet": "def chunks(x, n):\n # return slices of lists\n if hasattr(x, '__len__'):\n for i in range(0, len(x), n):\n yield x[i:i+n]\n else:\n # return sub-generators of generators\n i = iter(x)\n fo... | import os
import numpy as np
from tqdm import tqdm
from natsort import natsorted
from turbojpeg import TurboJPEG, TJPF_RGB
from utils.itertools import chunks
from diffusion_processor import DiffusionProcessor | 1,287 |
input_directory = "data/frames-1080"
output_directory = input_directory + "-i2i"
batch_size = 4
prompt = "Three ballety dancers in a psychedelic landscape."
steps = 2
strength = 0.7
seed = 0
jpeg = TurboJPEG()
def imread(fn):
with open(fn, 'rb') as f:
return jpeg.decode(f.read(), pixel_format=TJPF_RGB)
... |
input_directory = "data/frames-1080"
output_directory = input_directory + "-i2i"
batch_size = 4
prompt = "Three ballety dancers in a psychedelic landscape."
steps = 2
strength = 0.7
seed = 0
jpeg = TurboJPEG()
def imread(fn):
with open(fn, 'rb') as f:
return jpeg.decode(f.read(), pixel_format=TJPF_RGB)
... | batches = list(chunks(fns, batch_size)) | 0 | 2023-12-05 12:32:28+00:00 | 2k |
wusize/CLIM | src/training/train.py | [
{
"identifier": "is_master",
"path": "src/training/distributed.py",
"snippet": "def is_master(args, local=False):\n return is_local_master(args) if local else is_global_master(args)"
},
{
"identifier": "zero_shot_eval",
"path": "src/training/zero_shot.py",
"snippet": "def zero_shot_ev... | import json
import logging
import math
import time
import torch
import os
from open_clip import get_cast_dtype
from .distributed import is_master
from .zero_shot import zero_shot_eval
from .precision import get_autocast | 833 |
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum +=... |
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum +=... | autocast = get_autocast(args.precision) | 2 | 2023-12-09 05:43:08+00:00 | 2k |
firstof9/ha-gasbuddy | tests/test_config_flow.py | [
{
"identifier": "CONF_INTERVAL",
"path": "custom_components/gasbuddy/const.py",
"snippet": "CONF_INTERVAL = \"interval\""
},
{
"identifier": "CONF_NAME",
"path": "custom_components/gasbuddy/const.py",
"snippet": "CONF_NAME = \"name\""
},
{
"identifier": "CONF_POSTAL",
"path":... | from unittest.mock import patch
from homeassistant import config_entries, data_entry_flow, setup
from homeassistant.const import CONF_NAME
from homeassistant.data_entry_flow import FlowResult, FlowResultType
from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.gasbuddy.const i... | 727 | """Test config flow."""
pytestmark = pytest.mark.asyncio
@pytest.mark.parametrize(
"input,step_id,title,data",
[
(
{
| """Test config flow."""
pytestmark = pytest.mark.asyncio
@pytest.mark.parametrize(
"input,step_id,title,data",
[
(
{ | CONF_NAME: DEFAULT_NAME, | 5 | 2023-12-07 20:53:03+00:00 | 2k |
ku-dmlab/PORelDICE | learner.py | [
{
"identifier": "update_actor",
"path": "actor.py",
"snippet": "def update_actor(\n key: PRNGKey,\n actor: Model,\n critic: Model,\n value: Model,\n batch: Batch,\n alpha: float,\n epsilon: float,\n alg: str,\n) -> Tuple[Model, InfoDict]:\n v = value(batch.observations)\n i... | from typing import Optional, Sequence, Tuple
from actor import update_actor
from common import Batch, InfoDict, Model, PRNGKey
from critic import update_q, update_v
import jax
import jax.numpy as jnp
import numpy as np
import optax
import policy
import value_net | 1,262 | """Implementations of algorithms for continuous control."""
def target_update(critic: Model, target_critic: Model, tau: float) -> Model:
new_target_params = jax.tree_util.tree_map(
lambda p, tp: p * tau + tp * (1 - tau), critic.params, target_critic.params
)
return target_critic.replace(params=... | """Implementations of algorithms for continuous control."""
def target_update(critic: Model, target_critic: Model, tau: float) -> Model:
new_target_params = jax.tree_util.tree_map(
lambda p, tp: p * tau + tp * (1 - tau), critic.params, target_critic.params
)
return target_critic.replace(params=... | new_value, value_info = update_v(target_critic, value, batch, alpha, epsilon, discount, alg="PORelDICE") | 3 | 2023-12-11 07:47:22+00:00 | 2k |
Megant88/Valorant-GUI-Cheat-Arduino | cheese.py | [
{
"identifier": "MouseInstruct",
"path": "mouse_instruct.py",
"snippet": "class MouseInstruct:\n def __init__(self, dev):\n self._buttons_mask = 0\n self._dev = dev\n self.move(0, 0)\n\n @classmethod\n def getMouse(cls, vid=0, pid=0, ping_code=0xf9):\n dev = find_mou... | import cv2
import numpy as np
import win32api, sys
import serial
import keyboard, threading
import time, json
from mss import mss
from mouse_instruct import MouseInstruct, DeviceNotFoundError
from ctypes import WinDLL
from valclient.client import Client
| 968 |
user32, kernel32, shcore = (
WinDLL("user32", use_last_error=True),
WinDLL("kernel32", use_last_error=True),
WinDLL("shcore", use_last_error=True),
)
shcore.SetProcessDpiAwareness(2)
WIDTH, HEIGHT = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]
ZONE = 5
GRAB_ZONE = (
int(WIDTH ... |
user32, kernel32, shcore = (
WinDLL("user32", use_last_error=True),
WinDLL("kernel32", use_last_error=True),
WinDLL("shcore", use_last_error=True),
)
shcore.SetProcessDpiAwareness(2)
WIDTH, HEIGHT = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]
ZONE = 5
GRAB_ZONE = (
int(WIDTH ... | mouse = MouseInstruct.getMouse()
| 0 | 2023-12-07 18:37:11+00:00 | 2k |
Anashel-RPG/echoai | job_manager.py | [
{
"identifier": "download_image",
"path": "image_downloader.py",
"snippet": "def download_image(image_url, local_path, job_id, prompt, additional_metadata):\r\n logging.info(f\"Initiating download: URL {image_url}, Local Path {local_path}, Job ID {job_id}, Prompt {prompt[:30]}...\")\r\n\r\n try:\r... | import threading
import time
import os
import json
import requests
import logging
from queue import Queue, Empty
from datetime import datetime
from image_downloader import download_image
from config import MAX_CONCURRENT_JOBS, RATE_LIMIT_DELAY, API_BASE_URL, HEADERS, API_CALL_DELAY
from job_data_store import ... | 1,135 | # job_manager.py
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class API:
total_api_credit_cost = 0 # Class-level variable to track the total cost
total_images = 0 # Class-level variable to track the total images
@staticmethod
... | # job_manager.py
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class API:
total_api_credit_cost = 0 # Class-level variable to track the total cost
total_images = 0 # Class-level variable to track the total images
@staticmethod
... | headers = HEADERS
| 4 | 2023-12-09 16:16:39+00:00 | 2k |
llegomark/gemini-pro-chat | test_chat.py | [
{
"identifier": "ChatHistoryManager",
"path": "chat.py",
"snippet": "class ChatHistoryManager:\n def __init__(self, filename=\"chat_history.txt\", max_file_size_mb=5):\n self.history = []\n self.filename = filename\n self.max_file_size_mb = max_file_size_mb\n\n def add_message... | import unittest
import os
from unittest.mock import patch, mock_open, MagicMock
from chat import ChatHistoryManager, main | 1,274 |
class TestChatHistoryManager(unittest.TestCase):
def test_initialization(self):
manager = ChatHistoryManager()
self.assertEqual(manager.history, [])
self.assertEqual(manager.filename, 'chat_history.txt')
self.assertEqual(manager.max_file_size_mb, 5)
@patch('os.path.exists')
... |
class TestChatHistoryManager(unittest.TestCase):
def test_initialization(self):
manager = ChatHistoryManager()
self.assertEqual(manager.history, [])
self.assertEqual(manager.filename, 'chat_history.txt')
self.assertEqual(manager.max_file_size_mb, 5)
@patch('os.path.exists')
... | main() | 1 | 2023-12-14 02:11:11+00:00 | 2k |
CXH-Research/DeVigNet | train.py | [
{
"identifier": "Config",
"path": "config/config.py",
"snippet": "class Config(object):\n r\"\"\"\n A collection of all the required configuration parameters. This class is a nested dict-like\n structure, with nested keys accessible as attributes. It contains sensible default values for\n al... | import warnings
import torch.optim as optim
from accelerate import Accelerator
from pytorch_msssim import SSIM
from torch.utils.data import DataLoader
from torchmetrics.functional import peak_signal_noise_ratio, structural_similarity_index_measure
from torchmetrics.functional.regression import mean_absolute_error
from ... | 1,337 |
warnings.filterwarnings('ignore')
opt = Config('config.yml')
seed_everything(opt.OPTIM.SEED)
def train():
# Accelerate
accelerator = Accelerator(log_with='wandb') if opt.OPTIM.WANDB else Accelerator()
device = accelerator.device
config = {
"dataset": opt.TRAINING.TRAIN_DIR
}
accele... |
warnings.filterwarnings('ignore')
opt = Config('config.yml')
seed_everything(opt.OPTIM.SEED)
def train():
# Accelerate
accelerator = Accelerator(log_with='wandb') if opt.OPTIM.WANDB else Accelerator()
device = accelerator.device
config = {
"dataset": opt.TRAINING.TRAIN_DIR
}
accele... | train_dataset = get_training_data(train_dir, opt.MODEL.INPUT, opt.MODEL.TARGET, | 1 | 2023-12-09 06:35:54+00:00 | 2k |
moonshot-admin/moonshot | third-party/tqdm-4.66.1/tqdm/contrib/telegram.py | [
{
"identifier": "tqdm",
"path": "third-party/tqdm-4.66.1/tqdm/auto.py",
"snippet": "class tqdm(notebook_tqdm, asyncio_tqdm): # pylint: disable=inconsistent-mro\n pass"
},
{
"identifier": "TqdmWarning",
"path": "third-party/tqdm-4.66.1/tqdm/std.py",
"snippet": "class TqdmWarning(Warni... | from os import getenv
from warnings import warn
from requests import Session
from ..auto import tqdm as tqdm_auto
from ..std import TqdmWarning
from .utils_worker import MonoWorker | 836 | """
Sends updates to a Telegram bot.
Usage:
>>> from tqdm.contrib.telegram import tqdm, trange
>>> for i in trange(10, token='{token}', chat_id='{chat_id}'):
... ...

"""
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['TelegramIO', 'tqdm_... | """
Sends updates to a Telegram bot.
Usage:
>>> from tqdm.contrib.telegram import tqdm, trange
>>> for i in trange(10, token='{token}', chat_id='{chat_id}'):
... ...

"""
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['TelegramIO', 'tqdm_... | TqdmWarning, stacklevel=2) | 1 | 2023-12-14 07:43:03+00:00 | 2k |
LkPrtctrd/BSL-V53 | Heart/Packets/Server/Home/AvailableServerCommandMessage.py | [
{
"identifier": "LogicCommandManager",
"path": "Heart/Logic/LogicCommandManager.py",
"snippet": "class LogicCommandManager:\n commandsList = {\n 201: ChangeAvatarNameCommand,\n 202: 'DiamondsAddedCommand',\n 203: 'GiveDeliveryItemsCommand',\n 204: 'DayChangedCommand',\n ... | from Heart.Logic.LogicCommandManager import LogicCommandManager
from Heart.Packets.PiranhaMessage import PiranhaMessage | 1,261 |
class AvailableServerCommandMessage(PiranhaMessage):
def __init__(self, messageData):
super().__init__(messageData)
self.messageVersion = 0
def encode(self, fields, player):
self.writeVInt(fields["Command"]["ID"])
|
class AvailableServerCommandMessage(PiranhaMessage):
def __init__(self, messageData):
super().__init__(messageData)
self.messageVersion = 0
def encode(self, fields, player):
self.writeVInt(fields["Command"]["ID"]) | command = LogicCommandManager.createCommand(fields["Command"]["ID"], self.messagePayload) | 0 | 2023-12-14 18:57:56+00:00 | 2k |
sockheadrps/AIODesa | aiodesa/database.py | [
{
"identifier": "make_schema",
"path": "aiodesa/utils/table.py",
"snippet": "def make_schema(name: str, data_cls: Any) -> TableSchema:\n \"\"\"\n Generate a TableSchema based on the provided data class.\n\n Args:\n name: The name of the table.\n data_cls: A data class defining the... | from dataclasses import is_dataclass, fields
from typing import Tuple, Callable, Any, Coroutine
from pathlib import Path
from aiodesa.utils.table import make_schema, TableSchema
import aiosqlite | 1,028 | """
aiodesa.Database: Simple SQLite Database Interface
This module provides the `Db` class, a simple SQLite database interface that
supports asynchronous operations.
Classes:
- :class:`Db`: Represents a simple SQLite database interface.
Example:
.. code-block:: python
from aiodesa import Db
class Users:
... | """
aiodesa.Database: Simple SQLite Database Interface
This module provides the `Db` class, a simple SQLite database interface that
supports asynchronous operations.
Classes:
- :class:`Db`: Represents a simple SQLite database interface.
Example:
.. code-block:: python
from aiodesa import Db
class Users:
... | schema_ = make_schema(str(field.default), schema) | 0 | 2023-12-09 05:52:25+00:00 | 2k |
DavidBellamy/labrador | scripts/preprocessing/pretraining_jsonl_to_bert_bags.py | [
{
"identifier": "json_lines_loader",
"path": "lab_transformers/utils.py",
"snippet": "def json_lines_loader(filepath: Union[str, Path]) -> List[Dict[str, Any]]:\n \"\"\"Loads the JSON lines located at filepath and returns them as a list of flat dictionaries.\"\"\"\n\n jsonl = []\n with open(fil... | import json
import os.path as op
import sys
import numpy as np
import pandas as pd
from tqdm import tqdm
from lab_transformers.utils import json_lines_loader, NpEncoder | 1,528 |
def make_lab_bags_for_bert(
jsonl_batch: list, filepath: str, max_time_delta: float, min_bag_length: int = 3
) -> None:
"""Creates all unique bags of labs spanning max_time_delta (and with size min_bag_length) for the patients
in jsonl_batch.
Inputs:
> jsonl_batch: a list of JSON lines, where e... |
def make_lab_bags_for_bert(
jsonl_batch: list, filepath: str, max_time_delta: float, min_bag_length: int = 3
) -> None:
"""Creates all unique bags of labs spanning max_time_delta (and with size min_bag_length) for the patients
in jsonl_batch.
Inputs:
> jsonl_batch: a list of JSON lines, where e... | json_record = json.dumps(patient, cls=NpEncoder) | 1 | 2023-12-09 20:40:17+00:00 | 2k |
NLP-Core-Team/RealCode_eval | lm_eval/generators.py | [
{
"identifier": "Task",
"path": "lm_eval/datatypes.py",
"snippet": "class Task:\n repo: str\n repo_n: int\n path_from_root: str\n left_context: str\n right_context: str\n gt: str\n total_tests: int"
},
{
"identifier": "BaseParser",
"path": "lm_eval/context_parser.py",
... | import os
import typing as tp
import json
import re
import torch
import logging
from pathlib import Path
from dataclasses import asdict, fields
from transformers import AutoTokenizer, AutoModelForCausalLM, StoppingCriteria, StoppingCriteriaList
from tqdm import tqdm
from .datatypes import Task
from .context_parser impo... | 1,355 |
logger = logging.getLogger("RealCode")
class InfillGenerator:
def __init__(self,
model_path: str,
num_samples: int,
prefix_tokens: tp.Union[str, tp.List[int]] = [],
middle_tokens: tp.Union[str, tp.List[int]] = [],
suffix_tokens: tp.Union[str, tp.List[int]] = [],
... |
logger = logging.getLogger("RealCode")
class InfillGenerator:
def __init__(self,
model_path: str,
num_samples: int,
prefix_tokens: tp.Union[str, tp.List[int]] = [],
middle_tokens: tp.Union[str, tp.List[int]] = [],
suffix_tokens: tp.Union[str, tp.List[int]] = [],
... | def _prepare_tokens(self, task: Task) -> torch.Tensor: | 0 | 2023-12-12 12:43:06+00:00 | 2k |
centrifugal/grand-chat-tutorial | backend/chat/views.py | [
{
"identifier": "Message",
"path": "backend/chat/models.py",
"snippet": "class Message(models.Model):\n room = models.ForeignKey(Room, related_name='messages', on_delete=models.CASCADE)\n # Note, message may have null user – we consider such messages \"system\". These messages\n # initiated by ... | import json
import logging
import requests
from requests.adapters import HTTPAdapter, Retry
from django.conf import settings
from django.db import transaction
from django.db.models import Exists, OuterRef, Count
from django.shortcuts import get_object_or_404
from django.utils import timezone
from rest_framework import ... | 982 |
class RoomListViewSet(ListModelMixin, GenericViewSet):
serializer_class = RoomSerializer
permission_classes = [IsAuthenticated]
def get_queryset(self):
|
class RoomListViewSet(ListModelMixin, GenericViewSet):
serializer_class = RoomSerializer
permission_classes = [IsAuthenticated]
def get_queryset(self): | return Room.objects.annotate( | 1 | 2023-12-06 10:13:26+00:00 | 2k |
shinkungoo/SymbolicCDM | SCDM/parameter.py | [
{
"identifier": "accuracy",
"path": "SCDM/eval.py",
"snippet": "def accuracy(y_pred, y_true, threshold=0.5, weights=None):\n pred = np.array(y_pred)\n true = np.array(y_true)\n result = np.where(pred > threshold, 1, 0)\n if weights is not None:\n correct = np.sum((true == result) * we... | import torch
import torch.nn as nn
from tqdm import tqdm
from .eval import accuracy, area_under_curve, f1_score
from .utility import init_interaction_function | 1,076 |
class ComputeIF(nn.Module):
def __init__(self,
student_number,
question_number,
knowledge_number):
super(ComputeIF, self).__init__()
self.student_emb = nn.Embedding(student_number, knowledge_number)
self.difficulty = nn.Embedding(question... |
class ComputeIF(nn.Module):
def __init__(self,
student_number,
question_number,
knowledge_number):
super(ComputeIF, self).__init__()
self.student_emb = nn.Embedding(student_number, knowledge_number)
self.difficulty = nn.Embedding(question... | f1 = f1_score(y_pred, y_true) | 2 | 2023-12-09 13:37:15+00:00 | 2k |
pan-x-c/EE-LLM | megatron/core/tensor_parallel/mappings.py | [
{
"identifier": "get_tensor_and_expert_parallel_group",
"path": "megatron/core/parallel_state.py",
"snippet": "def get_tensor_and_expert_parallel_group():\n assert (\n _TENSOR_AND_EXPERT_PARALLEL_GROUP is not None\n ), 'tensor and expert parallel group is not initialized'\n return _TENSO... | import torch
from megatron.core.parallel_state import (
get_tensor_and_expert_parallel_group,
get_tensor_model_parallel_group,
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
)
from .utils import split_tensor_along_last_dim | 789 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
def _reduce(input_):
"""All-reduce the input tensor across model parallel group."""
# Bypass the function if we are using only 1 GPU.
if get_tensor_model_parallel_world_size() == 1:
return input_
# All-reduce.
torch.distri... | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
def _reduce(input_):
"""All-reduce the input tensor across model parallel group."""
# Bypass the function if we are using only 1 GPU.
if get_tensor_model_parallel_world_size() == 1:
return input_
# All-reduce.
torch.distri... | input_list = split_tensor_along_last_dim(input_, world_size) | 4 | 2023-12-07 08:29:38+00:00 | 2k |
kanadeblisst00/WeChat-PyRobot | src/wechat_pyrobot/hookmsg32.py | [
{
"identifier": "CDataJSONEncoder",
"path": "src/wechat_pyrobot/ctypes_json.py",
"snippet": "class CDataJSONEncoder(JSONEncoder):\r\n def default(self, obj):\r\n if isinstance(obj, (Array, list)):\r\n return [self.default(e) for e in obj]\r\n\r\n if isinstance(obj, _Pointer):... | import json
from py_process_hooker import Hook
from py_process_hooker.winapi import *
from .ctypes_json import CDataJSONEncoder
from .offset import CALL_OFFSET
| 904 |
struct_size = 0x2E0
class GeneralStructW32(Structure):
_fields_ = [
('value', c_wchar_p),
('len1', c_uint32),
('len2', c_uint32),
('_unkown_value0', c_uint32),
('_unkown_value1', c_uint32)
]
class WeChatMsgStruct32(Structure):
_fields_ = [
... |
struct_size = 0x2E0
class GeneralStructW32(Structure):
_fields_ = [
('value', c_wchar_p),
('len1', c_uint32),
('len2', c_uint32),
('_unkown_value0', c_uint32),
('_unkown_value1', c_uint32)
]
class WeChatMsgStruct32(Structure):
_fields_ = [
... | class MyCDataJSONEncoder(CDataJSONEncoder):
| 0 | 2023-12-12 08:43:11+00:00 | 2k |
mitrefireline/simharness | simharness2/environments/tests/check_reactive_environments.py | [
{
"identifier": "ReactiveDiscreteHarness",
"path": "simharness2/environments/reactive.py",
"snippet": "class ReactiveHarness(RLHarness): # noqa: D205,D212,D415\n def __init__(self, config: EnvContext) -> None:\n def set_trial_results_path(self, path: str) -> None:\n def step(\n self, ac... | import argparse
import logging
import os
import yaml
import traceback
from typing import Any, Dict
from ray.rllib.utils.pre_checks.env import check_gym_environments
from simharness2.environments.reactive import (
ReactiveDiscreteHarness,
ReactiveHarness,
)
from simharness2.sim_registry import get_simula... | 1,045 | # noqa : D212,D415
"""
To avoid an ImportError and/or ModueNotFoundError, run this script as a module:
python -m simharness2.environments.tests.check_reactive_environments \
--config <path_to_config_file> --env-type <train|eval>
(above command should be executed from the root of the repository)
"""
def setup_... | # noqa : D212,D415
"""
To avoid an ImportError and/or ModueNotFoundError, run this script as a module:
python -m simharness2.environments.tests.check_reactive_environments \
--config <path_to_config_file> --env-type <train|eval>
(above command should be executed from the root of the repository)
"""
def setup_... | def reactive_discrete_env_creator(env_config: str) -> ReactiveDiscreteHarness: | 0 | 2023-12-08 19:13:31+00:00 | 2k |
JeffJerseyCow/eviloauth | eviloauth/dispatcher.py | [
{
"identifier": "IDP",
"path": "eviloauth/idp.py",
"snippet": "class IDP():\n idps = get_idps()\n authz_endpoint = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'\n token_endpoint = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'\n\n def __init__(self, idp, redi... | import sys
import logging
from eviloauth.idp import IDP
from eviloauth.exceptions import EviloauthCommandException | 1,536 |
class Dispatcher:
def __init__(self, flask_server, module_dict, cache, redirect_server):
logging.debug('Initializing dispatcher')
logging.debug(f'\tFlask server: {flask_server}')
logging.debug(f'\tModule dict: {module_dict}')
logging.debug(f'\tCache: {cache}')
logging.debug... |
class Dispatcher:
def __init__(self, flask_server, module_dict, cache, redirect_server):
logging.debug('Initializing dispatcher')
logging.debug(f'\tFlask server: {flask_server}')
logging.debug(f'\tModule dict: {module_dict}')
logging.debug(f'\tCache: {cache}')
logging.debug... | idp = IDP(arg, self.redirect_server) | 0 | 2023-12-09 11:21:25+00:00 | 2k |
racinette/querky | querky/backends/postgresql/asyncpg/name_type_mapper.py | [
{
"identifier": "PostgresqlNameTypeMapper",
"path": "querky/backends/postgresql/name_type_mapper.py",
"snippet": "class PostgresqlNameTypeMapper(PostgresqlTypeMapper):\n def __init__(self, typemap: dict[str, dict[str, TypeMetaData]]):\n self.type_cache = dict()\n # копируем\n sel... | from querky.backends.postgresql.name_type_mapper import PostgresqlNameTypeMapper
from querky.base_types import TypeMetaData
from querky.common_imports import DATETIME_MODULE
from querky.common_imports import DECIMAL as DECIMAL_IMPORT
from querky.common_imports import UUID as UUID_IMPORT
from querky.common_imports impor... | 1,108 |
ASYNCPG_RANGE_IMPORT = "from asyncpg import Range as _Range"
ASYNCPG_RECORD_IMPORT = "from asyncpg import Record as _Record"
ASYNCPG_BITSTRING_IMPORT = "from asyncpg import BitString as _BitString"
ASYNCPG_BOX_IMPORT = "from asyncpg import Box as _Box"
ASYNCPG_CIRCLE_IMPORT = "from asyncpg import Circle as _Circle"
... |
ASYNCPG_RANGE_IMPORT = "from asyncpg import Range as _Range"
ASYNCPG_RECORD_IMPORT = "from asyncpg import Record as _Record"
ASYNCPG_BITSTRING_IMPORT = "from asyncpg import BitString as _BitString"
ASYNCPG_BOX_IMPORT = "from asyncpg import Box as _Box"
ASYNCPG_CIRCLE_IMPORT = "from asyncpg import Circle as _Circle"
... | INT = TypeMetaData("int") | 1 | 2023-12-13 15:16:34+00:00 | 2k |
Shahzadnit/EZ-CLIP | utils/solver.py | [
{
"identifier": "WarmupMultiStepLR",
"path": "utils/lr_scheduler.py",
"snippet": "class WarmupMultiStepLR(WarmupLR):\r\n\r\n def __init__(self,\r\n optimizer,\r\n milestones,\r\n gamma=0.1,\r\n warmup_epochs=0,\r\n warmup... | import torch.optim as optim
from utils.lr_scheduler import WarmupMultiStepLR, WarmupCosineAnnealingLR
| 1,071 |
def _optimizer(config, model):
if config.solver.optim == 'adam':
optimizer = optim.Adam([{'params': model.parameters()}],
lr=config.solver.lr, betas=(0.9, 0.98), eps=1e-8,
weight_decay=0.2) # Params used from paper, the lr is smaller, ... |
def _optimizer(config, model):
if config.solver.optim == 'adam':
optimizer = optim.Adam([{'params': model.parameters()}],
lr=config.solver.lr, betas=(0.9, 0.98), eps=1e-8,
weight_decay=0.2) # Params used from paper, the lr is smaller, ... | lr_scheduler = WarmupMultiStepLR(
| 0 | 2023-12-12 13:11:20+00:00 | 2k |
Gwolfgit/Authoritah | models.py | [
{
"identifier": "get_tailscale_ip4",
"path": "functions.py",
"snippet": "def get_tailscale_ip4() -> str:\n try:\n output = subprocess.check_output(\n [\"tailscale\", \"ip\", \"-4\"],\n stderr=subprocess.STDOUT,\n universal_newlines=True,\n )\n ip ... | import orjson
from typing import Any, Dict, Tuple
from functions import get_tailscale_ip4, get_tailscale_ip6
from pathlib import Path | 738 |
class dotdict(dict):
"""dot.notation access to dictionary attributes"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def load_config():
with open(Path(Path(__file__).parent.resolve(), "config.json"), "r") as fd:
return dotdict(orjson.loads(fd.read... |
class dotdict(dict):
"""dot.notation access to dictionary attributes"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def load_config():
with open(Path(Path(__file__).parent.resolve(), "config.json"), "r") as fd:
return dotdict(orjson.loads(fd.read... | self._ip = get_tailscale_ip4() | 0 | 2023-12-13 01:17:53+00:00 | 2k |
bluuewhale/nexon-openapi-python | src/nexon_openapi/utils/_transform.py | [
{
"identifier": "is_list",
"path": "src/nexon_openapi/utils/_utils.py",
"snippet": "def is_list(obj: object) -> TypeGuard[list[object]]:\n return isinstance(obj, list)"
},
{
"identifier": "is_mapping",
"path": "src/nexon_openapi/utils/_utils.py",
"snippet": "def is_mapping(obj: object... | from typing import Any, Mapping, Optional, TypeVar, Union, cast
from datetime import date, datetime
from typing_extensions import Literal, get_args, override, get_type_hints
from ._utils import (
is_list,
is_mapping,
is_list_type,
is_union_type,
extract_type_arg,
is_required_type,
is_annotat... | 1,275 | from __future__ import annotations
_T = TypeVar("_T")
PropertyFormat = Literal["iso8601", "custom"]
class PropertyInfo:
"""Metadata class to be used in Annotated types to provide information about a given type.
For example:
class MyParams(TypedDict):
account_holder_name: Annotated[str, Pro... | from __future__ import annotations
_T = TypeVar("_T")
PropertyFormat = Literal["iso8601", "custom"]
class PropertyInfo:
"""Metadata class to be used in Annotated types to provide information about a given type.
For example:
class MyParams(TypedDict):
account_holder_name: Annotated[str, Pro... | if is_annotated_type(type_): | 6 | 2023-12-14 18:12:17+00:00 | 2k |
Jack24658735/FedLGT | dataloaders/flair_dataset_fed.py | [
{
"identifier": "get_unk_mask_indices",
"path": "dataloaders/data_utils.py",
"snippet": "def get_unk_mask_indices(image,testing,num_labels,known_labels,epoch=1):\n if testing:\n # for consistency across epochs and experiments, seed using hashed image array \n random.seed(hashlib.sha1(np... | import os
import torch
import numpy as np
import pickle
import h5py
from torch.utils.data import Dataset, DataLoader
from pdb import set_trace as stop
from dataloaders.data_utils import get_unk_mask_indices,image_loader | 1,023 |
class FlairFedDataset(Dataset):
def __init__(self, inp_data, split, num_labels, data_file, img_root, curr_user=None, max_samples=-1,transform=None,known_labels=0,testing=False, label_mapping=None, fine_grained_label_mapping=None):
super(FlairFedDataset, self).__init__()
# print(data_file)
... |
class FlairFedDataset(Dataset):
def __init__(self, inp_data, split, num_labels, data_file, img_root, curr_user=None, max_samples=-1,transform=None,known_labels=0,testing=False, label_mapping=None, fine_grained_label_mapping=None):
super(FlairFedDataset, self).__init__()
# print(data_file)
... | unk_mask_indices = get_unk_mask_indices(image,self.testing,self.num_labels,self.known_labels) | 0 | 2023-12-09 09:16:59+00:00 | 2k |
AgriCodeHub/dairy-django-backend | production/validators.py | [
{
"identifier": "CowCategoryChoices",
"path": "core/choices.py",
"snippet": "class CowCategoryChoices(models.TextChoices):\n \"\"\"\n Choices for the category of a cow.\n\n Choices:\n - `CALF`: Represents a calf.\n - `WEANER`: Represents a weaner.\n - `HEIFER`: Represents a heifer.\n ... | from datetime import timedelta
from django.core.exceptions import ValidationError
from core.choices import CowCategoryChoices, CowAvailabilityChoices
from core.utils import todays_date
from production.choices import LactationStageChoices
from users.choices import SexChoices
from production.models import Lactati... | 1,470 |
class LactationValidator:
"""
Provides validation methods for lactation records associated with cows.
Methods:
- `validate_age(start_date, cow)`: Validates the start date of lactation based on the cow's age.
- `validate_cow_origin(cow)`: Validates that manual entry is allowed only for bought co... |
class LactationValidator:
"""
Provides validation methods for lactation records associated with cows.
Methods:
- `validate_age(start_date, cow)`: Validates the start date of lactation based on the cow's age.
- `validate_cow_origin(cow)`: Validates that manual entry is allowed only for bought co... | if category not in CowCategoryChoices.values: | 0 | 2023-12-09 06:56:42+00:00 | 2k |
PeriniM/Rotary-Pendulum-RL | control/reinforcement_learning/DQN/Agent.py | [
{
"identifier": "DeepQNetwork",
"path": "control/reinforcement_learning/DQN/DeepQNetwork.py",
"snippet": "class DeepQNetwork:\n \"\"\"\n Deep Q Network to approximate the Q function\n \"\"\"\n def __init__(self, lr, num_actions, input_dims, fc_dims = [32, 32], opt='adam', loss='mse'):\n\n ... | import os
import configparser
import ast
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import copy
import time
import tensorflow as tf
from matplotlib import cm
from datetime import datetime
from tensorflow.keras import backend as K
from tensorflow.keras.callbacks import T... | 1,295 | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
class Agent:
"""
DQN Agent
- Take an environment
- Set up the deep neural network
- Store the experience
- Choose action
- Train the network
- Evaluate the network
"""
def __init__(self, env):
# check if gpu is available
... | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
class Agent:
"""
DQN Agent
- Take an environment
- Set up the deep neural network
- Store the experience
- Choose action
- Train the network
- Evaluate the network
"""
def __init__(self, env):
# check if gpu is available
... | self.replay_buffer = ReplayBuffer(self.buffer_size) | 1 | 2023-12-09 11:22:54+00:00 | 2k |
Kokonico/ObjLog | objlog/Base/LogNode.py | [
{
"identifier": "Debug",
"path": "objlog/LogMessages.py",
"snippet": "class Debug(LogMessage):\n \"\"\"the default debug message, with blue color\"\"\"\n level = \"DEBUG\"\n color = \"\\033[94m\""
},
{
"identifier": "LogMessage",
"path": "objlog/Base/LogMessage.py",
"snippet": "... | from objlog.LogMessages import Debug
from objlog.Base.LogMessage import LogMessage # "no parent package" error happens when I don't specify the package,
from collections import deque | 875 | """The LogNode class, the main class of the ObjLogger"""
# IDK why
class LogNode:
"""A LogNode, the main class of the ObjLogger. It can log messages to a file, to the console, or both."""
open = open # this code is probably the reason why my dad left me
# this is clearly not a good way to do this, but... | """The LogNode class, the main class of the ObjLogger"""
# IDK why
class LogNode:
"""A LogNode, the main class of the ObjLogger. It can log messages to a file, to the console, or both."""
open = open # this code is probably the reason why my dad left me
# this is clearly not a good way to do this, but... | if not isinstance(message, LogMessage): | 1 | 2023-12-08 20:41:18+00:00 | 2k |
anyquest/pyaq | aq/providers/gemini/provider.py | [
{
"identifier": "BaseProvider",
"path": "aq/providers/provider.py",
"snippet": "class BaseProvider:\n async def create_completion(self, request: ChatCompletionRequest) -> ChatCompletionResponse:\n pass"
},
{
"identifier": "ProviderError",
"path": "aq/providers/provider.py",
"sn... | import logging
import re
from typing import Dict, Any, Optional, List, Literal
from pydantic import BaseModel
from ..provider import BaseProvider, ProviderError
from ..types import ChatCompletionRequest, ChatCompletionResponse, ChatCompletionMessage, Choice, Error
from ...http_client import AsyncHttpClient | 1,233 |
class InlineData(BaseModel):
mimeType: str
data: str
class Part(BaseModel):
text: Optional[str] = None
inlineData: Optional[InlineData] = None
class Content(BaseModel):
role: Literal["user", "model"]
parts: List[Part]
class GenerationConfig(BaseModel):
temperature: float = 0.5
... |
class InlineData(BaseModel):
mimeType: str
data: str
class Part(BaseModel):
text: Optional[str] = None
inlineData: Optional[InlineData] = None
class Content(BaseModel):
role: Literal["user", "model"]
parts: List[Part]
class GenerationConfig(BaseModel):
temperature: float = 0.5
... | async def create_completion(self, request: ChatCompletionRequest) -> ChatCompletionResponse: | 3 | 2023-12-14 13:25:52+00:00 | 2k |
multimodallearning/DG-TTA | dg_tta/tta/ipynb_utils.py | [
{
"identifier": "get_data_filepaths",
"path": "dg_tta/tta/config_log_utils.py",
"snippet": "def get_data_filepaths(tta_dataset_name, tta_dataset_bucket):\n raw_tta_dataset_dir = Path(nnUNet_raw, tta_dataset_name)\n if tta_dataset_bucket == \"imagesTr\":\n source_folders = [raw_tta_dataset_d... | import json
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import torch
from mpl_toolkits.axes_grid1.axes_grid import ImageGrid
from nnunetv2.imageio.simpleitk_reader_writer import SimpleITKIO
from dg_tta.tta.config_log_utils import (
get_data_filepaths,
get_dgtta_colormap,
get_resourc... | 1,136 |
def read_image(source_data_paths, path_idx):
if source_data_paths is None:
return None, None
source_img, source_sitk_stuff = SimpleITKIO().read_images(
source_data_paths[path_idx : path_idx + 1]
)
source_img = source_img[0]
return torch.tensor(source_img)[None, None, :], source_... |
def read_image(source_data_paths, path_idx):
if source_data_paths is None:
return None, None
source_img, source_sitk_stuff = SimpleITKIO().read_images(
source_data_paths[path_idx : path_idx + 1]
)
source_img = source_img[0]
return torch.tensor(source_img)[None, None, :], source_... | cmap = get_dgtta_colormap() | 1 | 2023-12-08 08:43:11+00:00 | 2k |
tommy-xq/SA2VP | vpt_main/src/models/resnet.py | [
{
"identifier": "MLP",
"path": "vpt_main/src/models/mlp.py",
"snippet": "class MLP(nn.Module):\n def __init__(\n self,\n input_dim: int,\n mlp_dims: List[int],\n dropout: float = 0.1,\n nonlinearity: Type[nn.Module] = nn.ReLU,\n normalization: Type[nn.Module]... | import torch
import torch.nn as nn
import torchvision as tv
from collections import OrderedDict
from torchvision import models
from .mlp import MLP
from ..utils import logging | 772 | #!/usr/bin/env python3
"""
ResNet-related models:
"imagenet_sup_rn18",
"imagenet_sup_rn34",
"imagenet_sup_rn50",
"imagenet_sup_rn101",
"imagenet_sup_rn152",
"mocov3_rn50"
"""
| #!/usr/bin/env python3
"""
ResNet-related models:
"imagenet_sup_rn18",
"imagenet_sup_rn34",
"imagenet_sup_rn50",
"imagenet_sup_rn101",
"imagenet_sup_rn152",
"mocov3_rn50"
"""
| logger = logging.get_logger("visual_prompt") | 1 | 2023-12-12 13:19:17+00:00 | 2k |
SooLab/DDCOT | utils_evaluate.py | [
{
"identifier": "caculate_bleu",
"path": "evaluations.py",
"snippet": "def caculate_bleu(results, data, gram):\n bleus = []\n for qid, output in results.items():\n prediction = output\n target = data[qid]\n # target = data[qid]['lecture'] + data[qid]['solution']\n targe... | import os
import json
import argparse
import warnings
import pandas as pd
from sentence_transformers import SentenceTransformer
from evaluations import caculate_bleu, caculate_rouge, caculate_similariry | 973 | '''
Adapted from https://github.com/lupantech/ScienceQA
'''
warnings.filterwarnings('ignore')
def get_acc_with_contion(res_pd, key, values):
if isinstance(values, list):
total_pd = res_pd[res_pd[key].isin(values)]
else:
total_pd = res_pd[res_pd[key] == values]
correct_pd = total_pd[total_... | '''
Adapted from https://github.com/lupantech/ScienceQA
'''
warnings.filterwarnings('ignore')
def get_acc_with_contion(res_pd, key, values):
if isinstance(values, list):
total_pd = res_pd[res_pd[key].isin(values)]
else:
total_pd = res_pd[res_pd[key] == values]
correct_pd = total_pd[total_... | similariry = caculate_similariry(rationale_data, results_reference, model) | 2 | 2023-12-14 20:47:08+00:00 | 2k |
Qazalbash/jaxampler | jaxampler/_src/rvs/bernoulli.py | [
{
"identifier": "Numeric",
"path": "jaxampler/_src/typing.py",
"snippet": ""
},
{
"identifier": "Binomial",
"path": "jaxampler/_src/rvs/binomial.py",
"snippet": "class Binomial(DiscreteRV):\n r\"\"\"Binomial random variable\n .. math::\n X\\sim Bin(p,n) \\iff P(X=x|p,n)=\\bi... | from typing import Any, Optional
from ..typing import Numeric
from .binomial import Binomial | 959 | # Copyright 2023 The Jaxampler Authors
#
# 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... | # Copyright 2023 The Jaxampler Authors
#
# 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... | def __init__(self, p: Numeric | Any, name: Optional[str] = None) -> None: | 0 | 2023-12-11 04:27:17+00:00 | 2k |
GXNU-ZhongLab/ODTrack | lib/models/odtrack/base_backbone.py | [
{
"identifier": "PatchEmbed",
"path": "lib/models/layers/patch_embed.py",
"snippet": "class PatchEmbed(nn.Module):\r\n \"\"\" 2D Image to Patch Embedding\r\n \"\"\"\r\n\r\n def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):\r\n supe... | from functools import partial
from timm.models.vision_transformer import resize_pos_embed
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
from lib.models.layers.patch_embed import PatchEmbed
from lib.models.odtrack.utils import combine_tokens, recover_tokens
import torch
import torch.nn as nn
i... | 1,542 |
class BaseBackbone(nn.Module):
def __init__(self):
super().__init__()
# for original ViT
self.pos_embed = None
self.img_size = [224, 224]
self.patch_size = 16
self.embed_dim = 384
self.cat_mode = 'direct'
self.pos_embed_z = None
... |
class BaseBackbone(nn.Module):
def __init__(self):
super().__init__()
# for original ViT
self.pos_embed = None
self.img_size = [224, 224]
self.patch_size = 16
self.embed_dim = 384
self.cat_mode = 'direct'
self.pos_embed_z = None
... | self.patch_embed = PatchEmbed(img_size=self.img_size, patch_size=new_patch_size, in_chans=3,
| 0 | 2023-12-10 03:57:19+00:00 | 2k |
yilin-bao/nnanim | TestingCode/transformer.py | [
{
"identifier": "Attention",
"path": "TestingCode/modules.py",
"snippet": "class Attention(nn.Module):\n def __init__(\n self, dim, num_heads=8, qkv_bias=False, attn_drop=0.0, proj_drop=0.0\n ):\n super(Attention, self).__init__()\n\n assert (\n dim % num_heads == 0... | from torch import nn
from TestingCode.modules import Attention, FeedForward, PreNorm | 1,079 |
class Transformer(nn.Module):
def __init__(
self,
dim,
depth,
heads,
mlp_ratio=4.0,
attn_dropout=0.0,
dropout=0.0,
qkv_bias=True,
revised=False,
):
super().__init__()
self.layers = nn.ModuleList([])
assert isinsta... |
class Transformer(nn.Module):
def __init__(
self,
dim,
depth,
heads,
mlp_ratio=4.0,
attn_dropout=0.0,
dropout=0.0,
qkv_bias=True,
revised=False,
):
super().__init__()
self.layers = nn.ModuleList([])
assert isinsta... | FeedForward(dim, mlp_dim, dropout_rate=dropout,), | 1 | 2023-12-05 22:01:06+00:00 | 2k |
Tlntin/booking_simulator | modelscope_agent/llm/custom_llm.py | [
{
"identifier": "AgentType",
"path": "modelscope_agent/agent_types.py",
"snippet": "class AgentType(str, Enum):\n\n DEFAULT = 'default'\n \"\"\"\"\"\"\n\n MS_AGENT = 'ms-agent'\n \"\"\"An agent that uses the ModelScope-agent specific format does a reasoning step before acting .\n \"\"\"\n... | import os
import json
import requests
import traceback
from modelscope_agent.agent_types import AgentType
from .base import LLM
from .utils import DEFAULT_MESSAGE | 809 |
class CustomLLM(LLM):
'''
This method is for the service that provide llm serving through http.
user could override the result parsing method if needed
While put all the necessary information in the env variable, such as Token, Model, URL
'''
name = 'custom_llm'
def __init__... |
class CustomLLM(LLM):
'''
This method is for the service that provide llm serving through http.
user could override the result parsing method if needed
While put all the necessary information in the env variable, such as Token, Model, URL
'''
name = 'custom_llm'
def __init__... | self.agent_type = self.cfg.get('agent_type', AgentType.DEFAULT) | 0 | 2023-12-12 04:24:00+00:00 | 2k |
dx-dtran/gpt2-mlx | generate.py | [
{
"identifier": "GPT",
"path": "transformer.py",
"snippet": "class GPT(nn.Module):\n def __init__(self, config: GPTConfig):\n super().__init__()\n assert config.vocab_size is not None\n assert config.block_size is not None\n self.config = config\n\n self.wte = nn.Em... | import argparse
import tiktoken
import time
import mlx.core as mx
from mlx.utils import tree_unflatten, tree_flatten
from transformer import GPT, GPTConfig | 1,096 |
def load_model(model_name):
config_args = {
"gpt2": dict(n_layer=12, n_head=12, n_embd=768),
"gpt2-medium": dict(n_layer=24, n_head=16, n_embd=1024),
"gpt2-large": dict(n_layer=36, n_head=20, n_embd=1280),
"gpt2-xl": dict(n_layer=48, n_head=25, n_embd=1600),
}[model_name]
... |
def load_model(model_name):
config_args = {
"gpt2": dict(n_layer=12, n_head=12, n_embd=768),
"gpt2-medium": dict(n_layer=24, n_head=16, n_embd=1024),
"gpt2-large": dict(n_layer=36, n_head=20, n_embd=1280),
"gpt2-xl": dict(n_layer=48, n_head=25, n_embd=1600),
}[model_name]
... | model = GPT(config) | 0 | 2023-12-09 03:33:57+00:00 | 2k |
chenchenygu/watermark-learnability | kgw_watermarking/watermark_reliability_release/utils/generation.py | [
{
"identifier": "load_lfqa",
"path": "kgw_watermarking/watermark_reliability_release/utils/data/lfqa.py",
"snippet": "def load_lfqa(args=None, path=\"./utils/data/lfqa.jsonl\"):\n cols_to_load = [\"prefix\", \"gold_completion\", \"title\", \"selftext\", \"q_id\"]\n\n args.dataset_config_name = Non... | import torch
from datasets import load_dataset, IterableDataset
from torch import Tensor
from tokenizers import Tokenizer
from transformers import (
AutoTokenizer,
LlamaTokenizer,
AutoModelForSeq2SeqLM,
AutoModelForCausalLM,
DataCollatorWithPadding,
)
from .data.lfqa import load_lfqa
from .data.essa... | 1,351 | # coding=utf-8
# Copyright 2023 Authors of "A Watermark for Large Language Models"
# available at https://arxiv.org/abs/2301.10226
#
# 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... | # coding=utf-8
# Copyright 2023 Authors of "A Watermark for Large Language Models"
# available at https://arxiv.org/abs/2301.10226
#
# 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... | dataset = load_lfqa(args) | 0 | 2023-12-07 16:45:33+00:00 | 2k |
skyoux/SemAIM | main_knn.py | [
{
"identifier": "interpolate_pos_embed",
"path": "util/pos_embed.py",
"snippet": "def interpolate_pos_embed(model, checkpoint_model):\n if 'pos_embed' in checkpoint_model:\n pos_embed_checkpoint = checkpoint_model['pos_embed']\n embedding_size = pos_embed_checkpoint.shape[-1]\n n... | import os
import sys
import argparse
import numpy as np
import torch
import torch.distributed as dist
import torch.backends.cudnn as cudnn
import timm.models as timm_models
import util.misc as misc
from torch import nn
from torchvision import datasets
from torchvision import transforms as pth_transforms
from torchvisio... | 887 | #!/usr/bin/env python
def extract_feature_pipeline(args):
######################## preparing data ... ########################
resize_size = 256 if args.input_size == 224 else 512
transform = pth_transforms.Compose([
pth_transforms.Resize(resize_size, interpolation=3),
pth_transforms.Cen... | #!/usr/bin/env python
def extract_feature_pipeline(args):
######################## preparing data ... ########################
resize_size = 256 if args.input_size == 224 else 512
transform = pth_transforms.Compose([
pth_transforms.Resize(resize_size, interpolation=3),
pth_transforms.Cen... | model = models_vit.__dict__[args.model]( | 1 | 2023-12-10 15:17:11+00:00 | 2k |
boweniac/autogan | autogan/oai/generate_utils.py | [
{
"identifier": "chat_completions",
"path": "autogan/oai/openai_utils.py",
"snippet": "def chat_completions(messages: list, api_key: Dict, request_timeout: int, max_retries: int,\n stream_mode: Optional[bool] = None):\n \"\"\"OpenAI interface and OpenAI like interface call\n\n ... | import time
from typing import Optional, List
from autogan.oai.openai_utils import chat_completions
from autogan.oai.config_utils import LLMConfig
from autogan.oai.count_tokens_utils import count_text_tokens
from autogan.utils.response import ResponseFuncType | 1,285 |
def generate_chat_completion(llm_config: LLMConfig, messages: List, agent_name: str, gen: str,
response_func: ResponseFuncType, stream_mode: Optional[bool] = None)\
-> tuple[Optional[str], Optional[int]]:
"""Call the LLM interface
Currently, only the chatgpt model of open... |
def generate_chat_completion(llm_config: LLMConfig, messages: List, agent_name: str, gen: str,
response_func: ResponseFuncType, stream_mode: Optional[bool] = None)\
-> tuple[Optional[str], Optional[int]]:
"""Call the LLM interface
Currently, only the chatgpt model of open... | for message in chat_completions(messages, api_key, llm_config.request_timeout, | 0 | 2023-12-06 03:24:34+00:00 | 2k |
JingHao99/IDR-Ingredients-oriented-Degradation-Reformulation | data/IDR_dataset.py | [
{
"identifier": "crop_HWC_img",
"path": "utils/data_util.py",
"snippet": "def crop_HWC_img(image, base=64):\r\n \"\"\"\r\n 裁切到multiple of base的size上\r\n :param image: H,W,C\r\n :param base: (int)\r\n :return:\r\n \"\"\"\r\n h = image.shape[0]\r\n w = image.shape[1]\r\n crop_h ... | import os
import random
import copy
import numpy as np
from PIL import Image, ImageFile
from torch.utils.data import Dataset
from torchvision.transforms import ToPILImage, Compose, RandomCrop, ToTensor
from utils.data_util import crop_HWC_img, random_augmentation, padding, onehot, smooth_one_hot
from sklearn.pr... | 1,386 | ImageFile.LOAD_TRUNCATED_IMAGES = True
class IDR_dataset(Dataset):
def __init__(self, dataset_opt):
super(IDR_dataset, self).__init__()
self.dataset_opt = dataset_opt
self.rs_ids = []
self.hazy_ids = []
| ImageFile.LOAD_TRUNCATED_IMAGES = True
class IDR_dataset(Dataset):
def __init__(self, dataset_opt):
super(IDR_dataset, self).__init__()
self.dataset_opt = dataset_opt
self.rs_ids = []
self.hazy_ids = []
| self.D = Degradation(dataset_opt)
| 5 | 2023-12-07 10:58:34+00:00 | 2k |
TACJu/Compositor | Compositor_Mask2Former/mask2former/modeling/meta_arch/mask_former_head.py | [
{
"identifier": "build_transformer_decoder",
"path": "Compositor_Mask2Former/mask2former/modeling/transformer_decoder/maskformer_transformer_decoder.py",
"snippet": "def build_transformer_decoder(cfg, in_channels, mask_classification=True):\n \"\"\"\n Build a instance embedding branch from `cfg.MO... | import logging
import fvcore.nn.weight_init as weight_init
from copy import deepcopy
from typing import Callable, Dict, List, Optional, Tuple, Union
from torch import nn
from torch.nn import functional as F
from detectron2.config import configurable
from detectron2.layers import Conv2d, ShapeSpec, get_norm
from detectr... | 1,245 | # Copyright (c) Facebook, Inc. and its affiliates.
@SEM_SEG_HEADS_REGISTRY.register()
class MaskFormerHead(nn.Module):
_version = 2
def _load_from_state_dict(
self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
):
version = local_metadata.get("v... | # Copyright (c) Facebook, Inc. and its affiliates.
@SEM_SEG_HEADS_REGISTRY.register()
class MaskFormerHead(nn.Module):
_version = 2
def _load_from_state_dict(
self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
):
version = local_metadata.get("v... | "transformer_predictor": build_transformer_decoder( | 0 | 2023-12-12 11:49:28+00:00 | 2k |
Mirascope/mirascope | cookbook/api_example/api_example.py | [
{
"identifier": "OpenAIChat",
"path": "mirascope/chat/models.py",
"snippet": "class OpenAIChat:\n \"\"\"A convenience wrapper for the OpenAI Chat client.\"\"\"\n\n def __init__(self, model: str = \"gpt-3.5-turbo\", api_key: Optional[str] = None):\n \"\"\"Initializes an instance of `OpenAICh... | import os
from fastapi import FastAPI
from mirascope import OpenAIChat, Prompt | 1,168 | """A FastAPI app integrated with a multi-chain prompt for recommending books on a topic
and then asking which one is the best for beginners.
How to Run:
uvicorn api_example:app --reload
"""
os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"
app = FastAPI()
class BookRecommendationPrompt(Prompt):
"""
Can... | """A FastAPI app integrated with a multi-chain prompt for recommending books on a topic
and then asking which one is the best for beginners.
How to Run:
uvicorn api_example:app --reload
"""
os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"
app = FastAPI()
class BookRecommendationPrompt(Prompt):
"""
Can... | model = OpenAIChat() | 0 | 2023-12-05 01:22:34+00:00 | 2k |
allisson/pysqsx | sqsx/queue.py | [
{
"identifier": "NoRetry",
"path": "sqsx/exceptions.py",
"snippet": "class NoRetry(Exception):\n \"\"\"\n This exception must be used when we need that the message will be removed from the queue\n \"\"\"\n\n pass"
},
{
"identifier": "Retry",
"path": "sqsx/exceptions.py",
"sni... | import logging
import signal
import time
from concurrent.futures import ThreadPoolExecutor, wait
from typing import Any, Callable, Dict, Optional
from pydantic import BaseModel, Field, PrivateAttr
from sqsx.exceptions import NoRetry, Retry
from sqsx.helper import backoff_calculator_seconds, base64_to_dict, dict_to_base... | 1,453 | logger = logging.getLogger(__name__)
queue_url_regex = r"(http|https)[:][\/]{2}[a-zA-Z0-9-_:.]+[\/][0-9]{12}[\/]{1}[a-zA-Z0-9-_]{0,80}"
class BaseQueueMixin:
def consume_messages(
self, max_messages: int = 1, max_threads: int = 1, wait_seconds: int = 10, run_forever: bool = True
) -> None:
log... |
logger = logging.getLogger(__name__)
queue_url_regex = r"(http|https)[:][\/]{2}[a-zA-Z0-9-_:.]+[\/][0-9]{12}[\/]{1}[a-zA-Z0-9-_]{0,80}"
class BaseQueueMixin:
def consume_messages(
self, max_messages: int = 1, max_threads: int = 1, wait_seconds: int = 10, run_forever: bool = True
) -> None:
... | except NoRetry: | 0 | 2023-12-13 10:48:29+00:00 | 2k |
turbopuffer/turbopuffer-python | turbopuffer/backend.py | [
{
"identifier": "TurbopufferError",
"path": "turbopuffer/error.py",
"snippet": "class TurbopufferError(Exception):\n pass"
},
{
"identifier": "AuthenticationError",
"path": "turbopuffer/error.py",
"snippet": "class AuthenticationError(TurbopufferError):\n pass"
},
{
"identi... | import json
import time
import traceback
import requests
import turbopuffer as tpuf
import gzip
from turbopuffer.error import TurbopufferError, AuthenticationError, APIError
from typing import Optional, List | 839 |
def find_api_key(api_key: Optional[str] = None) -> str:
if api_key is not None:
return api_key
elif tpuf.api_key is not None:
return tpuf.api_key
else:
raise AuthenticationError("No turbopuffer API key was provided.\n"
"Set the TURBOPUFFER_API_KEY ... |
def find_api_key(api_key: Optional[str] = None) -> str:
if api_key is not None:
return api_key
elif tpuf.api_key is not None:
return tpuf.api_key
else:
raise AuthenticationError("No turbopuffer API key was provided.\n"
"Set the TURBOPUFFER_API_KEY ... | raise APIError(response.status_code, traceback.format_exception_only(err), response.text) | 2 | 2023-12-12 06:52:27+00:00 | 2k |
neu-spiral/multi-label-emg | scripts/run_experiment_2.py | [
{
"identifier": "run_one",
"path": "multi_label_emg/slurm_utils.py",
"snippet": "def run_one(job: str, running_job_count: int, dry_run: bool):\n if ON_SLURM_CLUSTER:\n _run_one_slurm(job, running_job_count, slurm_logs_dir, dry_run)\n else:\n _run_one_local(job, running_job_count, dry... | import itertools
import numpy as np
from run_experiment_1 import Setting
from multi_label_emg.slurm_utils import run_one
from multi_label_emg.utils import PROJECT_ROOT | 675 | """
Experiment 2:
Using previous best parallel model type and classifier,
Vary method of subsetting synthetic doubles and how many to use.
"""
DRY_RUN = True
script = PROJECT_ROOT / "train.py"
python = PROJECT_ROOT.parent / "venv" / "bin" / "python"
assert script.exists()
assert python.exists()
subjects = [f"Subj... | """
Experiment 2:
Using previous best parallel model type and classifier,
Vary method of subsetting synthetic doubles and how many to use.
"""
DRY_RUN = True
script = PROJECT_ROOT / "train.py"
python = PROJECT_ROOT.parent / "venv" / "bin" / "python"
assert script.exists()
assert python.exists()
subjects = [f"Subj... | run_one(job, running_job_count, dry_run=DRY_RUN) | 0 | 2023-12-12 16:50:34+00:00 | 2k |
lbcb-sci/GNNome | graph_dataset.py | [
{
"identifier": "get_config",
"path": "config.py",
"snippet": "def get_config():\n return {\n 'checkpoints_path': 'checkpoints',\n 'models_path': 'models',\n \n 'tool_dir': 'vendor',\n 'raven_dir': 'vendor/raven-1.8.1',\n 'hifiasm_dir': 'vendor/hifiasm-0.18.8... | import re
import os
import pickle
import subprocess
import dgl
import graph_parser
from dgl.data import DGLDataset
from config import get_config
from utils import preprocess_graph, add_positional_encoding, extract_contigs | 1,513 |
class AssemblyGraphDataset(DGLDataset):
def __init__(self, root, assembler, threads=32, generate=False):
self.root = os.path.abspath(root)
self.assembler = assembler
self.threads = threads
self.assembly_dir = os.path.join(self.root, self.assembler)
# print(self.assembly_d... |
class AssemblyGraphDataset(DGLDataset):
def __init__(self, root, assembler, threads=32, generate=False):
self.root = os.path.abspath(root)
self.assembler = assembler
self.threads = threads
self.assembly_dir = os.path.join(self.root, self.assembler)
# print(self.assembly_d... | graph = add_positional_encoding(graph) | 2 | 2023-12-08 04:45:45+00:00 | 2k |
altfoxie/ha-sberdevices | custom_components/sberdevices/light.py | [
{
"identifier": "DeviceAPI",
"path": "custom_components/sberdevices/api.py",
"snippet": "class DeviceAPI:\n def __init__(self, home: HomeAPI, device_id: str) -> None:\n self._home = home\n self._id = device_id\n\n @property\n def device(self) -> dict[str, any]:\n return sel... | import math
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP_KELVIN,
ATTR_HS_COLOR,
ATTR_WHITE,
ColorMode,
LightEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry impo... | 1,211 | """Support for Abode Security System lights."""
from __future__ import annotations
# hardcode xd
COLOR_TEMP_MIN = 2700
COLOR_TEMP_MAX = 6500
COLOR_TEMP_RANGE = (COLOR_TEMP_MIN, COLOR_TEMP_MAX)
H_RANGE = (0, 360)
S_RANGE = (0, 100)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_ad... | """Support for Abode Security System lights."""
from __future__ import annotations
# hardcode xd
COLOR_TEMP_MIN = 2700
COLOR_TEMP_MAX = 6500
COLOR_TEMP_RANGE = (COLOR_TEMP_MIN, COLOR_TEMP_MAX)
H_RANGE = (0, 360)
S_RANGE = (0, 100)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_ad... | home: HomeAPI = hass.data[DOMAIN][entry.entry_id]["home"] | 2 | 2023-12-09 15:27:27+00:00 | 2k |
amadad/agentcy3 | agency_swarm/tools/tool_factory.py | [
{
"identifier": "BaseTool",
"path": "agency_swarm/tools/base_tool.py",
"snippet": "class BaseTool(OpenAISchema, ABC):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n @abstractmethod\n def run(self, **kwargs):\n pass"
},
{
"identifier": "reference_schema",
... | import inspect
from typing import Any, Dict, List, Type
from pydantic import create_model, Field
from .base_tool import BaseTool
from ..util.schema import reference_schema
from langchain.tools import format_tool_to_openai_function | 1,523 | except ImportError:
raise ImportError("You must install langchain to use this method.")
if inspect.isclass(tool):
tool = tool()
def callback(self):
tool_input = self.model_dump()
try:
return tool.run(tool_input)
except... |
class ToolFactory:
@staticmethod
def from_langchain_tools(tools: List):
"""
Converts a list of langchain tools into a list of BaseTools.
:param tools: A list of langchain tools.
:return: A list of BaseTools.
"""
converted_tools = []
for tool in tools:... | tool = type(name, (BaseTool, model), { | 0 | 2023-12-14 01:40:32+00:00 | 2k |
Deltares/imod-python | imod/tests/test_flow/test_flow_dis.py | [
{
"identifier": "TimeDiscretization",
"path": "imod/flow/dis.py",
"snippet": "class TimeDiscretization(Package):\n \"\"\"\n Time discretisation package class.\n\n Parameters\n ----------\n timestep_duration: xr.DataArray\n is the length of the current stress period (PERLEN). If the... | import cftime
import numpy as np
import pytest
import xarray as xr
from imod.flow import TimeDiscretization
from imod.wq import timeutil | 973 |
@pytest.fixture(scope="module")
def time_discretization(three_days):
times = three_days
|
@pytest.fixture(scope="module")
def time_discretization(three_days):
times = three_days | duration = timeutil.timestep_duration(times, False) | 1 | 2023-12-08 13:57:59+00:00 | 2k |
Dong142857/Live3DPortrait | models/eg3d/volumetric_rendering/renderer.py | [
{
"identifier": "MipRayMarcher2",
"path": "models/eg3d/volumetric_rendering/ray_marcher.py",
"snippet": "class MipRayMarcher2(nn.Module):\n def __init__(self):\n super().__init__()\n\n\n def run_forward(self, colors, densities, depths, rendering_options):\n deltas = depths[:, :, 1:] ... | import math
import torch
import torch.nn as nn
from models.eg3d.volumetric_rendering.ray_marcher import MipRayMarcher2
from models.eg3d.volumetric_rendering import math_utils | 1,563 | # SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation ... | # SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation ... | self.ray_marcher = MipRayMarcher2() | 0 | 2023-12-09 15:18:53+00:00 | 2k |
lumi-ua/goit-project2-django-assistant | personal_assistant/app_contacts/views.py | [
{
"identifier": "ContactForm",
"path": "personal_assistant/app_contacts/forms.py",
"snippet": "class ContactForm(ModelForm):\n fullname = CharField(max_length=255, \n widget=forms.TextInput(attrs={'placeholder': 'Name Lastname', \"class\": \"form-control\"}))\n address = CharField(max_lengt... | from datetime import date
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Q
from django.urls import reverse_lazy
from django.core.exceptions import ObjectDoesNotExist
from django.c... | 682 | # from django.db.models import Q
# Create your views here.
@login_required
def dashboard(request):
return render(request, 'app_contacts/dashboard.html', {"title": "Dashboard contact operations"})
@login_required
def contact(request):
contact_form = ContactForm()
| # from django.db.models import Q
# Create your views here.
@login_required
def dashboard(request):
return render(request, 'app_contacts/dashboard.html', {"title": "Dashboard contact operations"})
@login_required
def contact(request):
contact_form = ContactForm() | phone_number_form = PhoneNumberForm() | 1 | 2023-12-08 17:26:59+00:00 | 2k |
SubConv/SubConv | modules/convert/converter.py | [
{
"identifier": "RandUserAgent",
"path": "modules/convert/util.py",
"snippet": "def RandUserAgent() -> str:\n return userAgents[random.randint(0, len(userAgents) - 1)]"
},
{
"identifier": "get",
"path": "modules/convert/util.py",
"snippet": "def get(content):\n if content is None:\... | from modules.convert.util import RandUserAgent
from modules.convert.util import get
from modules.convert.util import uniqueName
from modules.convert.util import urlSafe
from modules.convert.util import base64RawStdDecode
from modules.convert.util import base64RawURLDecode
from modules.convert.v import handleVShareLink
... | 1,548 |
async def ConvertsV2Ray(buf):
try:
data = base64.b64decode(buf).decode("utf-8")
except:
try:
data = buf.decode("utf-8")
except:
data = buf
arr = data.splitlines()
proxies = []
names = {}
for line in arr:
if line == "":
... |
async def ConvertsV2Ray(buf):
try:
data = base64.b64decode(buf).decode("utf-8")
except:
try:
data = buf.decode("utf-8")
except:
data = buf
arr = data.splitlines()
proxies = []
names = {}
for line in arr:
if line == "":
... | hysteria["sni"] = query.get("peer") | 1 | 2023-12-06 12:57:11+00:00 | 2k |
Opt-Mucca/PySCIPOpt-ML | src/pyscipopt_ml/add_predictor.py | [
{
"identifier": "NotRegistered",
"path": "src/pyscipopt_ml/exceptions.py",
"snippet": "class NotRegistered(Exception):\n \"\"\"Predictor is not supported by pyscipopt-ml.\"\"\"\n\n def __init__(self, predictor):\n super().__init__(\n f\"Object of type {predictor} is not registere... | from warnings import warn
from .exceptions import NotRegistered
from .modelling.get_convertor import get_convertor
from .registered_predictors import registered_predictors | 820 |
def add_predictor_constr(
scip_model, predictor, input_vars, output_vars=None, unique_naming_prefix="p_", **kwargs
):
"""Formulate predictor in PySCIPOpt model.
The formulation predicts the values of output_vars using input_vars according to
predictor.
Parameters
----------
scip_model :... |
def add_predictor_constr(
scip_model, predictor, input_vars, output_vars=None, unique_naming_prefix="p_", **kwargs
):
"""Formulate predictor in PySCIPOpt model.
The formulation predicts the values of output_vars using input_vars according to
predictor.
Parameters
----------
scip_model :... | convertor = get_convertor(predictor, convertors) | 1 | 2023-12-10 20:28:22+00:00 | 2k |
DongqiShen/qwen-fast | generate.py | [
{
"identifier": "Transformer",
"path": "model.py",
"snippet": "class Transformer(nn.Module):\n def __init__(self, config: ModelArgs) -> None:\n super().__init__()\n self.config = config\n\n self.tok_embeddings = nn.Embedding(config.vocab_size, config.dim)\n self.layers = n... | import sys
import time
import itertools
import torch
import torch._inductor.config
import torch._dynamo.config
import contextlib
import argparse
from pathlib import Path
from typing import Optional, Tuple
from model import Transformer
from tp import maybe_init_dist
from sentencepiece import SentencePiecePro... | 1,107 | # 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.
torch._inductor.config.coordinate_descent_tuning = True
torch._inductor.config.triton.unique_kernel_names = True
torch._in... | # 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.
torch._inductor.config.coordinate_descent_tuning = True
torch._inductor.config.triton.unique_kernel_names = True
torch._in... | def prefill(model: Transformer, x: torch.Tensor, input_pos: torch.Tensor, **sampling_kwargs) -> torch.Tensor: | 0 | 2023-12-05 14:07:19+00:00 | 2k |
Yanyutin753/CowAndPandoraNext | channel/chat_channel.py | [
{
"identifier": "Channel",
"path": "channel/channel.py",
"snippet": "class Channel(object):\n NOT_SUPPORT_REPLYTYPE = [ReplyType.VOICE, ReplyType.IMAGE]\n\n def startup(self):\n \"\"\"\n init channel\n \"\"\"\n raise NotImplementedError\n\n def handle_text(self, msg)... | import os
import re
import threading
import time
from asyncio import CancelledError
from concurrent.futures import Future, ThreadPoolExecutor
from bridge.context import *
from bridge.reply import *
from channel.channel import Channel
from common.dequeue import Dequeue
from common.log import logger
from config import co... | 1,113 |
try:
except Exception as e:
pass
# 抽象类, 它包含了与消息通道无关的通用处理逻辑
class ChatChannel(Channel):
name = None # 登录的用户名
user_id = None # 登录的用户id
futures = {} # 记录每个session_id提交到线程池的future对象, 用于重置会话时把没执行的future取消掉,正在执行的不会被取消
sessions = {} # 用于控制并发,每个session_id同时只能有一个context在处理
lock = threading.Lock()... |
try:
except Exception as e:
pass
# 抽象类, 它包含了与消息通道无关的通用处理逻辑
class ChatChannel(Channel):
name = None # 登录的用户名
user_id = None # 登录的用户id
futures = {} # 记录每个session_id提交到线程池的future对象, 用于重置会话时把没执行的future取消掉,正在执行的不会被取消
sessions = {} # 用于控制并发,每个session_id同时只能有一个context在处理
lock = threading.Lock()... | config = conf() | 3 | 2023-12-14 15:21:17+00:00 | 2k |
nerdslab/bams | bams/models/bams.py | [
{
"identifier": "MLP",
"path": "bams/models/mlp.py",
"snippet": "class MLP(nn.Module):\n r\"\"\"Flexible Multi-layer perceptron model, with optional batchnorm layers.\n\n Args:\n hidden_layers (list): List of layer dimensions, from input layer to output\n layer. If first input si... | from collections import OrderedDict
from bams.models import TemporalConvNet, MLP
import torch
import torch.nn as nn | 1,395 |
class BAMS(nn.Module):
r"""BAMS model.
Args:
input_size (int): Number of input features.
predictor (dict): Parameters for the predictor MLP.
encoders (dict[dict]): A dictionnary of encoders, where each key is the name of
the encoder, and each value is a dictionnary of pa... |
class BAMS(nn.Module):
r"""BAMS model.
Args:
input_size (int): Number of input features.
predictor (dict): Parameters for the predictor MLP.
encoders (dict[dict]): A dictionnary of encoders, where each key is the name of
the encoder, and each value is a dictionnary of pa... | self.predictor = MLP(**predictor) | 0 | 2023-12-05 16:26:57+00:00 | 2k |
FF14CN/Sarean-arsenal | Utility/sqMall/sqMallDoSign.py | [
{
"identifier": "Daoyu",
"path": "Utility/sdoLogin/Daoyu.py",
"snippet": "def dykey_encrypt(self):\ndef config_handler():\ndef initialize():\ndef get_guid(device_id, manuid):\ndef get_flowid(manuid, deviceid, sessionid, show_username):\ndef get_account_id_list(flowid, deviceid, manuid, sessionid, show_u... | from Utility.sdoLogin import Daoyu
from Utility.sqMall.daoyuBuildinMallSign import daoyumall_sign
from Utility.sqMall.daoyuBuildinMallBalance import daoyu_mall_balance
import Utility.Notifications.push as pusher | 1,368 | """
Author: KuliPoi
Contact: me@pipirapira.com
Created: 2023-12-21
File: sqMailDoSign.py
Version: 2.5.0
Description: Do SQMALL AUTO SIGN, FUCK SQ BY THE WAY
"""
def main():
| """
Author: KuliPoi
Contact: me@pipirapira.com
Created: 2023-12-21
File: sqMailDoSign.py
Version: 2.5.0
Description: Do SQMALL AUTO SIGN, FUCK SQ BY THE WAY
"""
def main(): | if Daoyu.initialize(): | 0 | 2023-12-06 08:48:02+00:00 | 2k |
janmartchouk/vidgen | src/content_getter.py | [
{
"identifier": "SUBREDDITS",
"path": "config/dicts.py",
"snippet": "SUBREDDITS = {\n 'tifu': 'rss',\n 'confession': 'rss',\n 'relationship_advice': 'web',\n 'amitheasshole': 'rss'\n}"
},
{
"identifier": "setup_logger",
"path": "utils/logger.py",
"snippet": "def setup_logger(... | import feedparser
import logging
import time
import requests
from bs4 import BeautifulSoup
from tqdm import tqdm
from config.dicts import SUBREDDITS
from utils.logger import setup_logger
from models.post import Post | 1,182 |
class ContentGetter:
def __init__(self, loglevel = logging.INFO):
self.logger = setup_logger(__name__, loglevel, emoji='🌍')
# Get a list of Reddit Posts from an RSS feed
def from_subreddit(self, subreddit):
if not subreddit in SUBREDDITS:
self.logger.error(f"{subreddit} is n... |
class ContentGetter:
def __init__(self, loglevel = logging.INFO):
self.logger = setup_logger(__name__, loglevel, emoji='🌍')
# Get a list of Reddit Posts from an RSS feed
def from_subreddit(self, subreddit):
if not subreddit in SUBREDDITS:
self.logger.error(f"{subreddit} is n... | post_obj = Post( | 2 | 2023-12-14 13:00:22+00:00 | 2k |
asdfghjil/XMUCourseCheckin | checkin.py | [
{
"identifier": "getCheckinList",
"path": "checkinList.py",
"snippet": "def getCheckinList(session, http_header, userInfo, today=True):\n try:\n url = serverUrl + \"/getQdKbList\"\n data = {\n 'sign': userInfo['sign'],\n 'userType': userInfo['userType'],\n ... | import json
import requests
import sys
import time
import random
from checkinList import getCheckinList, printCheckinList | 1,515 |
serverUrl = "https://tingke.xmu.edu.cn/app"
def getCheckinInfo(session, http_header, userInfo, lesson):
try:
url = serverUrl + "/getXsQdInfo"
data = {
'sign': userInfo['sign'],
'unitCode': userInfo['unitCode'],
'userCode': userInfo['userCode'],
'use... |
serverUrl = "https://tingke.xmu.edu.cn/app"
def getCheckinInfo(session, http_header, userInfo, lesson):
try:
url = serverUrl + "/getXsQdInfo"
data = {
'sign': userInfo['sign'],
'unitCode': userInfo['unitCode'],
'userCode': userInfo['userCode'],
'use... | lesson = printCheckinList(session, http_header, userInfo, today=True) | 1 | 2023-12-13 10:42:20+00:00 | 2k |
Kanaries/kanaries-track | kanaries_track/client.py | [
{
"identifier": "config",
"path": "kanaries_track/config.py",
"snippet": "class Config:"
},
{
"identifier": "RequestClient",
"path": "kanaries_track/request.py",
"snippet": "class RequestClient:\n \"\"\"Client for sending events to kanaries-track server\"\"\"\n def __init__(\n ... | from typing import Dict, Any
from datetime import datetime
from threading import Thread
from functools import lru_cache
from dateutil.tz import tzlocal
from .config import config
from .request import RequestClient
import queue
import uuid
import logging
import time
import atexit | 1,388 | self.ruuning = False
def _upload(self):
"""Upload events"""
start_time = time.monotonic()
events = []
while len(events) < self.upload_size:
elapsed_seconds = time.monotonic() - start_time
if elapsed_seconds >= self.upload_interval_seconds:
... |
logger = logging.getLogger("kanaries_track")
class _Consumer(Thread):
def __init__(
self,
*,
event_queue: queue.Queue,
request_client: RequestClient,
upload_size: int,
upload_interval_seconds: int
) -> None:
super().__init__()
self.event_queu... | host=config.host, | 0 | 2023-12-06 06:01:32+00:00 | 2k |
Yingyue-L/Mamba-LLaVA | llava/model/llava_arch.py | [
{
"identifier": "build_vision_tower",
"path": "llava/model/multimodal_encoder/builder.py",
"snippet": "def build_vision_tower(vision_tower_cfg, **kwargs):\n vision_tower = getattr(vision_tower_cfg, 'mm_vision_tower', getattr(vision_tower_cfg, 'vision_tower', None))\n is_absolute_path_exists = os.p... | from abc import ABC, abstractmethod
from .multimodal_encoder.builder import build_vision_tower
from .multimodal_projector.builder import build_vision_projector
from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
import torch
import torch.n... | 715 | # Copyright 2023 Haotian Liu
#
# 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 agre... | # Copyright 2023 Haotian Liu
#
# 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 agre... | self.vision_tower = build_vision_tower(config, delay_load=True) | 0 | 2023-12-09 09:39:13+00:00 | 2k |
Theia-4869/MoSA | src/engine/evaluator.py | [
{
"identifier": "multilabel",
"path": "src/engine/eval/multilabel.py",
"snippet": "def get_continuous_ids(probe_labels: List[int]) -> Dict[int, int]:\ndef multihot(x: List[List[int]], nb_classes: int) -> np.ndarray:\ndef compute_map(\n scores: np.ndarray, multihot_targets: np.ndarray\n) -> Tuple[... | import numpy as np
from collections import defaultdict
from typing import List, Union
from .eval import multilabel
from .eval import singlelabel
from ..utils import logging | 898 | #!/usr/bin/env python3
logger = logging.get_logger("MOSA")
class Evaluator():
"""
An evaluator with below logics:
1. find which eval module to use.
2. store the eval results, pretty print it in log file as well.
"""
def __init__(
self,
) -> None:
self.results = defaultd... | #!/usr/bin/env python3
logger = logging.get_logger("MOSA")
class Evaluator():
"""
An evaluator with below logics:
1. find which eval module to use.
2. store the eval results, pretty print it in log file as well.
"""
def __init__(
self,
) -> None:
self.results = defaultd... | acc_dict = singlelabel.compute_acc_auc(scores, targets) | 1 | 2023-12-06 07:50:16+00:00 | 2k |
IBM/AI-assisted-chemical-sensing | src/chemsense/vision/cli/classification_analysis.py | [
{
"identifier": "setup_basic_logging_for_scripts",
"path": "src/chemsense/vision/logging_configuration.py",
"snippet": "def setup_basic_logging_for_scripts() -> None:\n \"\"\"Setup basic stdout logging for scripts.\"\"\"\n logging.basicConfig(\n stream=sys.stdout,\n level=logging.INF... | from pathlib import Path
from chemsense.vision.modeling.classification import (
attach_classification_head_fewshots,
attach_classification_head_kfold,
attach_classification_head_loco,
attach_classification_head_loco_sugars,
)
from ..logging_configuration import setup_basic_logging_for_scripts
fr... | 1,347 | """Training and testing models with extracted features."""
__copyright__ = """
LICENSED INTERNAL CODE. PROPERTY OF IBM.
IBM Research Licensed Internal Code
(C) Copyright IBM Corp. 2023
ALL RIGHTS RESERVED
"""
@click.command()
@click.option("--task", type=str, default="red_wines", help="Dataset name ... | """Training and testing models with extracted features."""
__copyright__ = """
LICENSED INTERNAL CODE. PROPERTY OF IBM.
IBM Research Licensed Internal Code
(C) Copyright IBM Corp. 2023
ALL RIGHTS RESERVED
"""
@click.command()
@click.option("--task", type=str, default="red_wines", help="Dataset name ... | setup_basic_logging_for_scripts()
| 0 | 2023-12-05 15:56:12+00:00 | 2k |
pymike00/tinychat | tests/llms/test_google_handler.py | [
{
"identifier": "GoogleAIHandler",
"path": "tinychat/llms/google.py",
"snippet": "class GoogleAIHandler:\n \"\"\"\n Handler class to interact with the OpenAI models.\n\n Returns chat responses and stores the chat history.\n\n TODO: add chat message dataclass so that we can enforce validation... | import json
import unittest
from unittest.mock import MagicMock, Mock, patch
from tinychat.llms.google import GoogleAIHandler, GoogleAIClient | 1,204 |
class TestGoogleGeminiHandlerStreaming(unittest.TestCase):
@patch.object(GoogleAIClient, "perform_stream_request")
def test_stream_response(self, mock_perform_stream_request):
# Create a mock SSEClient with a mock events method
mock_sse_client = MagicMock()
mock_stream = iter(
... |
class TestGoogleGeminiHandlerStreaming(unittest.TestCase):
@patch.object(GoogleAIClient, "perform_stream_request")
def test_stream_response(self, mock_perform_stream_request):
# Create a mock SSEClient with a mock events method
mock_sse_client = MagicMock()
mock_stream = iter(
... | handler = GoogleAIHandler() | 0 | 2023-12-11 20:40:02+00:00 | 2k |
nickruggeri/hypergraph-message-passing | test/model/test_sampling/test_helper_functions.py | [
{
"identifier": "_community_count_combinations",
"path": "src/model/sampling.py",
"snippet": "def _community_count_combinations(\n n_nodes: int, comm_counts: list[int]\n) -> Iterable[list[int]]:\n r\"\"\"Generate all possible community count vectors :math::`\\#`.\n\n Parameters\n ----------\... | import itertools
import numpy as np
import pytest
from collections import Counter
from typing import Dict, List
from scipy import special
from src.model.sampling import (
_community_count_combinations,
_log_n_sharp,
_sample_hye_from_count,
) | 1,425 |
n_nodes_all = [2, 5, 10, 25, 50, 100]
rng = np.random.default_rng(seed=123)
hye_comm_counts_all = [
rng.integers(low=0, high=max_val, size=q)
for _ in range(10)
for max_val in [5, 10]
for q in [2, 3, 4, 5]
]
comm_counts_all = sum(
(
[
hye_comm_count + rng.integers(low=0, high=... |
n_nodes_all = [2, 5, 10, 25, 50, 100]
rng = np.random.default_rng(seed=123)
hye_comm_counts_all = [
rng.integers(low=0, high=max_val, size=q)
for _ in range(10)
for max_val in [5, 10]
for q in [2, 3, 4, 5]
]
comm_counts_all = sum(
(
[
hye_comm_count + rng.integers(low=0, high=... | _sample_hye_from_count(comm_nodes, hye_comm_counts, rng), | 2 | 2023-12-06 22:01:38+00:00 | 2k |
sailfishos-chum/sailfishos-chum.github.io | chumweb/package.py | [
{
"identifier": "CONFIG",
"path": "chumweb/config.py",
"snippet": "CONFIG = init_config()"
},
{
"identifier": "RemoteImage",
"path": "chumweb/remote_image.py",
"snippet": "class RemoteImage:\n \"\"\"\n An image located on a remote computer that can be downloaded locally\n\n Attr... | import logging
import enum
import re
from dataclasses import dataclass, field
from datetime import datetime, UTC
from enum import StrEnum
from types import NoneType
from typing import List, Dict, Self, Set, Optional
from markupsafe import Markup
from . import CONFIG
from .remote_image import RemoteImage
... | 675 | """
Data classes for package metadata. It is also responsible for parsing the metadate of a single package
"""
logger = logging.getLogger(__name__)
class PackageApplicationCategory(StrEnum):
"""
Desktop application categories, from https://specifications.freedesktop.org/menu-spec/latest/apa.html
"""
... | """
Data classes for package metadata. It is also responsible for parsing the metadate of a single package
"""
logger = logging.getLogger(__name__)
class PackageApplicationCategory(StrEnum):
"""
Desktop application categories, from https://specifications.freedesktop.org/menu-spec/latest/apa.html
"""
... | icon: RemoteImage | None = None | 1 | 2023-12-14 19:25:31+00:00 | 2k |
oVo-HxBots/URLUploadBot | Uploader/youtube.py | [
{
"identifier": "get_file_extension_from_url",
"path": "Uploader/functions/help_ytdl.py",
"snippet": "def get_file_extension_from_url(url):\n url_path = urlparse(url).path\n basename = os.path.basename(url_path)\n return basename.split(\".\")[-1]"
},
{
"identifier": "get_resolution",
... | import os
import wget
import asyncio
from urllib.parse import urlparse
from opencc import OpenCC
from youtube_dl import YoutubeDL
from pyrogram import Client, filters, enums
from pyrogram.types import Message
from pyrogram import Client, filters
from Uploader.config import Config
from sample_config import Confi... | 979 | # MIT License
# Copyright (c) 2022 Hash Minner
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pu... | # MIT License
# Copyright (c) 2022 Hash Minner
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pu... | thumbnail_file = f"{basename}.{get_file_extension_from_url(thumbnail_url)}" | 0 | 2023-12-09 03:24:55+00:00 | 2k |
Jiawei-Yao0812/PixelFormer_DGR | pixelformer/networks/PQI.py | [
{
"identifier": "resize",
"path": "pixelformer/networks/utils.py",
"snippet": "def resize(input,\n size=None,\n scale_factor=None,\n mode='nearest',\n align_corners=None,\n warning=True):\n if warning:\n if size is not None and align_corners:\n... | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule
from .utils import resize, normal_init | 769 |
class PPM(nn.ModuleList):
"""Pooling Pyramid Module used in PSPNet.
Args:
pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
Module.
in_channels (int): Input channels.
channels (int): Channels after modules, before conv_seg.
conv_cfg (dict|None): Con... |
class PPM(nn.ModuleList):
"""Pooling Pyramid Module used in PSPNet.
Args:
pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
Module.
in_channels (int): Input channels.
channels (int): Channels after modules, before conv_seg.
conv_cfg (dict|None): Con... | upsampled_ppm_out = resize( | 0 | 2023-12-13 20:50:32+00:00 | 2k |
kramerlab/PeerLearning | peer.py | [
{
"identifier": "SuggestionBuffer",
"path": "suggestionbuffer.py",
"snippet": "class SuggestionBuffer:\n def __init__(self, capacity):\n self.buffer = deque(maxlen=capacity)\n\n def add(self, *args):\n self.buffer.append(args)\n\n def sample(self, batch_size):\n if len(self... | from abc import ABC
from typing import Type
from suggestionbuffer import SuggestionBuffer
from utils import make_env
from stable_baselines3.common.off_policy_algorithm import OffPolicyAlgorithm
import itertools as it
import numpy as np
import torch | 1,381 | lr=0.95, switch_ratio=0, use_advantage=False,
max_peer_epochs=1_000_000_000):
"""
:param peers: An iterable of peer agents
:param lr: The learning rate for trust and agent values
:param switch_ratio: switch_ratio == 0 means no switching
:param us... |
class PeerGroup:
""" A group of peers who train together. """
def __init__(self, peers, use_agent_values=False, init_agent_values=200.,
lr=0.95, switch_ratio=0, use_advantage=False,
max_peer_epochs=1_000_000_000):
"""
:param peers: An iterable of peer agent... | env=make_env(env, **env_args), | 1 | 2023-12-13 10:40:55+00:00 | 2k |
balewgize/skimmit | url_summary/views.py | [
{
"identifier": "Preference",
"path": "users/models.py",
"snippet": "class Preference(models.Model):\n class AIModels(models.TextChoices):\n GPT_3_5 = \"gpt-3.5-turbo\", \"GPT-3.5\"\n GEMINI_PRO = \"gemini-pro\", \"Gemini Pro\"\n\n SENTENCE_COUNT_CHOICES = tuple(zip(range(3, 11), ran... | import os
import json
import readtime
import google.generativeai as genai
from django.http import JsonResponse
from bs4 import BeautifulSoup
from django.shortcuts import get_object_or_404, redirect, render
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
fr... | 1,394 |
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
def home(request):
context = {"article_form": ArticleURLForm(), "video_form": VideoURLForm()}
return render(request, "index.html", context=context)
def article_summary(request):
if request.method == "POST":
form = ArticleURLForm(request.POS... |
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
def home(request):
context = {"article_form": ArticleURLForm(), "video_form": VideoURLForm()}
return render(request, "index.html", context=context)
def article_summary(request):
if request.method == "POST":
form = ArticleURLForm(request.POS... | response, error = download_page(url) | 4 | 2023-12-13 13:47:20+00:00 | 2k |
ZS-YANG/FemtoDet-v3 | projects/XDecoder/xdecoder/inference/texttoimage_regionretrieval_inferencer.py | [
{
"identifier": "DetInferencer",
"path": "mmdet/apis/det_inferencer.py",
"snippet": " VOID = None\nIMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif',\n '.tiff', '.webp')\nclass DetInferencer(BaseInferencer):\n def __init__(self,\n model: Opt... | import copy
import torch
from typing import Iterable, Optional, Union
from mmengine.dataset import Compose
from rich.progress import track
from mmdet.apis.det_inferencer import DetInferencer, InputsType
from mmdet.utils import ConfigType | 1,193 |
class TextToImageRegionRetrievalInferencer(DetInferencer):
def _init_pipeline(self, cfg: ConfigType) -> Compose:
"""Initialize the test pipeline."""
pipeline_cfg = cfg.test_dataloader.dataset.pipeline
# For inference, the key of ``img_id`` is not used.
if 'meta_keys' in pipelin... |
class TextToImageRegionRetrievalInferencer(DetInferencer):
def _init_pipeline(self, cfg: ConfigType) -> Compose:
"""Initialize the test pipeline."""
pipeline_cfg = cfg.test_dataloader.dataset.pipeline
# For inference, the key of ``img_id`` is not used.
if 'meta_keys' in pipelin... | inputs: InputsType, | 0 | 2023-12-11 15:23:03+00:00 | 2k |
mit-ll-ai-technology/maite | src/maite/_internals/interop/huggingface/image_classifier.py | [
{
"identifier": "BaseHFModel",
"path": "src/maite/_internals/interop/huggingface/base.py",
"snippet": "class BaseHFModel(nn.Module, BaseModel):\n def __init__(\n self,\n model_name: str,\n model: Union[HuggingFaceWithLogits, HuggingFaceWithDetection],\n processor: Optional... | from typing import TYPE_CHECKING, Any, List, Optional, Union, cast
from typing_extensions import Self
from maite.errors import InvalidArgument
from maite.protocols import HasDataImage, HasLogits, SupportsArray
from .base import BaseHFModel, InteropModelMetadata
from .typing import (
HuggingFacePredictions,
Hugg... | 1,012 | # Copyright 2023, MASSACHUSETTS INSTITUTE OF TECHNOLOGY
# Subject to FAR 52.227-11 – Patent Rights – Ownership by the Contractor (May 2014).
# SPDX-License-Identifier: MIT
__all__ = ["HuggingFaceImageClassifier"]
class HuggingFaceImageClassifier(BaseHFModel):
"""
Wrapper for HuggingFace image classifiati... | # Copyright 2023, MASSACHUSETTS INSTITUTE OF TECHNOLOGY
# Subject to FAR 52.227-11 – Patent Rights – Ownership by the Contractor (May 2014).
# SPDX-License-Identifier: MIT
__all__ = ["HuggingFaceImageClassifier"]
class HuggingFaceImageClassifier(BaseHFModel):
"""
Wrapper for HuggingFace image classifiati... | ) -> Union[HuggingFacePredictions, HuggingFaceProbs]: | 1 | 2023-12-12 15:34:16+00:00 | 2k |
djcopley/ShellOracle | src/shelloracle/providers/ollama.py | [
{
"identifier": "Provider",
"path": "src/shelloracle/provider.py",
"snippet": "class Provider(Protocol):\n \"\"\"\n LLM Provider Protocol\n\n All LLM backends must implement this interface.\n \"\"\"\n name: str\n\n @abstractmethod\n def generate(self, prompt: str) -> AsyncIterator[s... | import json
import httpx
from dataclasses import dataclass, asdict
from typing import Any, AsyncIterator
from ..provider import Provider, ProviderError
from ..config import Setting | 1,256 | from __future__ import annotations
def dataclass_to_json(obj: Any) -> dict[str, Any]:
"""Convert dataclass to a json dict
This function filters out 'None' values.
:param obj: the dataclass to serialize
:return: serialized dataclass
:raises TypeError: if obj is not a dataclass
"""
retu... | from __future__ import annotations
def dataclass_to_json(obj: Any) -> dict[str, Any]:
"""Convert dataclass to a json dict
This function filters out 'None' values.
:param obj: the dataclass to serialize
:return: serialized dataclass
:raises TypeError: if obj is not a dataclass
"""
retu... | raise ProviderError(response["error"]) | 1 | 2023-12-11 20:23:31+00:00 | 2k |
juniberry/PacketIRC | packetirc.py | [
{
"identifier": "LOG_FILE",
"path": "settings.py",
"snippet": "LOG_FILE = \"packetirc.log\""
},
{
"identifier": "LOG_LEVEL",
"path": "settings.py",
"snippet": "LOG_LEVEL = logging.INFO"
},
{
"identifier": "SERVER",
"path": "settings.py",
"snippet": "SERVER = \"\""
},
... | import socket
import threading
import random
import time
import logging
import re
import irc.client
import os
import sys
from settings import LOG_FILE, LOG_LEVEL, SERVER, PORT, PASS, CHANNEL, HIDE_SERVER, MAX_RETRIES, RETRY_DELAY, HELP_INFO, WELCOME_MESSAGE, BAD_WORDS_FILE, BAD_WORDS_FILTER | 666 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
______ _ _____ ______ ______
(_____ \ | | _ (_____|_____ \ / _____)
_____) )___ ____| | _ ____| |_ _ _____) ) /
| ____/ _ |/ ___) | / ) _ ) _) | | (_____ (| |
| | ( ( | ( (___| |< ( (/ /| |__ _| |_ | | ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
______ _ _____ ______ ______
(_____ \ | | _ (_____|_____ \ / _____)
_____) )___ ____| | _ ____| |_ _ _____) ) /
| ____/ _ |/ ___) | / ) _ ) _) | | (_____ (| |
| | ( ( | ( (___| |< ( (/ /| |__ _| |_ | | ... | logging.basicConfig(filename=os.path.join(HOME_PATH, LOG_FILE), filemode='w', level=LOG_LEVEL, format='%(asctime)s - %(levelname)s - %(message)s') | 0 | 2023-12-13 19:08:48+00:00 | 2k |
Tps-F/rvc-onnx-test | onnxlib/attentions.py | [
{
"identifier": "commons",
"path": "onnxlib/commons.py",
"snippet": "def init_weights(m, mean=0.0, std=0.01):\ndef get_padding(kernel_size, dilation=1):\ndef kl_divergence(m_p, logs_p, m_q, logs_q):\ndef rand_gumbel(shape):\ndef rand_gumbel_like(x):\ndef slice_segments(x, ids_str, segment_size=4):\ndef ... | import math
import torch
from typing import Optional
from torch import nn
from torch.nn import functional as F
from onnxlib import commons, modules
from onnxlib.modules import LayerNorm | 1,523 |
class Encoder(nn.Module):
def __init__(
self,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size=1,
p_dropout=0.0,
window_size=10,
**kwargs
):
super(Encoder, self).__init__()
self.hidden_channels = hidden_c... |
class Encoder(nn.Module):
def __init__(
self,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size=1,
p_dropout=0.0,
window_size=10,
**kwargs
):
super(Encoder, self).__init__()
self.hidden_channels = hidden_c... | self.norm_layers_1.append(LayerNorm(hidden_channels)) | 2 | 2023-12-09 04:08:04+00:00 | 2k |
zhenqincn/FedKSeed | utils_data/load_data.py | [
{
"identifier": "DefaultToken",
"path": "utils_data/default_tokens.py",
"snippet": "class DefaultToken(Enum):\n PAD_TOKEN = \"[PAD]\"\n EOS_TOKEN = \"</s>\"\n BOS_TOKEN = \"<s>\"\n UNK_TOKEN = \"<unk>\"\n IGNORE_INDEX = -100"
},
{
"identifier": "partition_idx_labeldir",
"path"... | import numpy as np
import torch
from torch.utils.data import DataLoader, Subset
from transformers import AutoTokenizer
from utils_data.default_tokens import DefaultToken
from utils_data.partition_data import partition_idx_labeldir
from collections import Counter
from utils_data.llm_dataset import LLMDataset, LL... | 862 |
def get_loaders(args, only_eval=False):
"""
Return: list of train_loaders, eval_loader
"""
tokenizer = AutoTokenizer.from_pretrained(args.model, use_fast=True)
tokenizer.model_max_length = args.max_length
special_tokens = dict()
if tokenizer.pad_token is None:
special_tokens["pad_t... |
def get_loaders(args, only_eval=False):
"""
Return: list of train_loaders, eval_loader
"""
tokenizer = AutoTokenizer.from_pretrained(args.model, use_fast=True)
tokenizer.model_max_length = args.max_length
special_tokens = dict()
if tokenizer.pad_token is None:
special_tokens["pad_t... | split_dic = partition_idx_labeldir(y_train, n_parties=args.num_clients, alpha=float(noniid[3:]), num_classes=len(counter)) | 1 | 2023-12-08 02:58:31+00:00 | 2k |
merlresearch/PixPNet | pixpnet/optim.py | [
{
"identifier": "get_logger",
"path": "pixpnet/utils.py",
"snippet": "def get_logger(name):\n logging.basicConfig(\n format=\"%(asctime)s[%(process)d][%(levelname)s] %(message)s\",\n datefmt=\"%Y-%m-%dT%H:%M:%S\",\n )\n logger = logging.getLogger(name)\n logger.setLevel(os.envi... | import argparse
import inspect
import re
import torch
from typing import Any, Dict, Optional, Set, Tuple, Type
from pytorch_warmup import ExponentialWarmup
from pytorch_warmup.base import BaseWarmup
from torch.optim.lr_scheduler import CosineAnnealingLR, MultiStepLR, StepLR
from pixpnet.utils import get_logger, interse... | 760 | # Copyright (c) 2022-2023 Mitsubishi Electric Research Laboratories (MERL)
#
# SPDX-License-Identifier: AGPL-3.0-or-later
logger = get_logger(__name__)
_OPTIMIZER_MAP = {attr: getattr(torch.optim, attr) for attr in dir(torch.optim) if attr != "Optimizer"}
_OPTIMIZER_MAP = {attr: cls for attr, cls in _OPTIMIZER_MAP... | # Copyright (c) 2022-2023 Mitsubishi Electric Research Laboratories (MERL)
#
# SPDX-License-Identifier: AGPL-3.0-or-later
logger = get_logger(__name__)
_OPTIMIZER_MAP = {attr: getattr(torch.optim, attr) for attr in dir(torch.optim) if attr != "Optimizer"}
_OPTIMIZER_MAP = {attr: cls for attr, cls in _OPTIMIZER_MAP... | hparams, invalid_keys = intersect_func_and_kwargs( | 1 | 2023-12-06 23:49:31+00:00 | 2k |
dhh1995/MeGraph | megraph/args_utils.py | [
{
"identifier": "get_default_config",
"path": "megraph/io_utils.py",
"snippet": "def get_default_config(args):\n dataset_name = args.dataset_name\n dataset_subname = args.dataset_subname\n model_name = args.model\n conv_name = args.layer\n\n # Config\n cfg_file = args.config_file\n ... | import git
from .io_utils import get_default_config, get_raw_cmdline | 704 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : args.py
# Author : Honghua Dong
# Email : dhh19951@gmail.com
#
# Distributed under terms of the MIT license.
__all__ = ["ArgsBuilder", "add_git_and_cmd_line_info", "get_args_and_model"]
class ArgsBuilder(object):
"""A meta-class to be inherit that sup... | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : args.py
# Author : Honghua Dong
# Email : dhh19951@gmail.com
#
# Distributed under terms of the MIT license.
__all__ = ["ArgsBuilder", "add_git_and_cmd_line_info", "get_args_and_model"]
class ArgsBuilder(object):
"""A meta-class to be inherit that sup... | args.raw_cmdline = get_raw_cmdline() | 1 | 2023-12-12 04:17:13+00:00 | 2k |
SJTU-Quant/SUNNY-GNN | main.py | [
{
"identifier": "train_baseline",
"path": "train/train_baseline.py",
"snippet": "def train(cfg):\ndef train_explain(cfg):"
},
{
"identifier": "train_gnn",
"path": "train/train_gnn.py",
"snippet": "def train(cfg):"
},
{
"identifier": "train_hgn",
"path": "train/train_hgn.py",
... | import argparse
import yaml
import os
import torch
import random
import copy
import numpy as np
from train import train_baseline, train_gnn, train_hgn
from tools.get_data import get_dataset | 847 |
def parse_args():
parser = argparse.ArgumentParser(description="Self-explainable GNN/HGN")
parser.add_argument('--method', type=str, default='snexgnn',
help='self-explainable GNN/HGN type',
choices=['snexgnn', 'snexhgn', 'gat', 'gcn', 'simplehgn'])
parser.ad... |
def parse_args():
parser = argparse.ArgumentParser(description="Self-explainable GNN/HGN")
parser.add_argument('--method', type=str, default='snexgnn',
help='self-explainable GNN/HGN type',
choices=['snexgnn', 'snexhgn', 'gat', 'gcn', 'simplehgn'])
parser.ad... | train_gnn.train(cfg_cp) | 1 | 2023-12-12 02:46:00+00:00 | 2k |
dvmazur/mixtral-offloading | src/expert_wrapper.py | [
{
"identifier": "nested_flatten",
"path": "src/utils.py",
"snippet": "def nested_flatten(t):\n \"\"\"\n Turn nested list/tuple/dict into a flat iterator.\n \"\"\"\n if isinstance(t, (list, tuple)):\n for x in t:\n yield from nested_flatten(x)\n elif isinstance(t, dict):\... | import typing as tp
import torch
from torch import nn
from .utils import nested_flatten, nested_pack | 742 |
class MixtralExpertWrapper(nn.Module):
def __init__(
self,
expert_module: tp.Any,
device: torch.device,
):
super().__init__()
expert_module, self.storage = self.replace_layer_storage(expert_module, device)
self.expert_module = lambda *args, **kwargs: ... |
class MixtralExpertWrapper(nn.Module):
def __init__(
self,
expert_module: tp.Any,
device: torch.device,
):
super().__init__()
expert_module, self.storage = self.replace_layer_storage(expert_module, device)
self.expert_module = lambda *args, **kwargs: ... | state_dict = nested_pack(new_flattened_states, state_dict) | 1 | 2023-12-15 03:32:35+00:00 | 2k |
CircleRadon/Osprey | osprey/datasets/stage2_data.py | [
{
"identifier": "preprocess",
"path": "osprey/train/train.py",
"snippet": "def preprocess(\n sources: Sequence[str],\n tokenizer: transformers.PreTrainedTokenizer,\n has_image: bool = False\n) -> Dict:\n \"\"\"\n Given a list of sources, each is a conversation list. This transform:\n 1... | import copy
import os
import random
import numpy as np
import torch
from osprey.train.train import preprocess, preprocess_multimodal
from torch.utils.data import Dataset
from pycocotools.coco import COCO
from pycocotools import mask as maskUtils
from PIL import Image | 1,598 |
class CustomDataset(Dataset):
def __init__(self,
tokenizer=None,
data_args=None,
ann_file=None,
img_prefix=None,
max_gt_per_img=20,
):
self.data_args = data_args
self.tokenizer = tokenizer
... |
class CustomDataset(Dataset):
def __init__(self,
tokenizer=None,
data_args=None,
ann_file=None,
img_prefix=None,
max_gt_per_img=20,
):
self.data_args = data_args
self.tokenizer = tokenizer
... | data_dict = preprocess( | 0 | 2023-12-17 16:21:45+00:00 | 2k |
open-mmlab/PIA | animatediff/data/dataset.py | [
{
"identifier": "zero_rank_print",
"path": "animatediff/utils/util.py",
"snippet": "def zero_rank_print(s):\n if (not dist.is_initialized()) or (dist.is_initialized() and dist.get_rank() == 0): print(\"### \" + s)"
},
{
"identifier": "detect_edges",
"path": "animatediff/utils/util.py",
... | import os, io, csv, math, random
import numpy as np
import torch
import torchvision.transforms as transforms
import cv2
from einops import rearrange
from decord import VideoReader
from torch.utils.data.dataset import Dataset
from animatediff.utils.util import zero_rank_print, detect_edges | 851 |
def get_score(video_data,
cond_frame_idx,
weight=[1.0, 1.0, 1.0, 1.0],
use_edge=True):
"""
Similar to get_score under utils/util.py/detect_edges
"""
"""
the shape of video_data is f c h w, np.ndarray
"""
h, w = video_data.shape[1], video_da... |
def get_score(video_data,
cond_frame_idx,
weight=[1.0, 1.0, 1.0, 1.0],
use_edge=True):
"""
Similar to get_score under utils/util.py/detect_edges
"""
"""
the shape of video_data is f c h w, np.ndarray
"""
h, w = video_data.shape[1], video_da... | zero_rank_print(f"loading annotations from {csv_path} ...") | 0 | 2023-12-21 03:29:34+00:00 | 2k |
VikParuchuri/texify | ocr_image.py | [
{
"identifier": "batch_inference",
"path": "texify/inference.py",
"snippet": "def batch_inference(images, model, processor, temperature=settings.TEMPERATURE, max_tokens=settings.MAX_TOKENS):\n images = [image.convert(\"RGB\") for image in images]\n encodings = processor(images=images, return_tenso... | import argparse
import os.path
import json
from texify.inference import batch_inference
from texify.model.model import load_model
from texify.model.processor import load_processor
from PIL import Image
from texify.output import replace_katex_invalid
from texify.settings import settings
from texify.util import is_valid_... | 1,160 |
def inference_single_image(image_path, json_path, model, processor, katex_compatible=False):
image = Image.open(image_path)
text = batch_inference([image], model, processor)
if katex_compatible:
text = [replace_katex_invalid(t) for t in text]
write_data = [{"image_path": image_path, "text": ... |
def inference_single_image(image_path, json_path, model, processor, katex_compatible=False):
image = Image.open(image_path)
text = batch_inference([image], model, processor)
if katex_compatible:
text = [replace_katex_invalid(t) for t in text]
write_data = [{"image_path": image_path, "text": ... | image_paths = [ip for ip in image_paths if is_valid_image(ip)] | 5 | 2023-12-18 22:59:58+00:00 | 2k |
dcharatan/pixelsplat | src/visualization/drawing/points.py | [
{
"identifier": "generate_conversions",
"path": "src/visualization/drawing/coordinate_conversion.py",
"snippet": "def generate_conversions(\n shape: tuple[int, int],\n device: torch.device,\n x_range: Optional[Pair] = None,\n y_range: Optional[Pair] = None,\n) -> tuple[\n ConversionFuncti... | from typing import Optional
from einops import repeat
from jaxtyping import Float
from torch import Tensor
from .coordinate_conversion import generate_conversions
from .rendering import render_over_image
from .types import Pair, Scalar, Vector, sanitize_scalar, sanitize_vector
import torch | 839 |
def draw_points(
image: Float[Tensor, "3 height width"],
points: Vector,
color: Vector = [1, 1, 1],
radius: Scalar = 1,
inner_radius: Scalar = 0,
num_msaa_passes: int = 1,
x_range: Optional[Pair] = None,
y_range: Optional[Pair] = None,
) -> Float[Tensor, "3 height width"]:
device... |
def draw_points(
image: Float[Tensor, "3 height width"],
points: Vector,
color: Vector = [1, 1, 1],
radius: Scalar = 1,
inner_radius: Scalar = 0,
num_msaa_passes: int = 1,
x_range: Optional[Pair] = None,
y_range: Optional[Pair] = None,
) -> Float[Tensor, "3 height width"]:
device... | world_to_pixel, _ = generate_conversions((h, w), device, x_range, y_range) | 0 | 2023-12-20 19:45:59+00:00 | 2k |
nianhua99/PandoraNext-Helper | share/share.py | [
{
"identifier": "db",
"path": "model.py",
"snippet": "class User(db.Model):\n def keys(self):\n def __getitem__(self, item):\n def __repr__(self):"
},
{
"identifier": "share_tools",
"path": "util/share_tools.py",
"snippet": "def get_host():\ndef get_share_token(access_token, uni... | import json
from datetime import datetime
from flask import Blueprint, request
from flask_jwt_extended import jwt_required
from loguru import logger
from sqlalchemy import and_, text
from model import db, User
from util import share_tools
from util.api_response import ApiResponse
from util.pandora_tools import sync_pan... | 680 |
share_bp = Blueprint('share_bp', __name__)
def account2share(accounts):
shares = []
for account in accounts:
_share_list = json.loads(account.share_list)
for share in _share_list:
share['email'] = account.email
share['account_id'] = account.id
shares.appe... |
share_bp = Blueprint('share_bp', __name__)
def account2share(accounts):
shares = []
for account in accounts:
_share_list = json.loads(account.share_list)
for share in _share_list:
share['email'] = account.email
share['account_id'] = account.id
shares.appe... | res = share_tools.get_share_token(account.access_token, unique_name) | 1 | 2023-12-18 13:18:50+00:00 | 2k |
shroominic/fastui-chat | src/fastui_chat/chat.py | [
{
"identifier": "ChatInputForm",
"path": "src/fastui_chat/components.py",
"snippet": "class ChatInputForm(c.Form):\n \"\"\"\n Component for displaying a chat input form.\n \"\"\"\n\n fire_page_event: str\n display_mode: str = \"inline\"\n class_name: str = \"row row-cols-lg-3 justify-c... | from typing import Annotated, AsyncIterable
from fastapi import APIRouter, Depends, Form
from fastapi.responses import StreamingResponse
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.events import PageEvent
from langchain_core.chat_history import BaseChatMessageHistory
from .com... | 1,428 |
router = APIRouter()
@router.get("/", response_model=FastUI, response_model_exclude_none=True)
async def chat_ui() -> list[AnyComponent]:
"""
Main endpoint for showing the Chat UI and handling user input.
"""
return [
c.Page(
components=[
c.ServerLoad(
... |
router = APIRouter()
@router.get("/", response_model=FastUI, response_model_exclude_none=True)
async def chat_ui() -> list[AnyComponent]:
"""
Main endpoint for showing the Chat UI and handling user input.
"""
return [
c.Page(
components=[
c.ServerLoad(
... | session: Annotated[ChatSession, Depends(get_session)], | 3 | 2023-12-17 15:07:48+00:00 | 2k |
SHI-Labs/VCoder | vcoder_llava/model/vcoder_ds_llava_arch.py | [
{
"identifier": "build_vision_tower",
"path": "vcoder_llava/model/multimodal_encoder/builder.py",
"snippet": "def build_vision_tower(vision_tower_cfg, **kwargs):\n vision_tower = getattr(vision_tower_cfg, 'mm_vision_tower', getattr(vision_tower_cfg, 'vision_tower', None))\n is_absolute_path_exists... | from abc import ABC, abstractmethod
from .multimodal_encoder.builder import build_vision_tower
from .multimodal_projector.builder import build_vision_projector
from .multimodal_adapter.builder import build_seg_projector
from .multimodal_depth_adapter.builder import build_depth_projector
from vcoder_llava.constants impo... | 1,210 | # Copyright 2023 Haotian Liu
#
# 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 agre... | # Copyright 2023 Haotian Liu
#
# 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 agre... | self.mm_projector = build_vision_projector(config) | 1 | 2023-12-17 07:46:27+00:00 | 2k |
galatolofederico/microchain | microchain/engine/engine.py | [
{
"identifier": "Function",
"path": "microchain/engine/function.py",
"snippet": "class Function:\n def __init__(self):\n self.call_signature = inspect.signature(self.__call__) \n self.call_parameters = []\n for name, parameter in self.call_signature.parameters.items():\n ... | import ast
from microchain.engine.function import Function, FunctionResult | 801 |
class Engine:
def __init__(self, state=dict()):
self.state = state
self.functions = dict()
self.help_called = False
self.agent = None
def register(self, function):
self.functions[function.name] = function
function.bind(state=self.state, engine=self)
de... |
class Engine:
def __init__(self, state=dict()):
self.state = state
self.functions = dict()
self.help_called = False
self.agent = None
def register(self, function):
self.functions[function.name] = function
function.bind(state=self.state, engine=self)
de... | return FunctionResult.ERROR, f"Error: syntax error in command {command}. Please try again." | 1 | 2023-12-19 10:57:56+00:00 | 2k |
OSU-NLP-Group/SeeAct | src/data_utils/format_prompt_utils.py | [
{
"identifier": "get_tree_repr",
"path": "src/data_utils/dom_utils.py",
"snippet": "def get_tree_repr(\n tree, max_value_length=5, max_length=20, id_mapping={}, keep_html_brackets=False\n):\n if isinstance(tree, str):\n tree = etree.fromstring(tree)\n else:\n tree = copy.deepc... | import string
import lxml
from .dom_utils import get_tree_repr, data_prune_tree | 1,404 | # -*- coding: utf-8 -*-
# Copyright (c) 2024 OSU Natural Language Processing Group
#
# Licensed under the OpenRAIL-S License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.licenses.ai/ai-pubs-open-rails-vz1
#
# Unless required by applica... | # -*- coding: utf-8 -*-
# Copyright (c) 2024 OSU Natural Language Processing Group
#
# Licensed under the OpenRAIL-S License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.licenses.ai/ai-pubs-open-rails-vz1
#
# Unless required by applica... | tree_repr, id_mapping = get_tree_repr( | 0 | 2023-12-21 18:22:11+00:00 | 2k |
DeepWok/mase | machop/chop/passes/graph/analysis/add_metadata/add_software_metadata.py | [
{
"identifier": "get_mase_op",
"path": "machop/chop/passes/graph/utils.py",
"snippet": "def get_mase_op(node):\n return node.meta[\"mase\"].parameters[\"common\"][\"mase_op\"]"
},
{
"identifier": "get_mase_type",
"path": "machop/chop/passes/graph/utils.py",
"snippet": "def get_mase_ty... | import logging
from ...utils import get_mase_op, get_mase_type
from .software_metadata_layers import SOFTWARE_PARAM_ANALYSIS_LAYERS | 1,107 |
logger = logging.getLogger(__name__)
def add_software_metadata_analysis_pass(graph, pass_args=None):
"""add software metadata
:param graph: a MaseGraph
:type graph: MaseGraph
:param pass_args: this pass does not need any arguments, defaults to None
:type pass_args: _type_, optional
:return:... |
logger = logging.getLogger(__name__)
def add_software_metadata_analysis_pass(graph, pass_args=None):
"""add software metadata
:param graph: a MaseGraph
:type graph: MaseGraph
:param pass_args: this pass does not need any arguments, defaults to None
:type pass_args: _type_, optional
:return:... | mase_op = get_mase_op(node) | 0 | 2023-12-18 12:50:53+00:00 | 2k |
PratikSingh121/ResearchPlot | main.py | [
{
"identifier": "GetPromptTemplates",
"path": "app/prompt_templates.py",
"snippet": "class GetPromptTemplates:\n def __init__(self, topic):\n self.topic = topic\n self.question_parser = CommaSeparatedListOutputParser()\n \n def ResearchPromptTemplate(self, questions = ''):\n if questions != ... | from langchain.output_parsers import CommaSeparatedListOutputParser
from app.prompt_templates import GetPromptTemplates
from app.question_framing import QuestionFraming
from packages.chains import Chains
import subprocess
import os | 818 | #app
#package
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Getting Topic
print('\033[93m' + "Enter the topic. You can add just a keyword or a description.\nTopic : > " + '\033[0m', end="")
topic = input()
print()
#Objects
Chain = Chains()
PromptTemplate = GetPromptTemplates(topic)
QuestionParser = CommaSe... | #app
#package
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Getting Topic
print('\033[93m' + "Enter the topic. You can add just a keyword or a description.\nTopic : > " + '\033[0m', end="")
topic = input()
print()
#Objects
Chain = Chains()
PromptTemplate = GetPromptTemplates(topic)
QuestionParser = CommaSe... | questionframing = QuestionFraming(QuestionsList) | 1 | 2023-12-17 10:23:00+00:00 | 2k |
yeyt97/AirDropPlus | AirDropPlus.py | [
{
"identifier": "Config",
"path": "config.py",
"snippet": "class Config:\n def __init__(self, config_path):\n self.config = configparser.ConfigParser()\n self.config.read(config_path, encoding='utf-8')\n\n self.config_path = config_path\n self.key = self.config.get('config... | import os
import sys
import utils
from config import Config
from notifier import create_notifier
from server import Server | 1,571 |
if __name__ == '__main__':
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
config_file_path = os.path.join(SCRIPT_DIR, 'config', 'config.ini')
|
if __name__ == '__main__':
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
config_file_path = os.path.join(SCRIPT_DIR, 'config', 'config.ini') | config = Config(config_file_path) | 0 | 2023-12-19 08:16:21+00:00 | 2k |
byeongjun-park/HarmonyView | ldm/thirdp/psp/model_irse.py | [
{
"identifier": "get_blocks",
"path": "ldm/thirdp/psp/helpers.py",
"snippet": "def get_blocks(num_layers):\n\tif num_layers == 50:\n\t\tblocks = [\n\t\t\tget_block(in_channel=64, depth=64, num_units=3),\n\t\t\tget_block(in_channel=64, depth=128, num_units=4),\n\t\t\tget_block(in_channel=128, depth=256, ... | from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Dropout, Sequential, Module
from ldm.thirdp.psp.helpers import get_blocks, Flatten, bottleneck_IR, bottleneck_IR_SE, l2_norm | 1,154 | # https://github.com/eladrich/pixel2style2pixel
"""
Modified Backbone implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch)
"""
class Backbone(Module):
def __init__(self, input_size, num_layers, mode='ir', drop_ratio=0.4, affine=True):
super(Backbone, self).__init__()
assert input_size ... | # https://github.com/eladrich/pixel2style2pixel
"""
Modified Backbone implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch)
"""
class Backbone(Module):
def __init__(self, input_size, num_layers, mode='ir', drop_ratio=0.4, affine=True):
super(Backbone, self).__init__()
assert input_size ... | blocks = get_blocks(num_layers) | 0 | 2023-12-21 04:44:00+00:00 | 2k |
srlabs/black-basta-buster | extractblock.py | [
{
"identifier": "detect_magic_size",
"path": "decryptblocks.py",
"snippet": "def make_int(i):\ndef make_int_or_percent(i):\ndef xor_blocks(var, key, byteorder=sys.byteorder):\ndef write_block(fd, offset, block):\ndef main():\ndef decrypt_file(f, keyblock, fsize=None, is_dry=True, lower_limit=None, upper... | import argparse
import logging
import sys
import logging
import math
from collections import deque
from itertools import islice
from pathlib import Path
from hexdump import hexdump
from decryptblocks import detect_magic_size, make_int, make_int_or_percent, Percent
from ranges import ranges_for_file
from collect... | 1,455 |
log = logging.getLogger(__name__)
def extract_block(fd, offset, size=64):
#log.debug("Reading %r at %r for %r ", fd, offset, size)
fd.seek(offset)
block = fd.read(size)
log.debug("Read %i bytes at %r for %r:\n%s", len(block), offset, size, hexdump(block, result="return"))
return block
def make_... | #!/usr/bin/env python3
# Copyright 2023 Tobias Mueller <tobias@srlabs.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any late... | if isinstance(start_at, Percent): | 0 | 2023-12-20 20:04:51+00:00 | 2k |
EntySec/SeaShell | seashell/core/console.py | [
{
"identifier": "Banner",
"path": "seashell/utils/ui/banner.py",
"snippet": "class Banner(object):\n \"\"\" Subclass of seashell.core module.\n\n This subclass of seashell.core module is intended for\n providing tools for printing banners in UI.\n \"\"\"\n\n def __init__(self) -> None:\n ... | import os
import cmd
import sys
from badges import Badges, Tables
from colorscript import ColorScript
from hatsploit.lib.commands import Commands
from hatsploit.lib.runtime import Runtime
from seashell.utils.ui.banner import Banner
from seashell.utils.ui.tip import Tip
from seashell.lib.config import Config | 1,297 | """
MIT License
Copyright (c) 2020-2024 EntySec
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, ... | """
MIT License
Copyright (c) 2020-2024 EntySec
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, ... | self.tip = Tip() | 1 | 2023-12-17 04:14:16+00:00 | 2k |
FlagOpen/TACO | train.py | [
{
"identifier": "Trainer",
"path": "train_utils.py",
"snippet": "class Trainer(transformers.Trainer):\n \"\"\"Use CosineAnnealingLR from pytorch \n \"\"\"\n \n def create_scheduler(self, num_training_steps: int, optimizer: torch.optim.Optimizer = None):\n \"\"\"\n Setup the sch... | from typing import Optional, Dict
from dataclasses import dataclass, field
from train_utils import Trainer
from datamodule import DEFAULT_PAD_TOKEN, DEFAULT_EOS_TOKEN, DEFAULT_BOS_TOKEN, TacoDataset, DataCollatorForTacoDataset
import transformers | 1,568 | """
Finetune models on TACO-Dataset train split
"""
@dataclass
class ModelArguments:
model_name_or_path: Optional[str] = field(default="bigcode/tiny_starcoder_py")
@dataclass
class DataArguments:
data_path: str = field(default=None, metadata={"help": "Path to the training data."})
@dataclass
class Trai... | """
Finetune models on TACO-Dataset train split
"""
@dataclass
class ModelArguments:
model_name_or_path: Optional[str] = field(default="bigcode/tiny_starcoder_py")
@dataclass
class DataArguments:
data_path: str = field(default=None, metadata={"help": "Path to the training data."})
@dataclass
class Trai... | train_dataset = TacoDataset(data_path=data_args.data_path) | 4 | 2023-12-20 03:12:01+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.