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 |
|---|---|---|---|---|---|---|---|---|---|---|
google-research/semivl | model/vlm.py | [
{
"identifier": "aggregate_concept_predictions",
"path": "model/text_embeddings.py",
"snippet": "def aggregate_concept_predictions(pred, class_to_concept_idxs):\n B, _, H, W = pred.shape\n agg_pred = torch.zeros(B, len(class_to_concept_idxs), H, W, device=pred.device)\n for cls_i, conc_i in cla... | import numpy as np
import torch
import torch.nn.functional as F
from mmseg.models import builder
from mmseg.models.builder import SEGMENTORS
from mmseg.models.segmentors.encoder_decoder import EncoderDecoder
from model.text_embeddings import (aggregate_concept_predictions,
get_class_t... | 1,186 | # Copyright 2023 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2023 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | cls2con = get_class_to_concept_idxs(self.load_mcc_text_embedding) | 1 | 2023-11-02 14:49:38+00:00 | 2k |
ej52/hass-ollama-conversation | custom_components/ollama_conversation/api.py | [
{
"identifier": "TIMEOUT",
"path": "custom_components/ollama_conversation/const.py",
"snippet": "TIMEOUT = 60"
},
{
"identifier": "ApiClientError",
"path": "custom_components/ollama_conversation/exceptions.py",
"snippet": "class ApiClientError(HomeAssistantError):\n \"\"\"Exception to... | import asyncio
import socket
import aiohttp
import async_timeout
from .const import TIMEOUT
from .exceptions import (
ApiClientError,
ApiCommError,
ApiJsonError,
ApiTimeoutError
) | 692 | """Ollama API Client."""
from __future__ import annotations
class OllamaApiClient:
"""Ollama API Client."""
def __init__(
self,
base_url: str,
session: aiohttp.ClientSession,
) -> None:
"""Sample API Client."""
self._base_url = base_url.rstrip("/")
self.... | """Ollama API Client."""
from __future__ import annotations
class OllamaApiClient:
"""Ollama API Client."""
def __init__(
self,
base_url: str,
session: aiohttp.ClientSession,
) -> None:
"""Sample API Client."""
self._base_url = base_url.rstrip("/")
self.... | raise ApiCommError("unknown error while talking to the server") from e | 2 | 2023-11-03 14:48:45+00:00 | 2k |
Zaczero/openstreetmap-ng | src/repositories/message_repository.py | [
{
"identifier": "DB",
"path": "src/db.py",
"snippet": "DB = async_sessionmaker(\n DB_ENGINE,\n expire_on_commit=False,\n)"
},
{
"identifier": "Message",
"path": "src/models/db/message.py",
"snippet": "class Message(Base.Sequential, CreatedAtMixin, RichTextMixin):\n __tablename__... | from sqlalchemy import false, func, select
from src.db import DB
from src.models.db.message import Message | 808 |
class MessageRepository:
@staticmethod
async def count_received_by_user_id(user_id: int) -> tuple[int, int]:
"""
Count received messages by user id.
Returns a tuple of (total, unread).
"""
|
class MessageRepository:
@staticmethod
async def count_received_by_user_id(user_id: int) -> tuple[int, int]:
"""
Count received messages by user id.
Returns a tuple of (total, unread).
"""
| async with DB() as session: | 0 | 2023-11-04 01:12:13+00:00 | 2k |
codefuse-ai/Collinear-Constrained-Attention | data/multi_task_dataset.py | [
{
"identifier": "print_rank_0",
"path": "utils/common_utils.py",
"snippet": "def print_rank_0(*message):\n \"\"\"If distributed is initialized print only on rank 0.\"\"\"\n if torch.distributed.is_initialized():\n if torch.distributed.get_rank() == 0:\n print(*message, flush=True... | import os
import math
import json
import random
import time
import numpy as np
import torch
from functools import partial
from utils.common_utils import print_rank_0, TASK2ID, ID2TASK, get_local_rank
from data import helpers | 864 |
class SingleTaskDataset(torch.utils.data.Dataset):
def __init__(
self,
name,
data_prefix,
input_dataset,
# loss_mask_dataset,
# num_samples,
seq_length,
weighted_loss_mode=None,
ds_weight=1.0,
):
... |
class SingleTaskDataset(torch.utils.data.Dataset):
def __init__(
self,
name,
data_prefix,
input_dataset,
# loss_mask_dataset,
# num_samples,
seq_length,
weighted_loss_mode=None,
ds_weight=1.0,
):
... | print_rank_0(f'self.tokenizer.sop_token {self.tokenizer.sop_token} id: {self.sop_id}') | 0 | 2023-11-02 01:37:01+00:00 | 2k |
rezaakb/pinns-tf2 | pinnstf2/models/pinn_module.py | [
{
"identifier": "gradient",
"path": "pinnstf2/utils/gradient.py",
"snippet": "def gradient(dy, dx, grad_ys=None):\n if grad_ys is None:\n dy_dx = tf.gradients(dy, dx)\n else:\n dy_dx = tf.gradients(dy, dx, grad_ys=grad_ys)\n if len(dy_dx)==1:\n dy_dx = dy_dx[0]\n return ... | from typing import List, Dict, Callable, Any, Tuple, Union
from pinnstf2.utils import fwd_gradient, gradient
from pinnstf2.utils import (
fix_extra_variables,
mse,
relative_l2_error,
sse
)
import tensorflow as tf
import sys, os, logging, time | 1,554 |
class PINNModule:
def __init__(
self,
net,
pde_fn: Callable[[Any, ...], tf.Tensor],
optimizer: tf.keras.optimizers.Adam = tf.keras.optimizers.Adam,
loss_fn: str = "sse",
extra_variables: Dict[str, Any] = None,
output_fn: Callable[[Any, ...], tf.Tensor] = No... |
class PINNModule:
def __init__(
self,
net,
pde_fn: Callable[[Any, ...], tf.Tensor],
optimizer: tf.keras.optimizers.Adam = tf.keras.optimizers.Adam,
loss_fn: str = "sse",
extra_variables: Dict[str, Any] = None,
output_fn: Callable[[Any, ...], tf.Tensor] = No... | self.extra_variables) = fix_extra_variables(self.trainable_variables, extra_variables, self.tf_dtype) | 2 | 2023-11-01 03:25:51+00:00 | 2k |
djinni-co/djinni-inbox-test | app/sandbox/views.py | [
{
"identifier": "Recruiter",
"path": "app/sandbox/models.py",
"snippet": "class Recruiter(models.Model):\n USERTYPE = \"recruiter\"\n\n name = models.CharField(max_length=255, blank=True, default='')\n email = models.EmailField(blank=False, db_index=True, unique=True)\n picture_url = models.... | from django.http import HttpResponse
from django.db.models import Count, Q
from django.shortcuts import render
from .models import Recruiter, MessageThread | 736 |
# Hardcode for logged in as recruiter
RECRUITER_ID = 125528
def inbox(request):
recruiter = Recruiter.objects.get(id = RECRUITER_ID)
|
# Hardcode for logged in as recruiter
RECRUITER_ID = 125528
def inbox(request):
recruiter = Recruiter.objects.get(id = RECRUITER_ID) | threads = MessageThread.objects.filter(recruiter = recruiter).select_related('candidate', 'job') | 1 | 2023-11-02 15:12:54+00:00 | 2k |
XinyuanWangCS/PromptAgent | src/prompt_optim_agent/world_model/beam_world_model.py | [
{
"identifier": "eval_instruction_with_loader",
"path": "src/prompt_optim_agent/test_helper.py",
"snippet": "def eval_instruction_with_loader(task, eval_prompt, dataloader, model='gpt-3.5-turbo', temperature=0, record_outputs=True):\n '''\n evaluate cur_prompt on task testing dataset\n '''\... | from .gradient_descent import *
from typing import NamedTuple
from ..test_helper import eval_instruction_with_loader
from typing import Generic
from ..search_algo.base_algo import State, Action
from ..search_algo.beam_search import BeamNode
from ..utils import gpt_chat_completion | 1,462 |
class BeamSearchWorldModel(Generic[State, Action]):
def __init__(
self,
task,
logger,
# model
pred_model: str,
optim_model: str,
pred_temperature: float,
optim_temperature: float,
prompt_length_limit:int,
num_new_pro... |
class BeamSearchWorldModel(Generic[State, Action]):
def __init__(
self,
task,
logger,
# model
pred_model: str,
optim_model: str,
pred_temperature: float,
optim_temperature: float,
prompt_length_limit:int,
num_new_pro... | def _get_trajectory_prompts(self, node: BeamNode): | 2 | 2023-11-03 19:14:00+00:00 | 2k |
evaluable-ai/auto-eval | evaluableai/models/candidate_models/null_model.py | [
{
"identifier": "InputRow",
"path": "evaluableai/data_model/input_row_object.py",
"snippet": "class InputRow:\n def __init__(self, input_text, context, input_id=None):\n self._input_id = input_id if input_id is not None else uuid.uuid4()\n self._input_text = input_text\n self._co... | import json
import logging
import uuid
from evaluableai.data_model.input_row_object import InputRow
from evaluableai.data_model.model_response_object import ModelResponseObject | 1,108 |
# Make sure to import InputRow if it's a separate class
class NullModel:
def __init__(self, model_name, model_version):
self._model_name = model_name
self._model_version = model_version
@property
def model_name(self):
return self._model_name
@property
def model_version(... |
# Make sure to import InputRow if it's a separate class
class NullModel:
def __init__(self, model_name, model_version):
self._model_name = model_name
self._model_version = model_version
@property
def model_name(self):
return self._model_name
@property
def model_version(... | input_row = InputRow(input_text, context) # Assuming InputRow is imported | 0 | 2023-11-06 01:26:17+00:00 | 2k |
allenai/wimbd | wimbd/contamination/promptsource_parse.py | [
{
"identifier": "INCLUDED_USERS",
"path": "wimbd/contamination/templates.py",
"snippet": "INCLUDED_USERS = {\"Zaid\", \"craffel\"}"
},
{
"identifier": "TemplateCollection",
"path": "wimbd/contamination/templates.py",
"snippet": "class TemplateCollection:\n \"\"\"\n This helper clas... | import argparse
import csv
import re
from glob import glob
from wimbd.contamination.templates import INCLUDED_USERS, TemplateCollection
from wimbd.contamination.utils import get_dataset | 1,194 |
def main():
parse = argparse.ArgumentParser("")
parse.add_argument("--path", type=str)
parse.add_argument("--out_file", type=str)
args = parse.parse_args()
datasets = []
for path in glob(args.path + '/**/templates.yaml', recursive=True):
datasets.append(path)
with... |
def main():
parse = argparse.ArgumentParser("")
parse.add_argument("--path", type=str)
parse.add_argument("--out_file", type=str)
args = parse.parse_args()
datasets = []
for path in glob(args.path + '/**/templates.yaml', recursive=True):
datasets.append(path)
with... | template_collection = TemplateCollection() | 1 | 2023-11-08 18:18:41+00:00 | 2k |
kakaobrain/cxr-clip | cxrclip/data/datasets/imagetext_eval.py | [
{
"identifier": "load_transform",
"path": "cxrclip/data/data_utils.py",
"snippet": "def load_transform(split: str = \"train\", transform_config: Dict = None):\n assert split in {\"train\", \"valid\", \"test\", \"aug\"}\n\n config = []\n if transform_config:\n if split in transform_config... | import ast
import pandas as pd
from typing import Dict, List
from PIL import Image
from torch.utils.data import default_collate
from torch.utils.data.dataset import Dataset
from cxrclip.data.data_utils import load_transform, transform_image
from cxrclip.prompt.constants import CHEXPERT_CLASS_PROMPTS | 1,417 |
class ImageTextEvalDataset(Dataset):
def __init__(
self,
name: str,
data_path: str,
split: str,
data_frac: float = 1.0,
tokenizer=None,
text_max_length: int = 256,
transform_config: Dict = None,
normalize: str = "huggingface",
**kwa... |
class ImageTextEvalDataset(Dataset):
def __init__(
self,
name: str,
data_path: str,
split: str,
data_frac: float = 1.0,
tokenizer=None,
text_max_length: int = 256,
transform_config: Dict = None,
normalize: str = "huggingface",
**kwa... | self.label_list = list(CHEXPERT_CLASS_PROMPTS.keys()) | 2 | 2023-11-01 07:24:52+00:00 | 2k |
mihirp1998/Diffusion-TTA | diff_tta/models/build.py | [
{
"identifier": "get_obj_from_str",
"path": "diff_tta/utils.py",
"snippet": "def get_obj_from_str(string, reload=False):\n \"\"\"A helper function to instantiate a class from a config object.\n See https://github.com/CompVis/stable-diffusion/blob/main/ldm/util.py\n \"\"\"\n module, cls = str... | import torch
import torch.nn as nn
import torchvision
from diffusers import (
AutoencoderKL,
UNet2DConditionModel,
DDPMScheduler,
StableDiffusionPipeline,
EulerDiscreteScheduler
)
from transformers import CLIPTextModel, CLIPTokenizer
from diff_tta.utils import get_obj_from_str
from diff_tta.models.D... | 893 |
def load_dit_model(config, device):
"""Load DiT model"""
#@param ["stabilityai/sd-vae-ft-mse", "stabilityai/sd-vae-ft-ema"]
vae_model = "stabilityai/sd-vae-ft-ema"
image_size = config.input.sd_img_res
latent_size = int(image_size) // 8
model = DiT_XL_2(input_size=latent_size).to(device)
... |
def load_dit_model(config, device):
"""Load DiT model"""
#@param ["stabilityai/sd-vae-ft-mse", "stabilityai/sd-vae-ft-ema"]
vae_model = "stabilityai/sd-vae-ft-ema"
image_size = config.input.sd_img_res
latent_size = int(image_size) // 8
model = DiT_XL_2(input_size=latent_size).to(device)
... | image_renormalizer = utils.VQVAEUnNormalize( | 2 | 2023-11-07 21:09:50+00:00 | 2k |
pofey/MemAI-Flow | memflow/main.py | [
{
"identifier": "CuboxErrorException",
"path": "memflow/exceptions.py",
"snippet": "class CuboxErrorException(RuntimeError):\n def __init__(self, message):\n self.message = message"
},
{
"identifier": "LOGGING_CONFIG",
"path": "memflow/common/logging.py",
"snippet": "LOGGING_CO... | import os
import logging.config
import inject
import httpx
import uvicorn
from memflow.exceptions import CuboxErrorException
from apscheduler.schedulers.background import BackgroundScheduler
from fastapi.exceptions import RequestValidationError
from memflow.common.logging import LOGGING_CONFIG
from memflow.memapi impor... | 1,424 | """
程序启动入口类
"""
if not os.environ.get("WORKDIR"):
workdir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data')
else:
workdir = os.environ.get("WORKDIR")
if not os.path.exists(workdir):
os.makedirs(workdir)
log_dir = os.path.join(workdir, 'logs')
if not os.path.exists(log_dir... | """
程序启动入口类
"""
if not os.environ.get("WORKDIR"):
workdir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data')
else:
workdir = os.environ.get("WORKDIR")
if not os.path.exists(workdir):
os.makedirs(workdir)
log_dir = os.path.join(workdir, 'logs')
if not os.path.exists(log_dir... | logging.config.dictConfig(LOGGING_CONFIG) | 1 | 2023-11-08 10:02:00+00:00 | 2k |
sdebruyn/dbt-timescaledb | dbt/adapters/timescaledb/timescaledb_adapter.py | [
{
"identifier": "NO_TRANSACTION_MARKER",
"path": "dbt/adapters/timescaledb/timescaledb_connection_manager.py",
"snippet": "NO_TRANSACTION_MARKER = \"/* MARKER SHOULD RUN OUTSIDE TRANSACTION */\""
},
{
"identifier": "TimescaleDBConnectionManager",
"path": "dbt/adapters/timescaledb/timescaledb... | from typing import Any, Optional
from dbt.adapters.base.meta import available
from dbt.adapters.postgres import PostgresAdapter
from dbt.adapters.timescaledb.timescaledb_connection_manager import (
NO_TRANSACTION_MARKER,
TimescaleDBConnectionManager,
)
from dbt.adapters.timescaledb.timescaledb_index_config impo... | 699 |
class TimescaleDBAdapter(PostgresAdapter):
ConnectionManager = TimescaleDBConnectionManager
@available
def parse_index(self, raw_index: Any) -> Optional[TimescaleDBIndexConfig]:
return TimescaleDBIndexConfig.parse(raw_index)
@available
def marker_run_outside_transaction(self) -> str:
|
class TimescaleDBAdapter(PostgresAdapter):
ConnectionManager = TimescaleDBConnectionManager
@available
def parse_index(self, raw_index: Any) -> Optional[TimescaleDBIndexConfig]:
return TimescaleDBIndexConfig.parse(raw_index)
@available
def marker_run_outside_transaction(self) -> str: | return NO_TRANSACTION_MARKER | 0 | 2023-11-07 21:54:46+00:00 | 2k |
jax-ml/bayeux | bayeux/_src/shared.py | [
{
"identifier": "debug",
"path": "bayeux/_src/debug.py",
"snippet": "def debug(model, seed, verbosity, printer, kwargs, catch_exceptions: bool):\n \"\"\"Debugger that includes the inverse log det jacobian.\"\"\"\n checkers = [\n check_shapes,\n check_test_point_log_density,\n check_kwar... | import dataclasses
import functools
import inspect
import jax
import jax.numpy as jnp
import oryx
from typing import Callable, Optional
from bayeux._src import debug
from bayeux._src import initialization
from bayeux._src import types | 1,108 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | # Copyright 2023 The bayeux 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 to in w... | def debug( | 0 | 2023-11-02 16:52:57+00:00 | 2k |
zamaniamin/fastapi-shop | apps/main.py | [
{
"identifier": "DatabaseManager",
"path": "config/database.py",
"snippet": "class DatabaseManager:\n \"\"\"\n A utility class for managing database operations using SQLAlchemy.\n\n The DatabaseManager simplifies the process of initializing and managing database connections, creating database\n... | from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from config.database import DatabaseManager
from config.routers import RouterManager
from config.settings import MEDIA_DIR | 1,496 |
# -------------------
# --- Init Models ---
# -------------------
DatabaseManager().create_database_tables()
# --------------------
# --- Init FastAPI ---
# --------------------
app = FastAPI()
# ------------------
# --- Middleware ---
# ------------------
app.add_middleware(
CORSMiddleware,
allow_origin... |
# -------------------
# --- Init Models ---
# -------------------
DatabaseManager().create_database_tables()
# --------------------
# --- Init FastAPI ---
# --------------------
app = FastAPI()
# ------------------
# --- Middleware ---
# ------------------
app.add_middleware(
CORSMiddleware,
allow_origin... | RouterManager(app).import_routers() | 1 | 2023-11-06 04:46:03+00:00 | 2k |
jkulhanek/nerfbaselines | tests/test_utils.py | [
{
"identifier": "Indices",
"path": "nerfbaselines/utils.py",
"snippet": "class Indices:\n def __init__(self, steps):\n self._steps = steps\n self.total: Optional[int] = None\n\n def __contains__(self, x):\n if isinstance(self._steps, list):\n steps = self._steps\n ... | import pytest
from time import sleep, perf_counter
from nerfbaselines.utils import Indices
from nerfbaselines.utils import cancellable, CancellationToken, CancelledException
from nerfbaselines.utils import get_resources_utilization_info | 1,160 |
def test_indices_last():
indices = Indices([-1])
indices.total = 12
for i in range(12):
if i == indices.total - 1:
assert i in indices
else:
assert i not in indices
class TimeLimitCancellationToken(CancellationToken):
def __init__(self, timeout=0.003):
... |
def test_indices_last():
indices = Indices([-1])
indices.total = 12
for i in range(12):
if i == indices.total - 1:
assert i in indices
else:
assert i not in indices
class TimeLimitCancellationToken(CancellationToken):
def __init__(self, timeout=0.003):
... | @cancellable | 1 | 2023-11-07 20:22:35+00:00 | 2k |
microsoft/Everything-of-Thoughts-XoT | xot_all_in_one/xot/prompter/prompter_cube.py | [
{
"identifier": "doAlgStr",
"path": "xot_all_in_one/xot/prompter/utils/py222.py",
"snippet": "def doAlgStr(s, alg):\n # print('',alg)\n moves = alg.split(\" \")\n # print('moves',moves)\n for m in moves:\n if m in moveInds:\n s = doMove(s, moveInds[m])\n return s"
},
{
"identifier":... | import re
import os
import sympy
import numpy as np
import pandas as pd
from .prompts.prompts_cube import *
from .utils.py222 import doAlgStr, getCube | 755 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
class CubePrompter():
"""
CubePrompter provides the generation of prompts specific to the cube
example for the language models.
"""
def __init__(self, last_step=True):
self.last_step = int(last_step)
self.valu... | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
class CubePrompter():
"""
CubePrompter provides the generation of prompts specific to the cube
example for the language models.
"""
def __init__(self, last_step=True):
self.last_step = int(last_step)
self.valu... | state2 = getCube(s2) | 1 | 2023-11-08 09:48:34+00:00 | 2k |
ultraleap/leapc-python-bindings | leapc-python-api/src/leap/device.py | [
{
"identifier": "LeapCStruct",
"path": "leapc-python-api/src/leap/datatypes.py",
"snippet": "class FrameData:\nclass FrameHeader(LeapCStruct):\nclass Vector(LeapCStruct):\nclass Quaternion(LeapCStruct):\nclass Palm(LeapCStruct):\nclass Bone(LeapCStruct):\nclass Digit(LeapCStruct):\nclass Hand(LeapCStruc... | from contextlib import contextmanager
from leapc_cffi import ffi, libleapc
from .datatypes import LeapCStruct
from .enums import get_enum_entries, DevicePID, DeviceStatus
from .exceptions import success_or_raise, LeapError, LeapCannotOpenDeviceError | 863 |
class DeviceNotOpenException(LeapError):
pass
class DeviceStatusInfo:
def __init__(self, status: ffi.CData):
"""Create the DeviceStatusInfo
:param status: The CData defining the status
"""
|
class DeviceNotOpenException(LeapError):
pass
class DeviceStatusInfo:
def __init__(self, status: ffi.CData):
"""Create the DeviceStatusInfo
:param status: The CData defining the status
""" | self._status_flags = get_enum_entries(DeviceStatus, status) | 3 | 2023-11-08 13:35:40+00:00 | 2k |
UMass-Foundation-Model/CoVLM | open_flamingo/src/flamingo_lm.py | [
{
"identifier": "getattr_recursive",
"path": "open_flamingo/src/utils.py",
"snippet": "def getattr_recursive(obj, att):\n \"\"\"\n Return nested attribute of obj\n Example: getattr_recursive(obj, 'a.b.c') is equivalent to obj.a.b.c\n \"\"\"\n if att == \"\":\n return obj\n i = a... | import random
import torch
import torch.nn as nn
import numpy as np
from .utils import getattr_recursive, setattr_recursive | 1,155 |
class FlamingoLayer(nn.Module):
def __init__(self, decoder_layer):
super().__init__()
self.decoder_layer = decoder_layer
self.vis_x = None
self.image_nums = None
self.image_start_index_list = None
def is_conditioned(self) -> bool:
"""Check whether the layer is... |
class FlamingoLayer(nn.Module):
def __init__(self, decoder_layer):
super().__init__()
self.decoder_layer = decoder_layer
self.vis_x = None
self.image_nums = None
self.image_start_index_list = None
def is_conditioned(self) -> bool:
"""Check whether the layer is... | return getattr_recursive(self, self.decoder_layers_attr_name) | 0 | 2023-11-07 04:23:57+00:00 | 2k |
nouu-me/document_vector_search_benchmark | tools/run_benchmark.py | [
{
"identifier": "DATASET_REGISTRY",
"path": "dvsb/data/dataset.py",
"snippet": "DATASET_REGISTRY = Registry[Dataset]()"
},
{
"identifier": "Dataset",
"path": "dvsb/data/dataset.py",
"snippet": "class Dataset(ABC):\n @abstractmethod\n def get_name(self) -> str:\n \"\"\"Return... | import argparse
import json
import numpy as np
import numpy.typing as npt
import pandas as pd
import yaml
from pathlib import Path
from typing import Iterable
from dvsb.data import DATASET_REGISTRY, Dataset
from dvsb.embedding import EMBEDDING_REGISTRY, Embedding
from dvsb.metric import METRIC_REGISTRY, Metric
from dvs... | 776 |
def get_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser("run_benchmark")
parser.add_argument("-n", "--name", help="config name", required=False, default="default")
parser.add_argument("--no-cache", action="store_true")
return parser
|
def get_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser("run_benchmark")
parser.add_argument("-n", "--name", help="config name", required=False, default="default")
parser.add_argument("--no-cache", action="store_true")
return parser
| def load_dataset(dataset_config: dict, cache: bool) -> Dataset: | 1 | 2023-11-09 00:04:51+00:00 | 2k |
HKU-BAL/ClairS-TO | src/nonsomatic_tagging.py | [
{
"identifier": "VcfReader",
"path": "shared/vcf.py",
"snippet": "class TruthStdout(object):\nclass VcfWriter(object):\nclass VcfReader(object):\n def __init__(self, handle):\n def __del__(self):\n def __init__(self,\n vcf_fn,\n ctg_name=None,\n r... | import os
import shlex
from argparse import ArgumentParser, SUPPRESS
from collections import defaultdict
from shared.vcf import VcfReader, VcfWriter, Position
from shared.utils import str2bool, str_none, reference_sequence_from, subprocess_popen | 1,163 |
major_contigs_order = ["chr" + str(a) for a in list(range(1, 23)) + ["X", "Y"]] + [str(a) for a in
list(range(1, 23)) + ["X", "Y"]]
class VcfReader_Database(object):
def __init__(self, vcf_fn,
ctg_name=None,
... |
major_contigs_order = ["chr" + str(a) for a in list(range(1, 23)) + ["X", "Y"]] + [str(a) for a in
list(range(1, 23)) + ["X", "Y"]]
class VcfReader_Database(object):
def __init__(self, vcf_fn,
ctg_name=None,
... | self.variant_dict = defaultdict(Position) | 0 | 2023-11-07 04:39:16+00:00 | 2k |
the-siesta-group/edfio | tests/test_utils.py | [
{
"identifier": "decode_edfplus_date",
"path": "edfio/_utils.py",
"snippet": "def decode_edfplus_date(date: str) -> datetime.date:\n day, month, year = date.split(\"-\")\n try:\n month_int = _MONTH_NAMES.index(month.upper()) + 1\n except ValueError:\n raise ValueError(f\"Invalid m... | import datetime
import math
import pytest
from edfio._utils import (
decode_edfplus_date,
encode_annotation_duration,
encode_annotation_onset,
encode_edfplus_date,
round_float_to_8_characters,
) | 1,114 |
VALID_EDFPLUS_DATE_PAIRS = (
("02-MAY-1951", datetime.date(1951, 5, 2)),
("02-DEC-1951", datetime.date(1951, 12, 2)),
("02-AUG-1951", datetime.date(1951, 8, 2)),
("02-MAY-2051", datetime.date(2051, 5, 2)),
)
@pytest.mark.parametrize(("string", "datetime_"), VALID_EDFPLUS_DATE_PAIRS)
def test_decode... |
VALID_EDFPLUS_DATE_PAIRS = (
("02-MAY-1951", datetime.date(1951, 5, 2)),
("02-DEC-1951", datetime.date(1951, 12, 2)),
("02-AUG-1951", datetime.date(1951, 8, 2)),
("02-MAY-2051", datetime.date(2051, 5, 2)),
)
@pytest.mark.parametrize(("string", "datetime_"), VALID_EDFPLUS_DATE_PAIRS)
def test_decode... | assert encode_annotation_duration(duration) == expected | 1 | 2023-11-09 09:53:27+00:00 | 2k |
microsoft/folx | folx/operators.py | [
{
"identifier": "Array",
"path": "folx/api.py",
"snippet": "T = TypeVar(\"T\", bound=PyTree[Array])\nR = TypeVar(\"R\", bound=PyTree[Array])\nJAC_DIM = 0 # should be either 0 or -1. TODO: switching is not support.\n GENERAL = 0\n LINEAR_IN_FIRST = 1\n LINEAR_IN_ONE = 2 | LINEAR_IN_FIRST\n L... | from dataclasses import dataclass
from typing import Callable, Protocol
from .api import Array
from .interpreter import forward_laplacian
import jax
import jax.numpy as jnp | 1,332 |
__all__ = [
"Laplacian",
"LaplacianOperator",
"ForwardLaplacianOperator",
"LoopLaplacianOperator",
"ParallelLaplacianOperator",
]
class Laplacian(Protocol):
|
__all__ = [
"Laplacian",
"LaplacianOperator",
"ForwardLaplacianOperator",
"LoopLaplacianOperator",
"ParallelLaplacianOperator",
]
class Laplacian(Protocol): | def __call__(self, x: Array) -> tuple[Array, Array]: | 0 | 2023-11-07 16:32:46+00:00 | 2k |
shuttworth/NICE-SLAM-Easyread | visualizer.py | [
{
"identifier": "config",
"path": "src/config.py",
"snippet": "def load_config(path, default_path=None):\ndef update_recursive(dict1, dict2):\ndef get_model(cfg, nice=True):"
},
{
"identifier": "SLAMFrontend",
"path": "src/tools/viz.py",
"snippet": "class SLAMFrontend:\n def __init__(... | import argparse
import os
import time
import numpy as np
import torch
import cv2
from tqdm import tqdm
from torch.utils.data import DataLoader
from src import config
from src.tools.viz import SLAMFrontend
from src.utils.datasets import get_dataset | 985 |
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Arguments to visualize the SLAM process.'
)
parser.add_argument('config', type=str, help='Path to config file.')
parser.add_argument('--input_folder', type=str,
help='input folder, this have hig... |
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Arguments to visualize the SLAM process.'
)
parser.add_argument('config', type=str, help='Path to config file.')
parser.add_argument('--input_folder', type=str,
help='input folder, this have hig... | frontend = SLAMFrontend(output, init_pose=estimate_c2w_list[0], cam_scale=0.3, | 1 | 2023-11-07 05:09:36+00:00 | 2k |
mileswyn/SAMIHS | models/segment_anything/modeling/image_encoder.py | [
{
"identifier": "LayerNorm2d",
"path": "models/segment_anything/modeling/common.py",
"snippet": "class LayerNorm2d(nn.Module):\n def __init__(self, num_channels: int, eps: float = 1e-6) -> None:\n super().__init__()\n self.weight = nn.Parameter(torch.ones(num_channels))\n self.bi... | import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional, Tuple, Type
from .common import LayerNorm2d, MLPBlock | 1,138 | # 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.
# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.... | # 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.
# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.... | LayerNorm2d(out_chans), | 0 | 2023-11-09 07:26:33+00:00 | 2k |
AlexandrErohin/home-assistant-tplink-router | custom_components/tplink_router/switch.py | [
{
"identifier": "DOMAIN",
"path": "custom_components/tplink_router/const.py",
"snippet": "DOMAIN = \"tplink_router\""
},
{
"identifier": "TPLinkRouterCoordinator",
"path": "custom_components/tplink_router/coordinator.py",
"snippet": "class TPLinkRouterCoordinator(DataUpdateCoordinator):\... | from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant... | 1,050 | from __future__ import annotations
@dataclass
class TPLinkRouterSwitchEntityDescriptionMixin:
method: Callable[[TPLinkRouterCoordinator, bool], Any]
property: str
@dataclass
class TPLinkRouterSwitchEntityDescription(SwitchEntityDescription, TPLinkRouterSwitchEntityDescriptionMixin):
"""A class that desc... | from __future__ import annotations
@dataclass
class TPLinkRouterSwitchEntityDescriptionMixin:
method: Callable[[TPLinkRouterCoordinator, bool], Any]
property: str
@dataclass
class TPLinkRouterSwitchEntityDescription(SwitchEntityDescription, TPLinkRouterSwitchEntityDescriptionMixin):
"""A class that desc... | coordinator = hass.data[DOMAIN][entry.entry_id] | 0 | 2023-11-09 17:38:33+00:00 | 2k |
DaveParr/starpilot | tests/test_utils.py | [
{
"identifier": "get_repo_contents",
"path": "starpilot/utils/utils.py",
"snippet": "def get_repo_contents(\n repos: List[Repository], g: Github, include_readmes: bool = False\n) -> List[Dict]:\n repo_infos = []\n for repo in track(repos, description=\"Reading the stars...\"):\n repo_inf... | from unittest.mock import Mock
from starpilot.utils.utils import get_repo_contents, get_user_starred_repos
import pytest
import os
import github | 1,103 |
def test_get_user_starred_repos_mocked():
# Mock the necessary objects
class MockRepo:
def __init__(self, stargazers_count):
self.stargazers_count = stargazers_count
class MockUser:
def get_starred(self):
return [MockRepo(10), MockRepo(5), MockRepo(8), MockRepo(3... |
def test_get_user_starred_repos_mocked():
# Mock the necessary objects
class MockRepo:
def __init__(self, stargazers_count):
self.stargazers_count = stargazers_count
class MockUser:
def get_starred(self):
return [MockRepo(10), MockRepo(5), MockRepo(8), MockRepo(3... | result = get_user_starred_repos("testuser", MockGithub(), num_repos=3) | 1 | 2023-11-07 20:03:08+00:00 | 2k |
xarray-contrib/xdggs | xdggs/h3.py | [
{
"identifier": "DGGSIndex",
"path": "xdggs/index.py",
"snippet": "class DGGSIndex(Index):\n _dim: str\n _pd_index: PandasIndex\n\n def __init__(self, cell_ids: Any | PandasIndex, dim: str):\n self._dim = dim\n\n if isinstance(cell_ids, PandasIndex):\n self._pd_index = ... | from collections.abc import Mapping
from typing import Any
from h3ronpy.arrow.vector import cells_to_coordinates, coordinates_to_cells
from xarray.indexes import PandasIndex
from xdggs.index import DGGSIndex
from xdggs.utils import _extract_cell_id_variable, register_dggs
import numpy as np
import xarray as xr | 883 |
@register_dggs("h3")
class H3Index(DGGSIndex):
_resolution: int
def __init__(
self,
cell_ids: Any | PandasIndex,
dim: str,
resolution: int,
):
super().__init__(cell_ids, dim)
self._resolution = int(resolution)
@classmethod
def from_variables(
... |
@register_dggs("h3")
class H3Index(DGGSIndex):
_resolution: int
def __init__(
self,
cell_ids: Any | PandasIndex,
dim: str,
resolution: int,
):
super().__init__(cell_ids, dim)
self._resolution = int(resolution)
@classmethod
def from_variables(
... | _, var, dim = _extract_cell_id_variable(variables) | 1 | 2023-11-06 16:11:15+00:00 | 2k |
ApolloAuto/apollo-model-centerpoint | paddle3d/utils/checkpoint.py | [
{
"identifier": "PRETRAINED_HOME",
"path": "paddle3d/env.py",
"snippet": "PRETRAINED_HOME = get_sub_home('pretrained')"
},
{
"identifier": "TMP_HOME",
"path": "paddle3d/env.py",
"snippet": "TMP_HOME = get_sub_home('tmp')"
},
{
"identifier": "download_with_progress",
"path": "... | import os
import filelock
import paddle
from typing import Union
from urllib.parse import unquote, urlparse
from paddle3d.env import PRETRAINED_HOME, TMP_HOME
from paddle3d.utils.download import download_with_progress
from paddle3d.utils.logger import logger
from paddle3d.utils.xarfile import unarchive_with_progress | 1,120 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 applic... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 applic... | logger.warning( | 3 | 2023-11-08 07:08:03+00:00 | 2k |
camlsys/fl-project-template | project/task/default/train_test.py | [
{
"identifier": "ClientConfig",
"path": "project/client/client.py",
"snippet": "class ClientConfig(BaseModel):\n \"\"\"Fit/eval config, allows '.' member acces and static checking.\n\n Used to check weather each component has its own independent config present. Each\n component should then use ... | from collections.abc import Sized
from pathlib import Path
from typing import cast
from flwr.common import NDArrays
from pydantic import BaseModel
from torch import nn
from torch.utils.data import DataLoader
from project.client.client import ClientConfig
from project.fed.utils.utils import generic_set_parameters
from p... | 1,246 |
class TrainConfig(BaseModel):
"""Training configuration, allows '.' member acces and static checking.
Guarantees that all necessary components are present, fails early if config is
mismatched to client.
"""
device: torch.device
# epochs: int
# learning_rate: float
class Config:
... | """Default training and testing functions, local and federated."""
class TrainConfig(BaseModel):
"""Training configuration, allows '.' member acces and static checking.
Guarantees that all necessary components are present, fails early if config is
mismatched to client.
"""
device: torch.devic... | fed_dataloater_generator: FedDataloaderGen, | 2 | 2023-11-08 15:31:44+00:00 | 2k |
alibaba/CloudEval-YAML | evaluate.py | [
{
"identifier": "bleu",
"path": "metrics/bleu.py",
"snippet": "def test(result_str=\"\", reference_str=\"\"):"
},
{
"identifier": "edit_distance",
"path": "metrics/edit_distance.py",
"snippet": "def test(result_str=\"\", reference_str=\"\"):"
},
{
"identifier": "exact_match",
... | import loader
import prompt
import query
import json
import ray
import os
import openai
import time
import importlib
import sys
import random
from tqdm import tqdm
from metrics import bleu, edit_distance, exact_match, kv_match
from metrics import kv_wildcard, unit_test, unit_test_pred | 663 |
metric_map = {
'bleu': bleu,
'edit_distance': edit_distance,
'exact_match': exact_match,
'kv_match': kv_match,
}
def import_module_from_string(module_name, module_code):
module_spec = importlib.util.spec_from_loader(module_name, loader=None)
module = importlib.util.module_from_spec(module_spec... |
metric_map = {
'bleu': bleu,
'edit_distance': edit_distance,
'exact_match': exact_match,
'kv_match': kv_match,
}
def import_module_from_string(module_name, module_code):
module_spec = importlib.util.spec_from_loader(module_name, loader=None)
module = importlib.util.module_from_spec(module_spec... | score = kv_wildcard.test(generated_code, reference_code) | 4 | 2023-11-08 08:13:39+00:00 | 2k |
KAIST-AILab/palr | rlkit/torch/sac/sac.py | [
{
"identifier": "LossFunction",
"path": "rlkit/core/loss.py",
"snippet": "class LossFunction(object, metaclass=abc.ABCMeta):\n def compute_loss(self, batch, skip_statistics=False, **kwargs):"
},
{
"identifier": "create_stats_ordered_dict",
"path": "rlkit/core/eval_util.py",
"snippet":... | from collections import OrderedDict, namedtuple
from typing import Tuple
from rlkit.core.loss import LossFunction, LossStatistics
from torch import nn as nn
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.torch.torch_rl_algorithm import TorchTrainer
from rlkit.core.logging import add_prefix
from m... | 1,192 |
SACLosses = namedtuple(
'SACLosses',
'policy_loss qf1_loss qf2_loss alpha_loss',
)
|
SACLosses = namedtuple(
'SACLosses',
'policy_loss qf1_loss qf2_loss alpha_loss',
)
| class SACTrainer(TorchTrainer, LossFunction): | 0 | 2023-11-06 08:35:34+00:00 | 2k |
JustlfC03/SCUNet-plusplus | trainer.py | [
{
"identifier": "DiceLoss",
"path": "utils.py",
"snippet": "class DiceLoss(nn.Module):\n def __init__(self, n_classes):\n super(DiceLoss, self).__init__()\n self.n_classes = n_classes\n\n def _one_hot_encoder(self, input_tensor):\n tensor_list = []\n for i in range(self... | import argparse
import logging
import os
import random
import sys
import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from tensorboardX import SummaryWriter
from torch.nn.modules.loss import CrossEntropyLoss
from torch.utils.data import DataLoader
from tqdm import tqdm
from uti... | 1,250 |
def trainer_synapse(args, model, snapshot_path):
logging.basicConfig(filename=snapshot_path + "/log.txt", level=logging.INFO,
format='[%(asctime)s.%(msecs)03d] %(message)s', datefmt='%H:%M:%S')
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
logging.info(str(args)... |
def trainer_synapse(args, model, snapshot_path):
logging.basicConfig(filename=snapshot_path + "/log.txt", level=logging.INFO,
format='[%(asctime)s.%(msecs)03d] %(message)s', datefmt='%H:%M:%S')
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
logging.info(str(args)... | dice_loss = DiceLoss(num_classes) | 0 | 2023-11-04 11:42:02+00:00 | 2k |
corcel-api/cortex.t | validators/image_validator.py | [
{
"identifier": "get_question",
"path": "template/utils.py",
"snippet": "async def get_question(category, num_questions_needed):\n if category not in [\"text\", \"images\"]:\n raise ValueError(\"Invalid category. Must be 'text' or 'images'.\")\n\n question = await update_counters_and_get_ne... | import io
import torch
import wandb
import random
import asyncio
import aiohttp
import base64
import traceback
import template.reward
import bittensor as bt
from PIL import Image
from io import BytesIO
from template.utils import get_question
from base_validator import BaseValidator
from template.protocol import ImageRe... | 1,332 |
class ImageValidator(BaseValidator):
def __init__(self, dendrite, config, subtensor, wallet):
super().__init__(dendrite, config, subtensor, wallet, timeout=25)
self.streaming = False
self.query_type = "images"
self.model = "dall-e-2"
self.weight = .5
self.provider ... |
class ImageValidator(BaseValidator):
def __init__(self, dendrite, config, subtensor, wallet):
super().__init__(dendrite, config, subtensor, wallet, timeout=25)
self.streaming = False
self.query_type = "images"
self.model = "dall-e-2"
self.weight = .5
self.provider ... | syn = ImageResponse(messages=messages, model=self.model, size=self.size, quality=self.quality, style=self.style, provider=self.provider, seed=self.seed, steps=self.steps) | 1 | 2023-11-06 10:35:34+00:00 | 2k |
flatypus/flowchat | flowchat/chain.py | [
{
"identifier": "autodedent",
"path": "flowchat/autodedent.py",
"snippet": "def autodedent(*text_lines) -> str:\n \"\"\"Format multiline strings, including with multiple levels of indentation, to align with the first line.\n\n Example:\n\n code = '''\n def add(a, b):\n return a + b\n ... | from .autodedent import autodedent
from .private._private_helpers import _encode_image
from retry import retry
from typing import List, TypedDict, Union, Callable, Dict, Literal, Any
from wrapt_timeout_decorator import timeout
import json
import openai
import os
import logging | 1,205 |
logging.basicConfig(level=logging.WARNING,
format='[%(asctime)s] %(levelname)s: %(message)s')
Message = TypedDict('Message', {'role': str, 'content': str | List[Any]})
ResponseFormat = TypedDict(
'ResponseFormat', {'type': Literal['text', 'json_object']})
ImageFormat = TypedDict('ImageFormat', ... |
logging.basicConfig(level=logging.WARNING,
format='[%(asctime)s] %(levelname)s: %(message)s')
Message = TypedDict('Message', {'role': str, 'content': str | List[Any]})
ResponseFormat = TypedDict(
'ResponseFormat', {'type': Literal['text', 'json_object']})
ImageFormat = TypedDict('ImageFormat', ... | return {"url": _encode_image(image, "PNG")} | 1 | 2023-11-08 00:45:21+00:00 | 2k |
WHU-USI3DV/PatchAugNet | place_recognition/Minkloc3D_V2/misc/utils.py | [
{
"identifier": "PolarQuantizer",
"path": "place_recognition/Minkloc3D_V2/misc/quantization.py",
"snippet": "class PolarQuantizer(Quantizer):\n def __init__(self, quant_step: List[float]):\n assert len(quant_step) == 3, '3 quantization steps expected: for sector (in degrees), ring and z-coordi... | import os
import configparser
import time
import numpy as np
from place_recognition.Minkloc3D_V2.misc.quantization import PolarQuantizer, CartesianQuantizer | 838 | # Warsaw University of Technology
class ModelParams:
def __init__(self, model_params_path):
config = configparser.ConfigParser()
config.read(model_params_path)
params = config['MODEL']
self.model_params_path = model_params_path
self.model = params.get('model')
se... | # Warsaw University of Technology
class ModelParams:
def __init__(self, model_params_path):
config = configparser.ConfigParser()
config.read(model_params_path)
params = config['MODEL']
self.model_params_path = model_params_path
self.model = params.get('model')
se... | self.quantizer = PolarQuantizer(quant_step=self.quantization_step) | 0 | 2023-11-02 13:52:20+00:00 | 2k |
WeiLab-Biology/DeepProSite | DeepProSite-main/edge_features.py | [
{
"identifier": "gather_edges",
"path": "self_attention.py",
"snippet": "def gather_edges(edges, neighbor_idx):\n # Features [B,N,N,C] at Neighbor indices [B,N,K] => Neighbor features [B,N,K,C]\n neighbors = neighbor_idx.unsqueeze(-1).expand(-1, -1, -1, edges.size(-1))\n edge_features = torch.g... | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from self_attention import gather_edges, gather_nodes, Normalize | 850 |
class PositionalEncodings(nn.Module):
def __init__(self, num_embeddings):
super(PositionalEncodings, self).__init__()
self.num_embeddings = num_embeddings
def forward(self, E_idx):
# i-j
N_batch = E_idx.size(0)
N_nodes = E_idx.size(1)
N_neighbors = E_idx.size(... |
class PositionalEncodings(nn.Module):
def __init__(self, num_embeddings):
super(PositionalEncodings, self).__init__()
self.num_embeddings = num_embeddings
def forward(self, E_idx):
# i-j
N_batch = E_idx.size(0)
N_nodes = E_idx.size(1)
N_neighbors = E_idx.size(... | self.norm_edges = Normalize(edge_features) | 2 | 2023-11-04 15:32:31+00:00 | 2k |
gchada/ROAM | real/rail_real_walker/robots/go1_remote.py | [
{
"identifier": "Go1RemoteActionMsg",
"path": "real/rail_real_walker/robots/go1_remote_runner.py",
"snippet": "class Go1RemoteActionMsg:\n target_action : np.ndarray"
},
{
"identifier": "Go1RemoteObservation",
"path": "real/rail_real_walker/robots/go1_remote_runner.py",
"snippet": "cl... | from .go1_remote_runner import Go1RemoteActionMsg, Go1RemoteObservation, Go1RemoteConfigMsg, empty_obs, DataPack, REAL_CONTROL_TIMESTEP
from typing import Optional
from rail_walker_interface import BaseWalker, BaseWalkerWithFootContact, BaseWalkerWithJoystick, BaseWalkerWithJointTemperatureSensor, Walker3DVelocityEstim... | 1,273 |
class Go1RealWalkerRemote(BaseWalker[Go1RemoteObservation], BaseWalkerWithFootContact, BaseWalkerWithJoystick, BaseWalkerWithJointTemperatureSensor):
def __init__(
self,
velocity_estimator: Walker3DVelocityEstimator,
power_protect_factor : float = 0.5,
foot_contact_threshold: np.nd... |
class Go1RealWalkerRemote(BaseWalker[Go1RemoteObservation], BaseWalkerWithFootContact, BaseWalkerWithJoystick, BaseWalkerWithJointTemperatureSensor):
def __init__(
self,
velocity_estimator: Walker3DVelocityEstimator,
power_protect_factor : float = 0.5,
foot_contact_threshold: np.nd... | self.data_pack = DataPack(self.deal_with_data) | 4 | 2023-11-02 23:21:38+00:00 | 2k |
NUCCASJNR/PaystackPyAPI | paystackpyAPI/transaction.py | [
{
"identifier": "PaystackAPI",
"path": "paystackpyAPI/base.py",
"snippet": "class PaystackAPI:\n \n def __init__(self, api_key: str) -> None:\n self.api_key = api_key"
},
{
"identifier": "APIError",
"path": "errors.py",
"snippet": "class APIError(PaystackError):\n \"\"\"E... | import requests
import datetime
import webbrowser
from .base import PaystackAPI
from typing import Dict, Union
from errors import APIError
from decimal import Decimal | 681 | #!/usr/bin/env python3
"""Handles All Paystack related tasks"""
class Transaction(PaystackAPI):
INITIALIZATION_OPTIONAL_PARAMS = [
"currency",
"reference",
"callback_url",
"plan",
"invoice_limit",
"metadata",
"channels",
"split_code",
"subacc... | #!/usr/bin/env python3
"""Handles All Paystack related tasks"""
class Transaction(PaystackAPI):
INITIALIZATION_OPTIONAL_PARAMS = [
"currency",
"reference",
"callback_url",
"plan",
"invoice_limit",
"metadata",
"channels",
"split_code",
"subacc... | raise APIError(400, "Missing required parameters: email and/or amount") | 1 | 2023-11-07 18:00:39+00:00 | 2k |
Dataherald/Assistant | assistant.py | [
{
"identifier": "Function",
"path": "function.py",
"snippet": "class Function(BaseModel, ABC):\n name: str\n description: Optional[str] = None\n parameters: Optional[List[Property]] = None\n\n def to_dict(self):\n if self.parameters is None:\n return {\n \"na... | from openai import OpenAI
from openai import Client
from function import Function, FunctionCall
from openai.types.beta import Thread, Assistant
from openai.types.beta.threads import Run, ThreadMessage
from yaspin import yaspin
import json
import random
import time | 1,288 |
PRINT_COLORS = [
'\033[31m',
'\033[32m',
'\033[33m',
'\033[34m',
'\033[35m',
'\033[36m',
]
class Message:
thread_id: str
role: str
content: str
file_ids: list[str]
def __init__(
self, thread_id: str, role: str, content: str, file_ids: list[str] = None
):
... |
PRINT_COLORS = [
'\033[31m',
'\033[32m',
'\033[33m',
'\033[34m',
'\033[35m',
'\033[36m',
]
class Message:
thread_id: str
role: str
content: str
file_ids: list[str]
def __init__(
self, thread_id: str, role: str, content: str, file_ids: list[str] = None
):
... | function_call = FunctionCall( | 1 | 2023-11-09 01:58:07+00:00 | 2k |
Skytliang/SpyGame | utils/agent.py | [
{
"identifier": "OutOfQuotaException",
"path": "utils/openai_utils.py",
"snippet": "class OutOfQuotaException(Exception):\n \"Raised when the key exceeded the current quota\"\n def __init__(self, key, cause=None):\n super().__init__(f\"No quota for key: {key}\")\n self.key = key\n ... | import os
import openai
import backoff
import time
import random
import json
import copy
import numpy as np
from datetime import datetime
from openai.error import RateLimitError, APIError, ServiceUnavailableError, APIConnectionError, AuthenticationError
from utils.openai_utils import OutOfQuotaException, AccessTerminat... | 1,371 |
# from bardapi import Bard
# import requests
# import torch
# from transformers import AutoTokenizer, AutoModelForCausalLM
# from FastChat.fastchat.model.model_adapter import load_model, get_conversation_template, add_model_args
cycle_all_keys = True
current_path = os.path.abspath(__file__).rsplit('/', 1)[0]
gpt3... |
# from bardapi import Bard
# import requests
# import torch
# from transformers import AutoTokenizer, AutoModelForCausalLM
# from FastChat.fastchat.model.model_adapter import load_model, get_conversation_template, add_model_args
cycle_all_keys = True
current_path = os.path.abspath(__file__).rsplit('/', 1)[0]
gpt3... | raise AccessTerminatedException(api_key) | 1 | 2023-11-01 03:42:10+00:00 | 2k |
SpectacularAI/point-cloud-tools | formats/auto.py | [
{
"identifier": "load_ply_to_dataframe",
"path": "formats/ply.py",
"snippet": "def load_ply_to_dataframe(ply_file):\n with open(ply_file, 'rb') as f:\n return load_ply_stream_to_dataframe(f)\n load_ply_to_dataframe"
},
{
"identifier": "dataframe_to_ply",
"path": "formats/ply.py"... | import pandas as pd
from .ply import load_ply_to_dataframe, dataframe_to_ply
from .splat import splat_file_to_data_frame, dataframe_to_splat_file
from .pcd import dataframe_to_pcd
from .html import dataframe_to_gsplat_html | 673 |
def load_to_dataframe(fn):
ext = fn.split('.')[-1]
if ext == 'ply':
return load_ply_to_dataframe(fn)
elif ext == 'csv':
return pd.read_csv(fn)
elif ext == 'txt':
# assuming COLMAP CSV format
return pd.read_csv(fn, sep=' ', header=None, usecols=list(range(7)), names... |
def load_to_dataframe(fn):
ext = fn.split('.')[-1]
if ext == 'ply':
return load_ply_to_dataframe(fn)
elif ext == 'csv':
return pd.read_csv(fn)
elif ext == 'txt':
# assuming COLMAP CSV format
return pd.read_csv(fn, sep=' ', header=None, usecols=list(range(7)), names... | dataframe_to_ply(df, fn) | 1 | 2023-11-02 14:16:49+00:00 | 2k |
jdelahayes/ha-voltalis | custom_components/voltalis/climate.py | [
{
"identifier": "DEFAULT_MAX_TEMP",
"path": "custom_components/voltalis/const.py",
"snippet": "DEFAULT_MAX_TEMP = 24"
},
{
"identifier": "DEFAULT_MIN_TEMP",
"path": "custom_components/voltalis/const.py",
"snippet": "DEFAULT_MIN_TEMP = 7"
},
{
"identifier": "DOMAIN",
"path": "... | import logging
from typing import Any
from homeassistant.components.climate import (
ClimateEntity,
ClimateEntityFeature,
HVACAction,
HVACMode,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature
from homeassistant.core import HomeAs... | 670 | """Platform for climate integration."""
from __future__ import annotations
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up climate entity for Voltalis Appliance."""
| """Platform for climate integration."""
from __future__ import annotations
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up climate entity for Voltalis Appliance.""" | controller = hass.data[DOMAIN][entry.entry_id][VOLTALIS_CONTROLLER] | 4 | 2023-11-01 09:05:17+00:00 | 2k |
r-three/licensed-pile | ubuntu/to-dolma.py | [
{
"identifier": "PermissiveLicenses",
"path": "licensed_pile/licenses.py",
"snippet": "class PermissiveLicenses(StringEnum):\n PD = \"Public Domain\"\n CC0 = \"Creative Commons Zero - Public Domain - https://creativecommons.org/publicdomain/zero/1.0/\"\n CC_BY = (\n \"Creative Commons - ... | import argparse
import datetime
import glob
import os
import urllib.parse
from charset_normalizer import from_bytes
from licensed_pile.licenses import PermissiveLicenses
from licensed_pile.write import to_dolma | 1,425 | """Convert the raw ubuntu data to the dolma format."""
SOURCE_NAME = "ubuntu-chat"
BASE_URL = "https://irclogs.ubuntu.com"
parser = argparse.ArgumentParser(description="Convert data to dolma.")
parser.add_argument(
"--data",
default="data/irclogs.ubuntu.com/",
help="Path to the directory containing ubu... | """Convert the raw ubuntu data to the dolma format."""
SOURCE_NAME = "ubuntu-chat"
BASE_URL = "https://irclogs.ubuntu.com"
parser = argparse.ArgumentParser(description="Convert data to dolma.")
parser.add_argument(
"--data",
default="data/irclogs.ubuntu.com/",
help="Path to the directory containing ubu... | to_dolma(chats, args.output_dir, args.filename, args.shard_size) | 1 | 2023-11-06 16:04:10+00:00 | 2k |
UMass-Foundation-Model/genome | engine/util.py | [
{
"identifier": "Wizardlm",
"path": "engine/llm.py",
"snippet": "class Wizardlm():\n @classmethod\n def init(cls, base_model=\"WizardLM/WizardCoder-Python-34B-V1.0\", n_gpus=4, max_input_tokens=16384):\n cls.llm = LLM(model=base_model, tensor_parallel_size=n_gpus, max_num_batched_tokens=max... | import os
import json
import openai
import pdb
from engine.llm import Wizardlm
from engine.llm import Codellama
from engine.datasets import get_dataset | 1,203 |
def strip_dict(dict):
for k, v in dict.items():
if isinstance(v, str):
dict[k] = v.strip()
return dict
def get_module_list(args):
if not args.use_new_module:
return []
module_save_dir = args.module_save_dir
if os.path.isdir(module_save_dir):
file_list = os.list... |
def strip_dict(dict):
for k, v in dict.items():
if isinstance(v, str):
dict[k] = v.strip()
return dict
def get_module_list(args):
if not args.use_new_module:
return []
module_save_dir = args.module_save_dir
if os.path.isdir(module_save_dir):
file_list = os.list... | Wizardlm.init() | 0 | 2023-11-01 16:39:33+00:00 | 2k |
ml4bio/RhoFold | rhofold/model/primitives.py | [
{
"identifier": "permute_final_dims",
"path": "rhofold/utils/tensor_utils.py",
"snippet": "def permute_final_dims(tensor: torch.Tensor, inds: List[int]):\n zero_index = -1 * len(inds)\n first_inds = list(range(len(tensor.shape[:zero_index])))\n return tensor.permute(first_inds + [zero_index + i... | import math
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import numpy as np
from typing import Optional, List, Tuple
from rhofold.utils.tensor_utils import (
permute_final_dims,
flatten_final_dims,
) | 757 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | key = permute_final_dims(key, (1, 0)) | 0 | 2023-11-01 10:29:08+00:00 | 2k |
ziqi-zhang/TAOISM | python/layers/flatten.py | [
{
"identifier": "SecretNonlinearLayer",
"path": "python/layers/nonlinear.py",
"snippet": "class SecretNonlinearLayer(SecretLayerBase):\n def __init__(\n self, sid, LayerName, EnclaveMode, link_prev=True, link_next=True,\n manually_register_prev=False, manually_register_next=False\n )... | from python.layers.nonlinear import SecretNonlinearLayer
from python.utils.timer_utils import NamedTimerInstance, VerboseLevel
from python.utils.torch_utils import compare_expected_actual
from python.utils.basic_utils import ExecutionModeOptions | 1,305 |
# Assume the prev. layer is of 4d. It outputs a 2d mat
# This layer doesnt pull the input in enclave if it is not so reduce duplicated action
class SecretFlattenLayer(SecretNonlinearLayer):
batch_size = None
n_features = None
input_shape = None
output_shape = None
def __init__(
self, sid,... |
# Assume the prev. layer is of 4d. It outputs a 2d mat
# This layer doesnt pull the input in enclave if it is not so reduce duplicated action
class SecretFlattenLayer(SecretNonlinearLayer):
batch_size = None
n_features = None
input_shape = None
output_shape = None
def __init__(
self, sid,... | if self.EnclaveMode == ExecutionModeOptions.Enclave: | 4 | 2023-11-01 10:37:37+00:00 | 2k |
rafaelleinio/biar | biar/model.py | [
{
"identifier": "ContentCallbackError",
"path": "biar/errors.py",
"snippet": "class ContentCallbackError(Exception):\n \"\"\"Base Exception for content callback errors.\"\"\""
},
{
"identifier": "ResponseEvaluationError",
"path": "biar/errors.py",
"snippet": "class ResponseEvaluationE... | import asyncio
import aiohttp
import tenacity
from functools import cached_property
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Type
from aiohttp import ClientResponseError
from loguru import logger
from pydantic import BaseModel, ConfigDict, Field, JsonValue, computed_field
from pyrate_limi... | 724 |
class ProxyConfig(BaseModel):
"""Proxy configuration.
Attributes:
host: proxy address.
headers: additional configuration required by the proxy.
ssl_cadata: certificate as a string required by some proxies to use SSL.
"""
host: str
headers: Optional[Dict[str, Any]] = No... |
class ProxyConfig(BaseModel):
"""Proxy configuration.
Attributes:
host: proxy address.
headers: additional configuration required by the proxy.
ssl_cadata: certificate as a string required by some proxies to use SSL.
"""
host: str
headers: Optional[Dict[str, Any]] = No... | exception_types=self.retry_if_exception_in + (ResponseEvaluationError,) | 1 | 2023-11-03 00:03:59+00:00 | 2k |
NVlabs/M2T2 | m2t2/action_decoder.py | [
{
"identifier": "MLP",
"path": "m2t2/model_utils.py",
"snippet": "class MLP(nn.Module):\n def __init__(\n self, input_dim, hidden_dim, output_dim, num_layers,\n activation=\"ReLU\", dropout=0.\n ):\n super().__init__()\n h = [hidden_dim] * (num_layers - 1)\n laye... | import numpy as np
import torch
import torch.nn.functional as F
import trimesh.transformations as tra
from m2t2.model_utils import MLP, repeat_new_axis | 1,520 | # distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# Author: Wentao Yuan
"""
Modules to compute gripper poses from contact masks and parameters.
"""
def double_split(tensor, chunks):
tensor = list(tensor.split([sum(ch... | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and relat... | self.contact_dir_head = MLP( | 0 | 2023-11-03 22:32:05+00:00 | 2k |
Codra-Ingenierie-Informatique/DataLab | cdl/tests/features/common/newobject_unit.py | [
{
"identifier": "execenv",
"path": "cdl/env.py",
"snippet": "DEBUG = os.environ.get(\"DEBUG\", \"\").lower() in (\"1\", \"true\")\n QUIET = \"quiet\"\n NORMAL = \"normal\"\n DEBUG = \"debug\"\n UNATTENDED_ARG = \"unattended\"\n VERBOSE_ARG = \"verbose\"\n SCREENSHOT_ARG = \"screenshot\... | from collections.abc import Generator
from guidata.qthelpers import qt_app_context
from cdl.env import execenv
from cdl.obj import (
Gauss2DParam,
ImageDatatypes,
ImageObj,
ImageTypes,
NormalRandomParam,
SignalObj,
SignalTypes,
UniformRandomParam,
create_image_from_param,
create_... | 1,082 | # -*- coding: utf-8 -*-
#
# Licensed under the terms of the BSD 3-Clause
# (see cdl/LICENSE for details)
"""
New signal/image test
Testing functions related to signal/image creation.
"""
# pylint: disable=invalid-name # Allows short reference names like x, y, ...
# pylint: disable=duplicate-code
# guitest: show
fr... | # -*- coding: utf-8 -*-
#
# Licensed under the terms of the BSD 3-Clause
# (see cdl/LICENSE for details)
"""
New signal/image test
Testing functions related to signal/image creation.
"""
# pylint: disable=invalid-name # Allows short reference names like x, y, ...
# pylint: disable=duplicate-code
# guitest: show
fr... | execenv.print( | 0 | 2023-11-09 16:56:03+00:00 | 2k |
sxwyh/pytradecn | src/pytradecn/control/wrappersa.py | [
{
"identifier": "BaseUIAWrapper",
"path": "src/pytradecn/control/baseuiawrapper.py",
"snippet": "class BaseUIAWrapper(UIAWrapper):\n\n _control_types = ['BaseUIA']\n\n def __init__(self, element_info):\n super(BaseUIAWrapper, self).__init__(element_info)\n self._client = get_client(p... | from os import remove
from csv import DictReader
from decimal import Decimal
from tempfile import NamedTemporaryFile
from os.path import exists
from .baseuiawrapper import BaseUIAWrapper
from ..error import RecordNotFoundError, RecordAmbiguousError, ItemKeyError, TimeoutError | 1,392 | #
# 券商客户端自动化测试库
# Copyright (C) 2023 谁的谁(41715399@qq.com) All rights reserved.
#
# 模块功能:各种自定义控件
# 建立日期:2023.07.20
# 联系方式:谁的谁(41715399@qq.com)
#
# 开源软件声明:
# 本软件遵守“MIT License”开源协议开源,仅供学习和参考。您可以自由使用或修改源代码或二进制文件,但必须保留上述版权声明。
# 该软件旨在深度学习和挖掘python pywinauto库的功能和潜力,由于环境的不确定性和该软件的不可靠性,请不要将该软件应用于
# 实盘交易。如您确需量化交易实盘功能,请使用券商提供的量化... | #
# 券商客户端自动化测试库
# Copyright (C) 2023 谁的谁(41715399@qq.com) All rights reserved.
#
# 模块功能:各种自定义控件
# 建立日期:2023.07.20
# 联系方式:谁的谁(41715399@qq.com)
#
# 开源软件声明:
# 本软件遵守“MIT License”开源协议开源,仅供学习和参考。您可以自由使用或修改源代码或二进制文件,但必须保留上述版权声明。
# 该软件旨在深度学习和挖掘python pywinauto库的功能和潜力,由于环境的不确定性和该软件的不可靠性,请不要将该软件应用于
# 实盘交易。如您确需量化交易实盘功能,请使用券商提供的量化... | except TimeoutError: | 1 | 2023-11-03 02:22:34+00:00 | 2k |
ingra14m/Tensor4D-DNeRF | models/fields.py | [
{
"identifier": "get_embedder",
"path": "models/embedder.py",
"snippet": "def get_embedder(multires, input_dims=3):\n embed_kwargs = {\n 'include_input': True,\n 'input_dims': input_dims,\n 'max_freq_log2': multires-1,\n 'num_freqs': multires,\n 'log_sampling': True... | from configparser import NoOptionError
from models.embedder import get_embedder
from models.mip_utils import integrated_pos_enc
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np | 978 |
class FieldNetwork(nn.Module):
def __init__(self,
d_in,
d_out,
d_hidden,
d_t4d,
min_emb,
max_emb,
n_layers,
t_emb=-1,
skip_in=(4,),
bias=0.5,
... |
class FieldNetwork(nn.Module):
def __init__(self,
d_in,
d_out,
d_hidden,
d_t4d,
min_emb,
max_emb,
n_layers,
t_emb=-1,
skip_in=(4,),
bias=0.5,
... | embed_fn, time_input_ch = get_embedder(t_emb, input_dims=1) | 0 | 2023-11-07 10:16:33+00:00 | 2k |
865charlesw/homeassistant-kidde | custom_components/kidde/binary_sensor.py | [
{
"identifier": "DOMAIN",
"path": "custom_components/kidde/const.py",
"snippet": "DOMAIN = \"kidde\""
},
{
"identifier": "KiddeCoordinator",
"path": "custom_components/kidde/coordinator.py",
"snippet": "class KiddeCoordinator(DataUpdateCoordinator):\n \"\"\"Coordinator for Kidde HomeS... | from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.components.binary_sensor import BinarySensorEntityDescription
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
f... | 825 | """Binary sensor platform for Kidde Homesafe integration."""
from __future__ import annotations
_BINARY_SENSOR_DESCRIPTIONS = (
BinarySensorEntityDescription(
"smoke_alarm", icon="mdi:smoke-detector-variant-alert", name="Smoke Alarm"
),
BinarySensorEntityDescription(
"smoke_hushed", icon... | """Binary sensor platform for Kidde Homesafe integration."""
from __future__ import annotations
_BINARY_SENSOR_DESCRIPTIONS = (
BinarySensorEntityDescription(
"smoke_alarm", icon="mdi:smoke-detector-variant-alert", name="Smoke Alarm"
),
BinarySensorEntityDescription(
"smoke_hushed", icon... | coordinator: KiddeCoordinator = hass.data[DOMAIN][entry.entry_id] | 0 | 2023-11-09 23:25:02+00:00 | 2k |
humemarx/CPG-LCF | models/backbone2d/resnet.py | [
{
"identifier": "constant_init",
"path": "models/utils/weight_init.py",
"snippet": "def constant_init(module, val, bias=0):\n if hasattr(module, 'weight') and module.weight is not None:\n nn.init.constant_(module.weight, val)\n if hasattr(module, 'bias') and module.bias is not None:\n ... | import warnings
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from collections import OrderedDict
from torch.nn.modules.batchnorm import _BatchNorm
from torch.nn.modules.instancenorm import _InstanceNorm
from torch.nn.modules.conv import _ConvNd
from models.utils.weight_init import (constant_in... | 1,521 |
downsample = None
if stride != 1 or inplanes != planes * block.expansion:
downsample = []
conv_stride = stride
if avg_down:
conv_stride = 1
downsample.append(
nn.AvgPool2d(
kernel_size=stride... | # coding=utf-8
'''
Author: husserl
License: Apache Licence
Software: VSCode
Date: 2023-07-17 06:36:26
LastEditors: husserl
LastEditTime: 2023-11-02 15:36:30
'''
def get_norm_name(norm_type, postfix=1):
if issubclass(norm_type, _InstanceNorm): # IN is a subclass of BN
return 'in{}'.format(postfix)
el... | constant_init(m, val=1.0, bias=0.) | 0 | 2023-11-02 09:50:13+00:00 | 2k |
intelheropuck/steam.com-scraping | listingcollector.py | [
{
"identifier": "parse_price",
"path": "helpers.py",
"snippet": "def parse_price(string):\n return int(string[1:].replace(\",\", \"\").split('.')[0])"
},
{
"identifier": "Database",
"path": "helpers.py",
"snippet": "class Database:\n _instance = None\n\n @classmethod\n def ge... | import json
import threading
import time
import argparse
import requests
import requests
import re
from queue import Queue
from urllib.parse import unquote
from helpers import parse_price
from helpers import Database, Listing
from urllib import parse
from bs4 import BeautifulSoup | 1,282 |
ACTIVITY_URL = "https://steamcommunity.com/market/itemordersactivity"\
"?item_nameid={item_id}&country=RU&language=english¤cy=1&&two_factor=0&norender=1"
db = Database().get_instance()
def get_activities(item_id):
return requests.get(ACTIVITY_URL.format(item_id=item_id)).json()["activity"... |
ACTIVITY_URL = "https://steamcommunity.com/market/itemordersactivity"\
"?item_nameid={item_id}&country=RU&language=english¤cy=1&&two_factor=0&norender=1"
db = Database().get_instance()
def get_activities(item_id):
return requests.get(ACTIVITY_URL.format(item_id=item_id)).json()["activity"... | listing = Listing( | 2 | 2023-11-05 04:47:16+00:00 | 2k |
JaeBinCHA7/DEMUCS-for-Speech-Enhancement | models/HDDEMUCS_TF.py | [
{
"identifier": "capture_init",
"path": "models/tools.py",
"snippet": "def capture_init(init):\n \"\"\"capture_init.\n Decorate `__init__` with this, and you can then\n recover the *args and **kwargs passed to it in `self._init_args_kwargs`\n \"\"\"\n @functools.wraps(init)\n def __ini... | import math
import torch
import torch as th
import typing as tp
from torch import nn
from torch.nn import functional as F
from einops import rearrange
from .tools import capture_init, spectro, ispectro | 1,343 | """
Reference: https://github.com/facebookresearch/denoiser/blob/main/denoiser/demucs.py
Copyright (c) Facebook, Inc. and its 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.
author: adefossez
"""
class BLSTM(nn.Mod... | """
Reference: https://github.com/facebookresearch/denoiser/blob/main/denoiser/demucs.py
Copyright (c) Facebook, Inc. and its 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.
author: adefossez
"""
class BLSTM(nn.Mod... | @capture_init | 0 | 2023-11-06 08:16:24+00:00 | 2k |
pauloxnet/generatedfields | samples/tests.py | [
{
"identifier": "Circle",
"path": "samples/models.py",
"snippet": "class Circle(models.Model):\n radius = models.FloatField()\n area = models.GeneratedField(\n expression=Round(\n Power(\"radius\", 2) * Pi(),\n precision=2,\n ),\n output_field=models.Floa... | from django.test import TestCase
from samples.models import (
Circle,
Event,
Item,
Order,
Package,
Rectangle,
RightTriangle,
Square,
User,
) | 1,227 |
class RectangleTestCase(TestCase):
@classmethod
def setUpTestData(cls):
cls.rectangle = Rectangle.objects.create(base=6, height=7)
def test_str(self):
self.assertEqual(str(self.rectangle), "6×7=42.0")
class SquareTestCase(TestCase):
@classmethod
def setUpTestData(cls):
... |
class RectangleTestCase(TestCase):
@classmethod
def setUpTestData(cls):
cls.rectangle = Rectangle.objects.create(base=6, height=7)
def test_str(self):
self.assertEqual(str(self.rectangle), "6×7=42.0")
class SquareTestCase(TestCase):
@classmethod
def setUpTestData(cls):
... | cls.righttriangle = RightTriangle.objects.create(hypotenuse=5, angle=45) | 6 | 2023-11-07 17:06:11+00:00 | 2k |
akhilravidas/stack-sparrow | sparrow/assistant/run.py | [
{
"identifier": "actions",
"path": "sparrow/assistant/actions.py",
"snippet": "class FileReviewComments(BaseModel):\nclass FileReviewResult(BaseModel):\n def new(cls, json_input: str) -> FileReviewResult:"
},
{
"identifier": "BaseReview",
"path": "sparrow/assistant/review.py",
"snippe... | import json
import logging
import os
import time
import pydantic
from functools import lru_cache
from typing import List, Optional, Tuple
from openai import OpenAI
from openai.types.beta.threads import Run
from rich import print # pylint: disable=redefined-builtin
from rich.progress import Progress, SpinnerColumn, Tex... | 1,248 | """
OpenAI assistant
"""
ASSISTANT_INSTRUCTIONS = """
You an an assistant that helps with DevOps tasks. You review code, help with adding documentation etc..
""".strip()
REVIEW_THREAD_INSTRUCTIONS = """
Each message in this thread represents changes made to a file in the patch set.
The first line is the file path. ... | """
OpenAI assistant
"""
ASSISTANT_INSTRUCTIONS = """
You an an assistant that helps with DevOps tasks. You review code, help with adding documentation etc..
""".strip()
REVIEW_THREAD_INSTRUCTIONS = """
Each message in this thread represents changes made to a file in the patch set.
The first line is the file path. ... | return OpenAI(api_key=config.AppConfig.instance().openai_token) | 4 | 2023-11-07 00:55:26+00:00 | 2k |
nimamahmoudi/LLMStreamlitDemoBasic | app-agent.py | [
{
"identifier": "get_agent_chain",
"path": "llm_helper.py",
"snippet": "def get_agent_chain(file_name=\"Mahmoudi_Nima_202202_PhD.pdf\", index_folder=\"index\", callbacks=None, st_cb: Optional[StreamlitCallbackHandler] = None, ):\n if callbacks is None:\n callbacks = []\n\n from langchain.ag... | import streamlit as st
from langchain.agents import initialize_agent, AgentType
from langchain.callbacks import StreamlitCallbackHandler
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from llm_helper import get_agent_chain, get_lc_oai_tools | 1,017 |
with st.sidebar:
openai_api_key = st.secrets["OPENAI_API_KEY"]
"[Get an OpenAI API key](https://platform.openai.com/account/api-keys)"
"[View the source code](https://github.com/streamlit/llm-examples/blob/main/pages/2_Chat_with_search.py)"
"["
"[View the source code](https://github.com/streamlit/llm-examples/blob/main/pages/2_Chat_with_search.py)"
"[ | 1 | 2023-11-05 13:19:04+00:00 | 2k |
JakubPluta/gymhero | gymhero/api/routes/user.py | [
{
"identifier": "get_current_superuser",
"path": "gymhero/api/dependencies.py",
"snippet": "def get_current_superuser(\n current_user: User = Depends(get_current_user),\n) -> User:\n \"\"\"Returns the current superuser.\n\n Parameters:\n current_user (User, optional): The current user.\n... | from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from gymhero.api.dependencies import get_current_superuser, get_pagination_params
from gymhero.crud import user_crud
from gymhero.database.db import get_db
from gymhero.log import get_logge... | 1,318 |
log = get_logger(__name__)
router = APIRouter(dependencies=[Depends(get_current_superuser)])
@router.get(
"/all", response_model=List[Optional[UserOut]], status_code=status.HTTP_200_OK
)
def fetch_all_users(
|
log = get_logger(__name__)
router = APIRouter(dependencies=[Depends(get_current_superuser)])
@router.get(
"/all", response_model=List[Optional[UserOut]], status_code=status.HTTP_200_OK
)
def fetch_all_users( | db: Session = Depends(get_db), pagination_params=Depends(get_pagination_params) | 3 | 2023-11-05 14:37:46+00:00 | 2k |
IIMunchII/restllm | src/restllm/models/chat.py | [
{
"identifier": "MetaModel",
"path": "src/restllm/models/base.py",
"snippet": "class MetaModel(BaseModel):\n id: int = Field(gt=0, examples=[1, 2, 3])\n class_name: str\n owner: int\n object: Any\n created_at: Datetime = Field(default_factory=Datetime)\n updated_at: Datetime = Field(de... | from enum import auto, UNIQUE, verify, StrEnum
from typing import Optional
from pydantic import BaseModel, Field
from .base import MetaModel
from .functions import FunctionCall
from .completion import CompletionParameters
from ..models.functions import get_function_schemas | 1,232 |
@verify(UNIQUE)
class RoleTypes(StrEnum):
USER = auto()
SYSTEM = auto()
ASSISTANT = auto()
FUNCTION = auto()
@verify(UNIQUE)
class ModelTypes(StrEnum):
GPT3_TURBO = "gpt-3.5-turbo"
GPT3_TURBO_16K = "gpt-3.5-turbo-16k"
GPT4 = "gpt-4"
GPT4_32K = "gpt-4-32k"
class ChatMessage(BaseMode... |
@verify(UNIQUE)
class RoleTypes(StrEnum):
USER = auto()
SYSTEM = auto()
ASSISTANT = auto()
FUNCTION = auto()
@verify(UNIQUE)
class ModelTypes(StrEnum):
GPT3_TURBO = "gpt-3.5-turbo"
GPT3_TURBO_16K = "gpt-3.5-turbo-16k"
GPT4 = "gpt-4"
GPT4_32K = "gpt-4-32k"
class ChatMessage(BaseMode... | function_call: Optional[FunctionCall] = Field( | 1 | 2023-11-05 19:16:00+00:00 | 2k |
rabilrbl/deepseek-api | deepseek_api/deepseek_api.py | [
{
"identifier": "API_URL",
"path": "deepseek_api/constants.py",
"snippet": "class API_URL:\n \"\"\"Deepseek API URL constants\"\"\"\n\n BASE_URL = \"https://coder.deepseek.com/api/v0\"\n LOGIN = BASE_URL + \"/users/login\"\n CLEAR_CONTEXT = BASE_URL + \"/chat/clear_context\"\n CHAT = BASE... | import requests
import aiohttp
import aiofiles
import threading
import json
import jwt
import datetime
from abc import ABC, abstractmethod
from deepseek_api.constants import API_URL, DeepseekConstants
from deepseek_api.errors import EmptyEmailOrPasswordError, NotLoggedInError | 743 |
class DeepseekBase(ABC):
"""
A base class to create DeepseekAPI instances.
"""
def __init__(
self,
email: str,
password: str,
model_class: str = "deepseek_code",
save_login: bool = False,
):
"""
Constructor method for DeepseekAPI class.
... |
class DeepseekBase(ABC):
"""
A base class to create DeepseekAPI instances.
"""
def __init__(
self,
email: str,
password: str,
model_class: str = "deepseek_code",
save_login: bool = False,
):
"""
Constructor method for DeepseekAPI class.
... | self.headers = DeepseekConstants.BASE_HEADERS | 1 | 2023-11-09 18:42:43+00:00 | 2k |
HealthSciTech/E2E-PPG | example.py | [
{
"identifier": "e2e_hrv_extraction",
"path": "e2e_ppg_pipeline.py",
"snippet": "def e2e_hrv_extraction(\n input_sig: np.ndarray,\n sampling_rate: int,\n window_length_sec: int = 60,\n peak_detection_method: str = 'kazemi'\n) -> pd.DataFrame:\n '''\n End-to-end HR and H... | import os
import warnings
from e2e_ppg_pipeline import e2e_hrv_extraction
from utils import get_data | 1,085 | # -*- coding: utf-8 -*-
warnings.filterwarnings("ignore")
# Import a sample data
file_name = "201902020222_Data.csv"
sampling_frequency = 20
input_sig = get_data(file_name=file_name)
# Set the window length for HR and HRV extraction in seconds
window_length_sec = 90
# Extract HRV parameters from the input PPG sign... | # -*- coding: utf-8 -*-
warnings.filterwarnings("ignore")
# Import a sample data
file_name = "201902020222_Data.csv"
sampling_frequency = 20
input_sig = get_data(file_name=file_name)
# Set the window length for HR and HRV extraction in seconds
window_length_sec = 90
# Extract HRV parameters from the input PPG sign... | hrv_data = e2e_hrv_extraction( | 0 | 2023-11-07 22:52:14+00:00 | 2k |
Antelcat/ida_copilot | ida_copilot/copilot.py | [
{
"identifier": "core",
"path": "ida_copilot/core.py",
"snippet": "def push_async_call_result(result):\ndef pop_async_call_result(index):\ndef preprocess_prompt(template: str) -> str:\ndef escape_agent_input(query: str, tool_name: str) -> str:\ndef get_screen_func():\ndef get_safe_new_name(new_func_name... | import asyncio
import concurrent.futures
import re
import idaapi
from typing import Any, Optional
from langchain.agents import tool, initialize_agent, AgentType
from langchain.callbacks import FileCallbackHandler
from langchain.callbacks.base import BaseCallbackManager
from langchain.callbacks.manager import CallbackMa... | 1,570 |
class Copilot:
def run(self, temperature=0.2, model='gpt-3.5-turbo-0613'):
ea = idaapi.get_screen_ea()
func_name = idaapi.get_func_name(ea)
tools = [
self.__GetAddressInfoTool(),
self.__GetDefinitionTool(),
self.__GetPseudocodeTool(),
sel... |
class Copilot:
def run(self, temperature=0.2, model='gpt-3.5-turbo-0613'):
ea = idaapi.get_screen_ea()
func_name = idaapi.get_func_name(ea)
tools = [
self.__GetAddressInfoTool(),
self.__GetDefinitionTool(),
self.__GetPseudocodeTool(),
sel... | query = core.escape_agent_input( | 0 | 2023-11-02 14:23:11+00:00 | 2k |
WSH032/fastapi-proxy-lib | tests/test_http.py | [
{
"identifier": "AppFactoryFixture",
"path": "tests/conftest.py",
"snippet": "_P = ParamSpec(\"_P\")\nclass LifeAppDataclass4Test(AppDataclass4Test):\nclass UvicornServerFixture(Protocol): # noqa: D101\n def __call__( # noqa: D102\n self, config: uvicorn.Config, contx_exit_timeout: Union[int... | import httpx
import pytest
from fastapi_proxy_lib.core.tool import default_proxy_filter
from typing_extensions import override
from .conftest import AppFactoryFixture, LifeAppDataclass4Test
from .tool import (
DEFAULT_URL,
PRIVATE_IP_URL,
WRONG_PROTO_URL,
AbstractTestProxy,
Tool4TestFixture,
che... | 1,070 | # noqa: D100
DEFAULT_TARGET_SERVER_BASE_URL = "http://www.echo.com/"
DEFAULT_PROXY_SERVER_BASE_URL = "http://www.proxy.com/"
class TestReverseHttpProxy(AbstractTestProxy):
"""For testing reverse http proxy."""
@override
@pytest.fixture()
async def tool_4_test_fixture( # pyright: ignore[reportInc... | # noqa: D100
DEFAULT_TARGET_SERVER_BASE_URL = "http://www.echo.com/"
DEFAULT_PROXY_SERVER_BASE_URL = "http://www.proxy.com/"
class TestReverseHttpProxy(AbstractTestProxy):
"""For testing reverse http proxy."""
@override
@pytest.fixture()
async def tool_4_test_fixture( # pyright: ignore[reportInc... | reverse_http_app_fct: AppFactoryFixture, | 0 | 2023-11-08 04:38:36+00:00 | 2k |
simorxb/PID-Controller-Python | main.py | [
{
"identifier": "Car",
"path": "lib.py",
"snippet": "class Car:\n\n \"\"\" This class represents a car moving in 1D, subject to a throttle force F, with mass m, \n aerodynamic drag coefficient b, F_max/F_min forces, and time step T. \n \"\"\"\n\n def __init__(self, m, b, F_max_0, F_max_m... | import numpy as np
import matplotlib.pyplot as plt
from lib import Car, PID | 1,348 |
def main():
# -------- Configuration --------
# Simulation parameters
time_step = 0.1
end_time = 25
length = round(end_time/time_step)
t = np.zeros(length)
stp = np.zeros(length)
v = np.zeros(length)
command = np.zeros(length)
# Car parameters
m = 2140
b = 0.33
... |
def main():
# -------- Configuration --------
# Simulation parameters
time_step = 0.1
end_time = 25
length = round(end_time/time_step)
t = np.zeros(length)
stp = np.zeros(length)
v = np.zeros(length)
command = np.zeros(length)
# Car parameters
m = 2140
b = 0.33
... | pid = PID(Kp, Ki, Kd, Kaw, T_C, time_step, F_max_0, 0, 30000) | 1 | 2023-11-03 19:38:34+00:00 | 2k |
aws-samples/amazon-location-geospatial-agent | geospatial_agent/agent/geospatial/planner/planner.py | [
{
"identifier": "_graph_generation_instructions",
"path": "geospatial_agent/agent/geospatial/planner/prompts.py",
"snippet": ""
},
{
"identifier": "GIS_AGENT_ROLE_INTRO",
"path": "geospatial_agent/shared/prompts.py",
"snippet": "GIS_AGENT_ROLE_INTRO = r'You are a geospatial data scienti... | import time
from langchain import PromptTemplate, LLMChain
from langchain.llms.base import LLM
from geospatial_agent.agent.geospatial.planner.prompts import _graph_generation_instructions, \
_graph_reply_example, _task_name_generation_prompt, _graph_requirement_list, \
_planning_graph_task_prompt_template
from ... | 730 |
class PlannerException(Exception):
def __init__(self, message: str):
self.message = message
super().__init__(self.message)
def gen_task_name(llm: LLM, task: str) -> str:
"""Returns a task name for creating unix folders from task description using LLM"""
task_name_gen_prompt_template: P... |
class PlannerException(Exception):
def __init__(self, message: str):
self.message = message
super().__init__(self.message)
def gen_task_name(llm: LLM, task: str) -> str:
"""Returns a task name for creating unix folders from task description using LLM"""
task_name_gen_prompt_template: P... | graph_plan_code = extract_code(graph_plan_response) | 3 | 2023-11-09 18:29:25+00:00 | 2k |
Hojagulyyev/rp2 | apps/diaries/interactors.py | [
{
"identifier": "COMMIT_MIN_LENGTH",
"path": "rp2/business_logic.py",
"snippet": "COMMIT_MIN_LENGTH = 10"
},
{
"identifier": "Diary",
"path": "apps/diaries/models.py",
"snippet": "class Diary(models.Model):\n\n account = models.ForeignKey(Account, on_delete=models.CASCADE, related_nam... | import datetime
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
from django.contrib import messages
from django.urls import reverse
from rp2.business_logic import COMMIT_MIN_LENGTH
from .models import Diary, DiaryCommit, DiaryComment
from .signals import diary_commit_crea... | 728 |
@login_required
def create_commit(request, diary_id: int):
# ===== DTO
message = request.POST.get("message", "").strip()
diary = Diary.objects.get(id=diary_id)
# ===== VALIDATION
if diary.account != request.user.account:
messages.error(request, f"others' diaries are readonly")
... |
@login_required
def create_commit(request, diary_id: int):
# ===== DTO
message = request.POST.get("message", "").strip()
diary = Diary.objects.get(id=diary_id)
# ===== VALIDATION
if diary.account != request.user.account:
messages.error(request, f"others' diaries are readonly")
... | diary_commit_created.send(sender=DiaryCommit, instance=diary_commit) | 4 | 2023-11-05 07:57:17+00:00 | 2k |
soobin419/DWT | basicsr/utils/logger.py | [
{
"identifier": "get_dist_info",
"path": "basicsr/utils/dist_util.py",
"snippet": "def get_dist_info():\n if dist.is_available():\n initialized = dist.is_initialized()\n else:\n initialized = False\n if initialized:\n rank = dist.get_rank()\n world_size = dist.get_wo... | import datetime
import logging
import time
import wandb
import torch
import torchvision
from .dist_util import get_dist_info, master_only
from torch.utils.tensorboard import SummaryWriter
from version import __version__ | 1,528 | train (dict): Contains 'total_iter' (int) for total iters.
use_tb_logger (bool): Use tensorboard logger.
start_iter (int): Start iter. Default: 1.
tb_logger (obj:`tb_logger`): Tensorboard logger. Default: None.
"""
def __init__(self, opt, start_iter=1, tb_logger=None):
... |
initialized_logger = {}
class AvgTimer():
def __init__(self, window=200):
self.window = window # average window
self.current_time = 0
self.total_time = 0
self.count = 0
self.avg_time = 0
self.start()
def start(self):
self.start_time = self.tic = tim... | rank, _ = get_dist_info() | 0 | 2023-11-09 08:08:09+00:00 | 2k |
Rishit-dagli/Astroformer | pytorch-image-models/timm/layers/create_norm.py | [
{
"identifier": "GroupNorm",
"path": "pytorch-image-models/timm/layers/norm.py",
"snippet": "class GroupNorm(nn.GroupNorm):\n def __init__(self, num_channels, num_groups=32, eps=1e-5, affine=True):\n # NOTE num_channels is swapped to first arg for consistency in swapping norm layers with BN\n ... | import functools
import types
import torch.nn as nn
from typing import Type
from .norm import GroupNorm, GroupNorm1, LayerNorm, LayerNorm2d, RmsNorm
from torchvision.ops.misc import FrozenBatchNorm2d | 1,331 | """ Norm Layer Factory
Create norm modules by string (to mirror create_act and creat_norm-act fns)
Copyright 2022 Ross Wightman
"""
_NORM_MAP = dict(
batchnorm=nn.BatchNorm2d,
batchnorm2d=nn.BatchNorm2d,
batchnorm1d=nn.BatchNorm1d,
groupnorm=GroupNorm,
groupnorm1=GroupNorm1,
layernorm=Layer... | """ Norm Layer Factory
Create norm modules by string (to mirror create_act and creat_norm-act fns)
Copyright 2022 Ross Wightman
"""
_NORM_MAP = dict(
batchnorm=nn.BatchNorm2d,
batchnorm2d=nn.BatchNorm2d,
batchnorm1d=nn.BatchNorm1d,
groupnorm=GroupNorm,
groupnorm1=GroupNorm1,
layernorm=Layer... | rmsnorm=RmsNorm, | 4 | 2023-11-05 01:25:14+00:00 | 2k |
dewgenenny/rtl_433_discoverandsubmit | rtl_433_discoverandsubmit/modules/mqtt_client.py | [
{
"identifier": "config",
"path": "rtl_433_discoverandsubmit/config.py",
"snippet": ""
},
{
"identifier": "save_devices_to_file",
"path": "rtl_433_discoverandsubmit/modules/device_manager.py",
"snippet": "def save_devices_to_file(devices):\n \"\"\"Save the list of devices to a JSON fi... | import paho.mqtt.client as mqtt
import json
import logging
from datetime import datetime
from rtl_433_discoverandsubmit import config
from rtl_433_discoverandsubmit.modules.device_manager import save_devices_to_file | 704 | log_level = getattr(logging, config.configuration['log_level'])
logging.basicConfig(filename=config.configuration['log_filename'], level=log_level)
# List to store detected devices
detected_devices = []
def reset_message_counters():
global detected_devices
for device in detected_devices:
if 'message_... | log_level = getattr(logging, config.configuration['log_level'])
logging.basicConfig(filename=config.configuration['log_filename'], level=log_level)
# List to store detected devices
detected_devices = []
def reset_message_counters():
global detected_devices
for device in detected_devices:
if 'message_... | save_devices_to_file(detected_devices) | 1 | 2023-11-03 19:34:56+00:00 | 2k |
dvruette/pygba | src/pygba/gym_env.py | [
{
"identifier": "KEY_MAP",
"path": "src/pygba/utils.py",
"snippet": "KEY_MAP = {\n \"up\": GBA.KEY_UP,\n \"down\": GBA.KEY_DOWN,\n \"left\": GBA.KEY_LEFT,\n \"right\": GBA.KEY_RIGHT,\n \"A\": GBA.KEY_A,\n \"B\": GBA.KEY_B,\n \"L\": GBA.KEY_L,\n \"R\": GBA.KEY_R,\n \"start\": G... | import sys
import gymnasium as gym
import mgba.core
import mgba.image
import numpy as np
import pygame
from typing import Any, Literal
from .utils import KEY_MAP
from .pygba import PyGBA
from .game_wrappers.base import GameWrapper
from pygame import gfxdraw | 1,415 |
try:
except ImportError as e:
pass
def _pil_image_to_pygame(img):
return pygame.image.fromstring(img.tobytes(), img.size, img.mode).convert()
class PyGBAEnv(gym.Env):
metadata = {
"render_modes": ["human", "rgb_array"],
"render_fps": 60,
}
def __init__(
self,
... |
try:
except ImportError as e:
pass
def _pil_image_to_pygame(img):
return pygame.image.fromstring(img.tobytes(), img.size, img.mode).convert()
class PyGBAEnv(gym.Env):
metadata = {
"render_modes": ["human", "rgb_array"],
"render_fps": 60,
}
def __init__(
self,
... | game_wrapper: GameWrapper | None = None, | 2 | 2023-11-08 20:51:13+00:00 | 2k |
BouncyKoishi/ChuCaoQi-Bot | dbConnection/draw_item.py | [
{
"identifier": "DrawItemList",
"path": "dbConnection/models.py",
"snippet": "class DrawItemList(Model):\n id = IntField(pk=True)\n name = CharField(max_length=64)\n pool = CharField(max_length=32)\n rareRank = IntField()\n detail = CharField(max_length=1024)\n author = CharField(max_l... | from random import randint
from .models import DrawItemList, DrawItemStorage
from tortoise import Tortoise
from tortoise.query_utils import Prefetch
from tortoise.functions import Sum | 646 |
async def getItem(itemId):
return await DrawItemList.filter(id=itemId).first()
async def getItemByName(itemName):
return await DrawItemList.filter(name=itemName).first()
async def getItemListByAuthor(qqNum, rareRank=None, poolName=None):
filterQuery = getRareRankAndPoolFilter(rareRank, poolName)
r... |
async def getItem(itemId):
return await DrawItemList.filter(id=itemId).first()
async def getItemByName(itemName):
return await DrawItemList.filter(name=itemName).first()
async def getItemListByAuthor(qqNum, rareRank=None, poolName=None):
filterQuery = getRareRankAndPoolFilter(rareRank, poolName)
r... | Prefetch("draw_item_storage", queryset=DrawItemStorage.filter(qq=qqNum), to_attr="storage") | 1 | 2023-11-02 04:06:31+00:00 | 2k |
ilur98/DGQ | dgq/utils/evalutils.py | [
{
"identifier": "get_blocks",
"path": "dgq/utils/modelutils.py",
"snippet": "def get_blocks(model):\n if isinstance(model, LlamaForCausalLM):\n layers = model.model.layers\n elif isinstance(model, OPTForCausalLM):\n layers = model.model.decoder.layers\n elif isinstance(model, Bloo... | import torch
import torch.nn as nn
import numpy as np
from dgq.utils.modelutils import get_blocks, move_embed, move_norm_head
from datasets import load_dataset, load_from_disk
from tqdm import tqdm
from dgq.utils.datautils import IGNORE_INDEX, DEFAULT_PAD_TOKEN | 866 |
@torch.no_grad()
def model_eval(model, testenc, dev, local_args=None):
testenc = testenc.input_ids
nsamples = testenc.numel() // model.seqlen
# model = model.to(dev)
model.eval()
model.config.use_cache = False
# testenc = testenc.to(dev)
|
@torch.no_grad()
def model_eval(model, testenc, dev, local_args=None):
testenc = testenc.input_ids
nsamples = testenc.numel() // model.seqlen
# model = model.to(dev)
model.eval()
model.config.use_cache = False
# testenc = testenc.to(dev) | layers = get_blocks(model) | 0 | 2023-11-01 13:45:16+00:00 | 2k |
JeasunLok/ResNet-pytorch | test.py | [
{
"identifier": "AverageMeter",
"path": "utils/utils.py",
"snippet": "class AverageMeter(object):\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.average = 0 \n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.sum += val * n\n self.count += n\n... | import numpy as np
import torch
from tqdm import tqdm
from utils.utils import AverageMeter
from utils.accuracy import accuracy | 695 |
# test model
def test_epoch(model, test_loader, device):
acc1 = AverageMeter()
acc3 = AverageMeter()
prediction = np.array([])
label = np.array([])
loop = tqdm(enumerate(test_loader), total = len(test_loader))
with torch.no_grad():
for batch_idx, (batch_data, batch_label) in loop:
... |
# test model
def test_epoch(model, test_loader, device):
acc1 = AverageMeter()
acc3 = AverageMeter()
prediction = np.array([])
label = np.array([])
loop = tqdm(enumerate(test_loader), total = len(test_loader))
with torch.no_grad():
for batch_idx, (batch_data, batch_label) in loop:
... | acc_batch = accuracy(batch_prediction, batch_label, topk=(1,3)) | 1 | 2023-11-02 06:26:47+00:00 | 2k |
soobin419/EDAT | basicsr/utils/logger.py | [
{
"identifier": "get_dist_info",
"path": "basicsr/utils/dist_util.py",
"snippet": "def get_dist_info():\n if dist.is_available():\n initialized = dist.is_initialized()\n else:\n initialized = False\n if initialized:\n rank = dist.get_rank()\n world_size = dist.get_wo... | import datetime
import logging
import time
import wandb
import torch
import torchvision
from .dist_util import get_dist_info, master_only
from torch.utils.tensorboard import SummaryWriter
from version import __version__ | 1,528 | train (dict): Contains 'total_iter' (int) for total iters.
use_tb_logger (bool): Use tensorboard logger.
start_iter (int): Start iter. Default: 1.
tb_logger (obj:`tb_logger`): Tensorboard logger. Default: None.
"""
def __init__(self, opt, start_iter=1, tb_logger=None):
... |
initialized_logger = {}
class AvgTimer():
def __init__(self, window=200):
self.window = window # average window
self.current_time = 0
self.total_time = 0
self.count = 0
self.avg_time = 0
self.start()
def start(self):
self.start_time = self.tic = tim... | rank, _ = get_dist_info() | 0 | 2023-11-09 08:53:40+00:00 | 2k |
noco-ai/elemental-golem | modules/noco-ai/bark-tts/handler.py | [
{
"identifier": "BaseHandler",
"path": "application/base_handler.py",
"snippet": "class BaseHandler:\n\n def __init__(self):\n self.cached_schemas = {}\n\n def execute(self, model, request) -> dict:\n raise NotImplementedError(\"The `execute` method should be implemented in the deriv... | from application.base_handler import BaseHandler
from transformers import AutoProcessor, AutoModel
from io import BytesIO
from application.progress_streamer import ProgressStreamer
import torch
import base64
import scipy
import copy
import logging | 1,247 |
logger = logging.getLogger(__name__)
class BarkHandler(BaseHandler):
def __init__(self):
|
logger = logging.getLogger(__name__)
class BarkHandler(BaseHandler):
def __init__(self): | self.progress_streamer = ProgressStreamer() | 1 | 2023-11-06 19:03:07+00:00 | 2k |
anilaltuner/personalized-news-agent | pages/chatbot.py | [
{
"identifier": "CUSTOM_ALGO_ID",
"path": "news.py",
"snippet": "CUSTOM_ALGO_ID = st.secrets[\"custom_algo_id\"]"
},
{
"identifier": "initialize_session",
"path": "news.py",
"snippet": "def initialize_session(user_input=\"\"):\n \"\"\"Initialize or restart the session.\"\"\"\n if u... | import streamlit as st
from firstbatch import AlgorithmLabel
from pydantic import BaseModel
from news import CUSTOM_ALGO_ID, initialize_session, fetch_content
from chat_tools.kernel import chat, setup_chat_with_memory
from markdowns.markdowns_chat import css_, sidebar | 1,313 |
# Pydantic models
class SessionData(BaseModel):
username: str
class PersonalizeData(BaseModel):
message: str
class SignalData(BaseModel):
sessionID: dict
id: str
def get_user_input():
return st.sidebar.text_input("Username/Session Name", st.session_state.get("username", ""))
def update_se... |
# Pydantic models
class SessionData(BaseModel):
username: str
class PersonalizeData(BaseModel):
message: str
class SignalData(BaseModel):
sessionID: dict
id: str
def get_user_input():
return st.sidebar.text_input("Username/Session Name", st.session_state.get("username", ""))
def update_se... | fetch_content() | 2 | 2023-11-07 12:51:01+00:00 | 2k |
m4rkw/monzo-utils | monzo_utils/model/payment.py | [
{
"identifier": "Config",
"path": "monzo_utils/lib/config.py",
"snippet": "class Config(metaclass=Singleton):\n\n def __init__(self, config=None, config_path=None):\n if config_path is None:\n homedir = pwd.getpwuid(os.getuid()).pw_dir\n config_path = f\"{homedir}/.monzo\... | import re
import datetime
from monzo_utils.lib.config import Config
from monzo_utils.model.transaction import Transaction
from monzo_utils.lib.transactions import Transactions | 1,356 | self.today = datetime.datetime.now()
self.cache = {}
def data(self, abbreviate=False):
if self.num_paid is not None:
suffix = '%d/%d' % (
self.num_paid,
self.num_total
)
else:
suffix = ''
if self.remainin... |
class Payment:
transaction_type = 'money_out'
always_fixed = False
def __init__(self, config, payment_list_config, payment_config, last_salary_date, next_salary_date, following_salary_date):
self.config = config
self.payment_list_config = payment_list_config
self.payment_config = ... | if 'last_amount_overrides' in Config().keys and \ | 0 | 2023-11-05 12:48:18+00:00 | 2k |
rossiyareich/inknhue | src/conditional/conditional_encoder.py | [
{
"identifier": "DownSample",
"path": "src/downsample.py",
"snippet": "class DownSample(nn.Module):\n \"\"\"\n ## Down-sampling layer\n \"\"\"\n\n def __init__(self, channels: int):\n \"\"\"\n :param channels: is the number of channels\n \"\"\"\n super().__init__(... | from typing import List
from torch import nn
from ..downsample import DownSample
from ..resnet_block import ResnetBlock
from ..utils import zero_module
import torch | 1,084 |
class ConditionalEncoder(nn.Module):
def __init__(
self,
*,
channels: int,
channel_multipliers: List[int],
n_resnet_blocks: int,
in_channels: int,
) -> None:
super().__init__()
# Number of blocks of different resolutions.
# The resolut... |
class ConditionalEncoder(nn.Module):
def __init__(
self,
*,
channels: int,
channel_multipliers: List[int],
n_resnet_blocks: int,
in_channels: int,
) -> None:
super().__init__()
# Number of blocks of different resolutions.
# The resolut... | proj = zero_module(proj) | 2 | 2023-11-03 09:35:30+00:00 | 2k |
drakoRRR/chatSynthia | users/views.py | [
{
"identifier": "ProfileForm",
"path": "users/forms.py",
"snippet": "class ProfileForm(UserChangeForm):\n first_name = forms.CharField(widget=forms.TextInput(attrs={\n 'class': 'form-control py-4'\n }))\n last_name = forms.CharField(widget=forms.TextInput(attrs={\n 'class': 'form-... | from django.contrib import auth, messages
from django.contrib.auth.views import LoginView
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView, UpdateView
from users.forms import ProfileForm, UserLoginForm, UserRegisterForm
from users.models import User | 864 |
# Create your views here.
class LoginUserView(LoginView):
template_name = 'users/login.html'
form_class = UserLoginForm
def form_invalid(self, form):
messages.error(self.request, 'There was an error with username or password, check again !')
return super().form_invalid(form)
class Regi... |
# Create your views here.
class LoginUserView(LoginView):
template_name = 'users/login.html'
form_class = UserLoginForm
def form_invalid(self, form):
messages.error(self.request, 'There was an error with username or password, check again !')
return super().form_invalid(form)
class Regi... | form_class = ProfileForm | 0 | 2023-11-08 12:21:53+00:00 | 2k |
TencentBlueKing/bkflow-feel | bkflow_feel/parsers.py | [
{
"identifier": "RangeGroupData",
"path": "bkflow_feel/data_models.py",
"snippet": "class RangeGroupData(BaseModel):\n left_val: Any\n right_val: Any\n left_operator: RangeGroupOperator\n right_operator: RangeGroupOperator"
},
{
"identifier": "RangeGroupOperator",
"path": "bkflow... | import abc
import datetime
import logging
import re
import pytz
from dateutil.parser import parse as date_parse
from .data_models import RangeGroupData, RangeGroupOperator
from .utils import FEELFunctionsManager
from .validators import BinaryOperationValidator, DummyValidator, ListsLengthValidator | 1,209 | # -*- coding: utf-8 -*-
logger = logging.getLogger(__name__)
class Expression(metaclass=abc.ABCMeta):
validator_cls = DummyValidator
@abc.abstractmethod
def evaluate(self, context):
pass
class CommonExpression(Expression):
def __init__(self, value):
self.value = value
def ev... | # -*- coding: utf-8 -*-
logger = logging.getLogger(__name__)
class Expression(metaclass=abc.ABCMeta):
validator_cls = DummyValidator
@abc.abstractmethod
def evaluate(self, context):
pass
class CommonExpression(Expression):
def __init__(self, value):
self.value = value
def ev... | validator_cls = ListsLengthValidator | 5 | 2023-11-09 13:47:26+00:00 | 2k |
namedgraph/oxijen | oxijen/model_impl/impl.py | [
{
"identifier": "Resource",
"path": "oxijen/rdf_model.py",
"snippet": "class Resource(ABC):\n\n @property\n def node(self):\n return self._node\n\n @property\n def graph(self):\n return self._graph\n\n @property\n def is_anon(self):\n if isinstance(self.node, Named... | from oxijen.rdf_model import Resource, Property, Graph, Dataset
from oxijen.model_impl.xsd import XSD
from pyoxigraph import Store, Triple, BlankNode, NamedNode, Literal, Quad, DefaultGraph
from typing import Iterator, Union, Optional, Any | 1,453 |
class ResourceImpl(Resource):
def __init__(self, node: Union[BlankNode, NamedNode], graph: Graph):
self._node = node
self._graph = graph
def __hash__(self):
return hash(self.node.value)
def __eq__(self, other):
if isinstance(other, self.__class__):
return ... |
class ResourceImpl(Resource):
def __init__(self, node: Union[BlankNode, NamedNode], graph: Graph):
self._node = node
self._graph = graph
def __hash__(self):
return hash(self.node.value)
def __eq__(self, other):
if isinstance(other, self.__class__):
return ... | datatype = NamedNode(XSD.INTEGER.value) | 4 | 2023-11-03 19:50:51+00:00 | 2k |
sivasurend/lyzr | build/lib/lyzr/utils/document_reading.py | [
{
"identifier": "LyzrDocxReader",
"path": "lyzr/utils/docx_reader.py",
"snippet": "class LyzrDocxReader(BaseReader):\n def __init__(self) -> None:\n try:\n import docx2txt\n except ImportError:\n raise ImportError(\n \"`docx2txt` package not found, p... | import logging
from typing import List, Sequence, Optional
from llama_index.readers.file.base import SimpleDirectoryReader
from llama_index.schema import Document
from lyzr.utils.docx_reader import LyzrDocxReader
from lyzr.utils.pdf_reader import LyzrPDFReader
from lyzr.utils.txt_reader import LyzrTxtReader
from lyzr.u... | 1,230 |
logger = logging.getLogger(__name__)
def read_pdf_as_documents(
input_dir: Optional[str] = None,
input_files: Optional[List] = None,
exclude_hidden: bool = True,
filename_as_id: bool = True,
recursive: bool = True,
required_exts: Optional[List[str]] = None,
**kwargs,
) -> Sequence[Docum... |
logger = logging.getLogger(__name__)
def read_pdf_as_documents(
input_dir: Optional[str] = None,
input_files: Optional[List] = None,
exclude_hidden: bool = True,
filename_as_id: bool = True,
recursive: bool = True,
required_exts: Optional[List[str]] = None,
**kwargs,
) -> Sequence[Docum... | file_extractor = {".pdf": LyzrPDFReader()} | 1 | 2023-11-07 14:52:08+00:00 | 2k |
focused-labs/ai-custom-chatbot-data-pipeline | main.py | [
{
"identifier": "import_web_scrape_data",
"path": "import_service.py",
"snippet": "def import_web_scrape_data(urls: list):\n BeautifulSoupWebReader = download_loader(\"BeautifulSoupWebReader\")\n\n loader = BeautifulSoupWebReader()\n documents = loader.load_data(urls=urls)\n\n for document i... | import logging
import os
import sys
import openai
import uvicorn
from contextlib import asynccontextmanager
from dotenv import load_dotenv
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from import_service import import_web_scrape_data, import_notion_data
from models.imported_pages impor... | 689 |
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
allowed_origins = [
"http://localhost:3000",
]
|
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
allowed_origins = [
"http://localhost:3000",
]
| query_service = QueryService() | 5 | 2023-11-01 20:47:07+00:00 | 2k |
pradyunsg/pip-resolver-benchmarks | src/common/creation.py | [
{
"identifier": "DistributionInfo",
"path": "src/common/model.py",
"snippet": "class DistributionInfo(BaseModel):\n depends_by_extra: dict[str, list[str]]\n requires_python: str | None = None\n\n @field_validator(\"depends_by_extra\", mode=\"after\")\n @classmethod\n def ensure_no_empty_e... | import base64
import hashlib
import zipfile
from pathlib import Path
from rich.progress import BarColumn, MofNCompleteColumn, Progress
from .model import DistributionInfo, Scenario | 725 | """Creates the actual wheel files in a directory to pass to the resolver.
"""
from __future__ import annotations
WHEEL = """\
Wheel-Version: 1.0
Generator: pip-resolver-benchmark
Root-Is-Purelib: true
Tag: py2-none-any
Tag: py3-none-any
"""
def _make_wheel(
| """Creates the actual wheel files in a directory to pass to the resolver.
"""
from __future__ import annotations
WHEEL = """\
Wheel-Version: 1.0
Generator: pip-resolver-benchmark
Root-Is-Purelib: true
Tag: py2-none-any
Tag: py3-none-any
"""
def _make_wheel( | name: str, version: str, wheel: DistributionInfo, output_dir: Path | 0 | 2023-11-05 17:59:32+00:00 | 2k |
allmonday/pydantic2-resolve | pydantic2_resolve/resolver.py | [
{
"identifier": "ResolverTargetAttrNotFound",
"path": "pydantic2_resolve/exceptions.py",
"snippet": "class ResolverTargetAttrNotFound(Exception):\n pass"
},
{
"identifier": "LoaderFieldNotProvidedError",
"path": "pydantic2_resolve/exceptions.py",
"snippet": "class LoaderFieldNotProvid... | import asyncio
import contextvars
import inspect
import pydantic2_resolve.constant as const
import pydantic2_resolve.util as util
from collections import defaultdict
from inspect import iscoroutine
from typing import TypeVar, Dict
from .exceptions import ResolverTargetAttrNotFound, LoaderFieldNotProvidedError, MissingA... | 1,477 |
# for dataloader which has class attributes, you can assign the value at here
self.loader_filters = loader_filters or {}
# now you can pass your loader instance, Resolver will check `isinstance``
if loader_instances and self._validate_loader_instance(loader_instances):
self... |
def LoaderDepend( # noqa: N802
dependency: Optional[Callable[..., Any]] = None,
) -> Any:
return Depends(dependency=dependency)
class Depends:
def __init__(
self,
dependency: Optional[Callable[..., Any]] = None,
):
self.dependency = dependency
T = TypeVar("T")
class Resolv... | raise LoaderFieldNotProvidedError(f'{cache_key}.{field} not found in Resolver()') | 1 | 2023-11-01 02:37:26+00:00 | 2k |
StoneMoe/ASub | app/ui/windows/subtitle_window.py | [
{
"identifier": "SRTFile",
"path": "app/core/models/srt.py",
"snippet": "class SRTFile:\r\n filepath: str\r\n entries: List[SRTEntry]\r\n\r\n def __init__(self, source: str | list):\r\n self.filepath = ''\r\n self.entries = []\r\n\r\n match source:\r\n case str()... | from PyQt5.QtWidgets import QVBoxLayout, QPushButton, QTableWidgetItem, QDialog
from qfluentwidgets import TableWidget, isDarkTheme
from qframelesswindow import FramelessWindow
from app.core.models.srt import SRTFile
from app.ui.const import CONTAINER_MARGINS
from app.core.utils.env import res_dir | 1,290 |
class SubtitleWindow(QDialog, FramelessWindow):
def __init__(self, filepath: str, parent=None):
super().__init__(parent)
self.srt_file = SRTFile(filepath)
self.hBoxLayout = QVBoxLayout(self)
self.tableView = TableWidget(self)
self.saveButton = QPushButton("Save", self)
... |
class SubtitleWindow(QDialog, FramelessWindow):
def __init__(self, filepath: str, parent=None):
super().__init__(parent)
self.srt_file = SRTFile(filepath)
self.hBoxLayout = QVBoxLayout(self)
self.tableView = TableWidget(self)
self.saveButton = QPushButton("Save", self)
... | with open(res_dir(f'app/ui/resource/qss/{color}/style.qss'), encoding='utf-8') as f: | 2 | 2023-11-07 16:45:43+00:00 | 2k |
openshift/lightspeed-service | tests/unit/docs/test_doc_summarizer.py | [
{
"identifier": "DocsSummarizer",
"path": "ols/src/docs/docs_summarizer.py",
"snippet": "class DocsSummarizer:\n \"\"\"A class for summarizing documentation context.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the DocsSummarizer.\"\"\"\n self.logger = Logger(\"docs_summarizer\")... | import os
from unittest.mock import patch
from ols.src.docs.docs_summarizer import DocsSummarizer
from ols.utils import config
from tests.mock_classes.llm_loader import mock_llm_loader
from tests.mock_classes.mock_llama_index import MockLlamaIndex | 1,175 | """Unit tests for DocsSummarizer class."""
@patch("ols.src.docs.docs_summarizer.LLMLoader", new=mock_llm_loader(None))
@patch("ols.src.docs.docs_summarizer.ServiceContext.from_defaults")
@patch("ols.src.docs.docs_summarizer.StorageContext.from_defaults")
| """Unit tests for DocsSummarizer class."""
@patch("ols.src.docs.docs_summarizer.LLMLoader", new=mock_llm_loader(None))
@patch("ols.src.docs.docs_summarizer.ServiceContext.from_defaults")
@patch("ols.src.docs.docs_summarizer.StorageContext.from_defaults") | @patch("ols.src.docs.docs_summarizer.load_index_from_storage", new=MockLlamaIndex) | 3 | 2023-11-08 06:29:41+00:00 | 2k |
xlcaptain/LLM-Workbench | component/knowledge_chat.py | [
{
"identifier": "ElasticsearchServer",
"path": "component/pipelines/es.py",
"snippet": "class ElasticsearchServer:\n def __init__(self):\n self.client = Elasticsearch(\n ES_URL,\n verify_certs=False,\n )\n self.embedding = Embeddings()\n self.es = Ela... | import time
import os
import streamlit as st
import pandas as pd
from .pipelines.es import ElasticsearchServer
from .pipelines.utils import handle_response, create_message
from .pipelines.prompt import KNOWLEDGE_PROMPT, CHAT_EXAMPLES | 1,286 |
BAICHUAN_URL = os.getenv("BAICHUAN_URL")
def handle_kb_qa(prompt, top_k, threshold):
index_name = 'audit_index'
|
BAICHUAN_URL = os.getenv("BAICHUAN_URL")
def handle_kb_qa(prompt, top_k, threshold):
index_name = 'audit_index' | es_server = ElasticsearchServer() | 0 | 2023-11-01 07:54:03+00:00 | 2k |
NicolasZucchet/Online-learning-LR-dependencies | online_lru/rec.py | [
{
"identifier": "matrix_init",
"path": "online_lru/rec_init.py",
"snippet": "def matrix_init(key, shape, dtype=jnp.float32, normalization=1):\n return random.normal(key=key, shape=shape, dtype=dtype) / normalization"
},
{
"identifier": "truncated_normal_matrix_init",
"path": "online_lru/r... | from functools import partial
from flax import linen as nn
from .rec_init import matrix_init, truncated_normal_matrix_init, theta_init, nu_init, gamma_log_init
from flax.core.frozen_dict import unfreeze
import jax
import jax.numpy as jnp | 1,517 | A_i, b_i = q_i
A_j, b_j = q_j
return A_j * A_i, jax.lax.stop_gradient(A_j * b_i) + b_j
class LRU(nn.Module):
"""
LRU layer that updates internal elegibility traces to allow online learning.
"""
d_hidden: int # hidden state dimension
d_model: int # input and output dimensions
seq... |
# Parallel scan operations
@jax.vmap
def binary_operator_diag(q_i, q_j):
"""Binary operator for parallel scan of linear recurrence"""
A_i, b_i = q_i
A_j, b_j = q_j
return A_j * A_i, A_j * b_i + b_j
@jax.vmap
def binary_operator_diag_spatial(q_i, q_j):
"""Same as above but stop the gradient for t... | partial(theta_init, max_phase=self.max_phase, log=self.exp_param), | 2 | 2023-11-01 13:18:32+00:00 | 2k |
uygarkurt/video-retalking | models/ENet.py | [
{
"identifier": "ResBlock",
"path": "models/base_blocks.py",
"snippet": "class ResBlock(nn.Module):\n def __init__(self, in_channels, out_channels, mode='down'):\n super(ResBlock, self).__init__()\n self.conv1 = nn.Conv2d(in_channels, in_channels, 3, 1, 1)\n self.conv2 = nn.Conv2... | import torch
import torch.nn as nn
import torch.nn.functional as F
from models.base_blocks import ResBlock, StyleConv, ToRGB | 1,390 |
class ENet(nn.Module):
def __init__(
self,
num_style_feat=512,
lnet=None,
concat=False
):
super(ENet, self).__init__()
self.low_res = lnet
for param in self.low_res.parameters():
param.requires_grad = False
channel_multiplie... |
class ENet(nn.Module):
def __init__(
self,
num_style_feat=512,
lnet=None,
concat=False
):
super(ENet, self).__init__()
self.low_res = lnet
for param in self.low_res.parameters():
param.requires_grad = False
channel_multiplie... | self.to_rgbs.append(ToRGB(out_channels, num_style_feat, upsample=True)) | 2 | 2023-11-02 18:25:51+00:00 | 2k |
fortelex/hiveline | hiveline/jobs/mongo.py | [
{
"identifier": "get_database",
"path": "hiveline/mongo/db.py",
"snippet": "def get_database():\n dotenv.load_dotenv()\n\n user = os.getenv(\"UP_MONGO_USER\")\n password = os.getenv(\"UP_MONGO_PASSWORD\")\n domain = os.getenv(\"UP_MONGO_DOMAIN\")\n database = os.getenv(\"UP_MONGO_DATABASE... | import datetime
import pymongo.errors
from hiveline import get_database
from hiveline.jobs.jobs import JobsDataSource, JobStatus | 1,517 |
class MongoJob:
"""
A calculation job of some sort. Used to track the status of a job. A job is uniquely identified by the key (
service_name, sim_id, job_id)
:param service_name: the name of the service
:param sim_id: the simulation ID
:param job_id: the job ID
:param status: the job s... |
class MongoJob:
"""
A calculation job of some sort. Used to track the status of a job. A job is uniquely identified by the key (
service_name, sim_id, job_id)
:param service_name: the name of the service
:param sim_id: the simulation ID
:param job_id: the job ID
:param status: the job s... | class MongoJobsDataSource(JobsDataSource): | 1 | 2023-11-07 15:34:04+00:00 | 2k |
uhppoted/uhppoted-app-home-assistant | custom_components/uhppoted/config.py | [
{
"identifier": "CONF_BIND_ADDR",
"path": "custom_components/uhppoted/const.py",
"snippet": "CONF_BIND_ADDR = 'bind_address'"
},
{
"identifier": "CONF_BROADCAST_ADDR",
"path": "custom_components/uhppoted/const.py",
"snippet": "CONF_BROADCAST_ADDR = 'broadcast_address'"
},
{
"iden... | import re
import logging
import datetime
import calendar
import uuid
from typing import Any
from uhppoted import uhppote
from .const import CONF_BIND_ADDR
from .const import CONF_BROADCAST_ADDR
from .const import CONF_LISTEN_ADDR
from .const import CONF_DEBUG
from .const import CONF_CONTROLLERS
from .const import CONF_... | 1,116 |
_LOGGER = logging.getLogger(__name__)
MAX_CARDS = 25
MAX_CARD_INDEX = 20000
MAX_ERRORS = 5
def normalise(v):
return re.sub(r'\s+', '', f'{v}', flags=re.UNICODE).lower()
def validate_controller_id(serial_no, name, options):
if not name or name.strip() == '':
raise ValueError(ERR_INVALID_CONTROL... |
_LOGGER = logging.getLogger(__name__)
MAX_CARDS = 25
MAX_CARD_INDEX = 20000
MAX_ERRORS = 5
def normalise(v):
return re.sub(r'\s+', '', f'{v}', flags=re.UNICODE).lower()
def validate_controller_id(serial_no, name, options):
if not name or name.strip() == '':
raise ValueError(ERR_INVALID_CONTROL... | if name.strip() != '-' and options and CONF_DOORS in options: | 8 | 2023-11-06 18:46:49+00:00 | 2k |
kyegomez/HeptapodLM | train.py | [
{
"identifier": "Autoregressive2DWrapper",
"path": "heptapod/at.py",
"snippet": "class Autoregressive2DWrapper(nn.Module):\n def __init__(self, net, matrix_size=32, pad_value=0):\n super().__init__()\n self.matrix_size = matrix_size\n self.pad_value = pad_value\n self.net ... | import gzip
import random
import numpy as np
import torch
import torch.optim as optim
import tqdm
from torch.utils.data import DataLoader, Dataset
from heptapod.at import Autoregressive2DWrapper
from heptapod.model import NonLinearTransformer | 756 |
# Constants
NUM_BATCHES = int(1e5)
BATCH_SIZE = 4
GRADIENT_ACCUMULATE_EVERY = 4
LEARNING_RATE = 2e-4
VALIDATE_EVERY = 100
GENERATE_EVERY = 500
GENERATE_LENGTH = 512
SEQ_LEN = 1024
# Helpers
def cycle(loader):
while True:
for data in loader:
yield data
def decode_token(token):
return s... |
# Constants
NUM_BATCHES = int(1e5)
BATCH_SIZE = 4
GRADIENT_ACCUMULATE_EVERY = 4
LEARNING_RATE = 2e-4
VALIDATE_EVERY = 100
GENERATE_EVERY = 500
GENERATE_LENGTH = 512
SEQ_LEN = 1024
# Helpers
def cycle(loader):
while True:
for data in loader:
yield data
def decode_token(token):
return s... | model = NonLinearTransformer(vocab_size=10000, dim=512, depth=6, matrix_dim=5) | 1 | 2023-11-01 06:07:50+00:00 | 2k |
shixiaoyu0216/SAC4IR | sacd/memory/per.py | [
{
"identifier": "LazyMultiStepMemory",
"path": "sacd/memory/base.py",
"snippet": "class LazyMultiStepMemory(LazyMemory):\n\n def __init__(self, capacity, state_shape, device, gamma=0.99,\n multi_step=3):\n super(LazyMultiStepMemory, self).__init__(\n capacity, state_... | import numpy as np
import torch
from .base import LazyMultiStepMemory
from .segment_tree import SumTree, MinTree | 740 |
class LazyPrioritizedMultiStepMemory(LazyMultiStepMemory):
def __init__(self, capacity, state_shape, device, gamma=0.99,
multi_step=3, alpha=0.6, beta=0.4, beta_steps=2e5,
min_pa=0.0, max_pa=1.0, eps=0.01):
super().__init__(capacity, state_shape, device, gamma, multi_ste... |
class LazyPrioritizedMultiStepMemory(LazyMultiStepMemory):
def __init__(self, capacity, state_shape, device, gamma=0.99,
multi_step=3, alpha=0.6, beta=0.4, beta_steps=2e5,
min_pa=0.0, max_pa=1.0, eps=0.01):
super().__init__(capacity, state_shape, device, gamma, multi_ste... | self.it_min = MinTree(it_capacity) | 2 | 2023-11-02 07:35:57+00:00 | 2k |
In-Network-Machine-Learning/QCMP | initiate_rules.py | [
{
"identifier": "init_path_weights",
"path": "q_table.py",
"snippet": "def init_path_weights(p4info_helper, ingress_sw, nhop_dmacs, nhop_ipv4s, ports):\n for i in range(50):\n write_path_weights(p4info_helper, ingress_sw=ingress_sw, value=i,\n nhop_dmac=nhop_dmacs[0], nhop_ipv4=nhop... | import sys
import argparse
import os
import pandas as pd
import grpc
import p4runtime_lib.bmv2
import p4runtime_lib.helper
from scapy.all import *
from scapy.layers.inet import _IPOption_HDR
from p4runtime_lib.error_utils import printGrpcError
from p4runtime_lib.switch import ShutdownAllSwitchConnections
from q_table i... | 951 | # This file is part of the Planter extend project: QCMP.
# This program is a free software tool, which does ensemble in-network reinforcement learning for load balancing.
# licensed under Apache-2.0
#
# Utility: This file is used to initiate rules in the q-table
#
# Copyright (c) 2022-2023 Benjamin Rienecker Modified b... | # This file is part of the Planter extend project: QCMP.
# This program is a free software tool, which does ensemble in-network reinforcement learning for load balancing.
# licensed under Apache-2.0
#
# Utility: This file is used to initiate rules in the q-table
#
# Copyright (c) 2022-2023 Benjamin Rienecker Modified b... | init_path_weights(p4info_helper, s1, nhop_dmacs, nhop_ipv4s, ports) | 0 | 2023-11-01 09:37:28+00:00 | 2k |
Fsoft-AIC/LSDM | vis_fitting_results.py | [
{
"identifier": "gen_human_meshes",
"path": "gen_human_meshes.py",
"snippet": "def gen_human_meshes(vertices_path, output_path):\n vertices = np.load(open(vertices_path, \"rb\"))\n # If your input human vertices are full resolution SMPL-X bodies, use mesh_0.obj\n # faces = trimesh.load(os.path.... | import os
import numpy as np
import argparse
import open3d as o3d
import json
from pathlib import Path
from gen_human_meshes import gen_human_meshes, gen_human_meshes_humanise
from tqdm import tqdm | 723 |
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="")
parser.add_argument("--fitting_results_path", type=str, help="Path to the fitting results of some motion sequence")
parser.add_argument("--vertices_path", type=str, help="Path to human vertices of some motion sequence")
parser... |
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="")
parser.add_argument("--fitting_results_path", type=str, help="Path to the fitting results of some motion sequence")
parser.add_argument("--vertices_path", type=str, help="Path to human vertices of some motion sequence")
parser... | gen_human_meshes_humanise(vertices_path, body_faces, output_path=human_mesh_dir) | 1 | 2023-11-06 07:55:51+00:00 | 2k |
molML/traversing_chem_space | active_learning/data_prep.py | [
{
"identifier": "molecular_graph_featurizer",
"path": "active_learning/utils.py",
"snippet": "def molecular_graph_featurizer(smiles: str, y=None, structural_feats: bool = True, functional_feats: bool = True):\n\n y = torch.tensor([y]).to(torch.long)\n\n mol = Chem.MolFromSmiles(smiles, sanitize=Tr... | from active_learning.utils import molecular_graph_featurizer as smiles_to_graph
from active_learning.utils import smiles_to_ecfp, get_tanimoto_matrix, check_featurizability
from collections import OrderedDict
from rdkit.Chem.Scaffolds import MurckoScaffold
from rdkit import Chem
from tqdm import tqdm
from typing import... | 1,588 |
def canonicalize(smiles: str, sanitize: bool = True):
return Chem.MolToSmiles(Chem.MolFromSmiles(smiles, sanitize=sanitize))
def get_data(random_state: int = 42, dataset: str = 'ALDH1'):
# read smiles from file and canonicalize them
with open(os.path.join(ROOT_DIR, f'data/{dataset}/original/inactives... |
def canonicalize(smiles: str, sanitize: bool = True):
return Chem.MolToSmiles(Chem.MolFromSmiles(smiles, sanitize=sanitize))
def get_data(random_state: int = 42, dataset: str = 'ALDH1'):
# read smiles from file and canonicalize them
with open(os.path.join(ROOT_DIR, f'data/{dataset}/original/inactives... | if check_featurizability(smi): | 3 | 2023-11-10 08:53:40+00:00 | 2k |
yunik1004/SAiD | script/render.py | [
{
"identifier": "load_mesh",
"path": "said/util/mesh.py",
"snippet": "def load_mesh(mesh_path: str) -> trimesh.Trimesh:\n \"\"\"Load the mesh\n\n Parameters\n ----------\n filepath : str\n Path of the mesh file\n\n Returns\n -------\n trimesh.Trimesh\n Mesh object\n ... | import argparse
import os
import pathlib
import cv2
import numpy as np
from moviepy import editor as mpy
from said.util.mesh import load_mesh
from said.util.parser import parse_list
from said.util.blendshape import load_blendshape_coeffs
from rendering.render_visual import RendererObject, render_blendshape_coefficients | 1,256 | """Render the animation
"""
os.environ["PYOPENGL_PLATFORM"] = "egl"
def main() -> None:
"""Main function"""
default_data_dir = pathlib.Path(__file__).resolve().parent.parent / "data"
# Arguments
parser = argparse.ArgumentParser(description="Render the animation")
parser.add_argument(
"-... | """Render the animation
"""
os.environ["PYOPENGL_PLATFORM"] = "egl"
def main() -> None:
"""Main function"""
default_data_dir = pathlib.Path(__file__).resolve().parent.parent / "data"
# Arguments
parser = argparse.ArgumentParser(description="Render the animation")
parser.add_argument(
"-... | blendshape_coeffs = load_blendshape_coeffs(blendshape_coeffs_path).numpy() | 2 | 2023-11-03 06:38:51+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.