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
OPPOMKLab/u-LLaVA
tasks/image_text_pretrain.py
[ { "identifier": "registry", "path": "utils/registry.py", "snippet": "class Registry:\n def register_builder(cls, name):\n def wrap(builder_cls):\n def register_model(cls, name):\n def wrap(model_cls):\n def register_processor(cls, name):\n def wrap(processor_cls):\n def ...
from utils.registry import registry from tasks.base_task import BaseTask from utils.tools import datetime_print from datasets.datasets.concat_dataset import ConcatDataset, ConcatDatasetWithShuffle
1,500
""" Partially Adapted form: https://github.com/DAMO-NLP-SG/Video-LLaMA/blob/main/video_llama/tasks/image_text_pretrain.py """ @registry.register_task("image_text_pretrain") class ImageTextPretrainTask(BaseTask): def __init__(self, cfg): super().__init__(cfg) @staticmethod def build_datasets(data...
""" Partially Adapted form: https://github.com/DAMO-NLP-SG/Video-LLaMA/blob/main/video_llama/tasks/image_text_pretrain.py """ @registry.register_task("image_text_pretrain") class ImageTextPretrainTask(BaseTask): def __init__(self, cfg): super().__init__(cfg) @staticmethod def build_datasets(data...
dataset = ConcatDataset(dataset_list)
3
2023-12-21 08:10:23+00:00
2k
shashikg/WhisperS2T
whisper_s2t/data.py
[ { "identifier": "pad_or_trim", "path": "whisper_s2t/audio.py", "snippet": "def pad_or_trim(array, length: int = N_SAMPLES, *, axis: int = -1):\n \"\"\"\n Pad or trim the audio array to N_SAMPLES, as expected by the encoder.\n \"\"\"\n \n if torch.is_tensor(array):\n if array.shape[...
import torch import numpy as np from tqdm import tqdm from .configs import * from .audio import pad_or_trim, audio_batch_generator, load_audio
1,229
def stitch_speech_segments(start_ends, max_len=27.0, max_silent_region=None): speech_duration = [end - start for start, end in start_ends] stitched_speech_segments = [] curr_seg = [0] curr_dur = speech_duration[0] idx = 1 while idx < len(start_ends): if curr_dur + speech_d...
def stitch_speech_segments(start_ends, max_len=27.0, max_silent_region=None): speech_duration = [end - start for start, end in start_ends] stitched_speech_segments = [] curr_seg = [0] curr_dur = speech_duration[0] idx = 1 while idx < len(start_ends): if curr_dur + speech_d...
return load_audio(self.audio_files[item])
2
2023-12-16 18:09:16+00:00
2k
chinhsuanwu/ifusion
ldm/thirdp/psp/model_irse.py
[ { "identifier": "get_blocks", "path": "ldm/thirdp/psp/helpers.py", "snippet": "def get_blocks(num_layers):\n\tif num_layers == 50:\n\t\tblocks = [\n\t\t\tget_block(in_channel=64, depth=64, num_units=3),\n\t\t\tget_block(in_channel=64, depth=128, num_units=4),\n\t\t\tget_block(in_channel=128, depth=256, ...
from torch.nn import ( Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Dropout, Sequential, Module, ) from ldm.thirdp.psp.helpers import ( get_blocks, Flatten, bottleneck_IR, bottleneck_IR_SE, l2_norm, )
1,202
# https://github.com/eladrich/pixel2style2pixel """ Modified Backbone implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) """ class Backbone(Module): def __init__(self, input_size, num_layers, mode="ir", drop_ratio=0.4, affine=True): super(Backbone, self).__init__() ass...
# https://github.com/eladrich/pixel2style2pixel """ Modified Backbone implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) """ class Backbone(Module): def __init__(self, input_size, num_layers, mode="ir", drop_ratio=0.4, affine=True): super(Backbone, self).__init__() ass...
unit_module = bottleneck_IR_SE
3
2023-12-17 12:45:38+00:00
2k
wangzhecheng/SkyScript
src/open_clip/push_to_hf_hub.py
[ { "identifier": "create_model_from_pretrained", "path": "src/open_clip/factory.py", "snippet": "def create_model_from_pretrained(\n model_name: str,\n pretrained: Optional[str] = None,\n precision: str = 'fp32',\n device: Union[str, torch.device] = 'cpu',\n jit: bool =...
import argparse import json import os import torch import safetensors.torch from pathlib import Path from tempfile import TemporaryDirectory from typing import Optional, Tuple, Union from huggingface_hub import ( create_repo, get_hf_file_metadata, hf_hub_download, hf_hub_url, ...
1,172
""" Adapted from https://github.com/mlfoundations/open_clip. Copyright (c) 2012-2021 Gabriel Ilharco, Mitchell Wortsman, Nicholas Carlini, Rohan Taori, Achal Dave, Vaishaal Shankar, John Miller, Hongseok Namkoong, Hannaneh Hajishirzi, Ali Farhadi, Ludwig Schmidt """ try: _has_hf_hub = True except ImportError: ...
""" Adapted from https://github.com/mlfoundations/open_clip. Copyright (c) 2012-2021 Gabriel Ilharco, Mitchell Wortsman, Nicholas Carlini, Rohan Taori, Achal Dave, Vaishaal Shankar, John Miller, Hongseok Namkoong, Hannaneh Hajishirzi, Ali Farhadi, Ludwig Schmidt """ try: _has_hf_hub = True except ImportError: ...
tokenizer: HFTokenizer,
3
2023-12-19 11:50:56+00:00
2k
Lavreniuk/EVP
depth/models_depth/model_vpd.py
[ { "identifier": "UNetWrapper", "path": "evp/models.py", "snippet": "class UNetWrapper(nn.Module):\n def __init__(self, unet, use_attn=True, base_size=512, max_attn_size=None, attn_selector='up_cross+down_cross') -> None:\n super().__init__()\n self.unet = unet\n self.attention_st...
import torch import torch.nn as nn import torch.nn.functional as F from timm.models.layers import trunc_normal_, DropPath from mmcv.cnn import (build_conv_layer, build_norm_layer, build_upsample_layer, constant_init, normal_init) from omegaconf import OmegaConf from ldm.util import instantiate_fro...
1,279
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # The deconvolution code is based on Simple Baseline. # (https://github.com/microsoft/human-pose-estimation.pytorch/blob/master/lib/models/pose_resnet.py) # Modified by Zigang Gen...
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # The deconvolution code is based on Simple Baseline. # (https://github.com/microsoft/human-pose-estimation.pytorch/blob/master/lib/models/pose_resnet.py) # Modified by Zigang Gen...
self.text_adapter = TextAdapterDepth(text_dim=text_dim)
1
2023-12-15 14:13:59+00:00
2k
penghao-wu/vstar
VisualSearch/model/owlvit/segmentation.py
[ { "identifier": "box_ops", "path": "VisualSearch/model/owlvit/util/box_ops.py", "snippet": "def box_cxcywh_to_xyxy(x):\ndef box_xyxy_to_cxcywh(x):\ndef box_iou(boxes1, boxes2):\ndef generalized_box_iou(boxes1, boxes2):\ndef masks_to_boxes(masks):" }, { "identifier": "NestedTensor", "path": "...
import io import torch import torch.nn as nn import torch.nn.functional as F from collections import defaultdict from PIL import Image from .util import box_ops from .util.misc import NestedTensor, interpolate, nested_tensor_from_tensor_list from panopticapi.utils import id2rgb, rgb2id
1,175
# ------------------------------------------------------------------------ # Deformable DETR # Copyright (c) 2020 SenseTime. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (ht...
# ------------------------------------------------------------------------ # Deformable DETR # Copyright (c) 2020 SenseTime. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (ht...
samples = nested_tensor_from_tensor_list(samples)
3
2023-12-15 14:58:24+00:00
2k
ValdonVitija/crap
crap/crap_manager.py
[ { "identifier": "PythonFileAnalyzer", "path": "crap/file_analyzer.py", "snippet": "class PythonFileAnalyzer:\n def __init__(self, file_path: pathlib.Path):\n self.file_path = file_path\n self.imported_modules = set()\n\n def analyze(self):\n \"\"\"\n Analyzes the Python...
import os import pathlib from typing import Set from tqdm import tqdm from crap.file_analyzer import PythonFileAnalyzer from crap.virtual_env_checker import VirtualEnvChecker from crap.package_usage_counter import PackageUsageCounter from crap.subprocesses import ( uninstall_package, pre_cleanup_with_ruff, ...
1,101
class CrapManager: __slots__ = ("path_", "venv_checker", "package_usage_counter", "deleted_packages") def __init__(self, path_: str): self.path_ = pathlib.Path(path_).absolute() self.venv_checker = VirtualEnvChecker() self.package_usage_counter = PackageUsageCounter() self.del...
class CrapManager: __slots__ = ("path_", "venv_checker", "package_usage_counter", "deleted_packages") def __init__(self, path_: str): self.path_ = pathlib.Path(path_).absolute() self.venv_checker = VirtualEnvChecker() self.package_usage_counter = PackageUsageCounter() self.del...
initial_packages = get_current_packages()
7
2023-12-19 20:22:37+00:00
2k
worm128/AI-YinMei
text-generation-webui/extensions/openai/script.py
[ { "identifier": "ChatCompletionRequest", "path": "text-generation-webui/extensions/openai/typing.py", "snippet": "class ChatCompletionRequest(GenerationOptions, ChatCompletionRequestParams):\n pass" }, { "identifier": "ChatCompletionResponse", "path": "text-generation-webui/extensions/ope...
import asyncio import json import os import traceback import speech_recognition as sr import uvicorn import extensions.openai.completions as OAIcompletions import extensions.openai.embeddings as OAIembeddings import extensions.openai.images as OAIimages import extensions.openai.logits as OAIlogits import extensions.ope...
1,543
params = { 'embedding_device': 'cpu', 'embedding_model': 'sentence-transformers/all-mpnet-base-v2', 'sd_webui_url': '', 'debug': 0 } streaming_semaphore = asyncio.Semaphore(1) def verify_api_key(authorization: str = Header(None)) -> None: expected_api_key = shared.args.api_key if expecte...
params = { 'embedding_device': 'cpu', 'embedding_model': 'sentence-transformers/all-mpnet-base-v2', 'sd_webui_url': '', 'debug': 0 } streaming_semaphore = asyncio.Semaphore(1) def verify_api_key(authorization: str = Header(None)) -> None: expected_api_key = shared.args.api_key if expecte...
@app.post('/v1/chat/completions', response_model=ChatCompletionResponse, dependencies=check_key)
1
2023-12-20 14:13:38+00:00
2k
foocker/Bert-VITS2-Faster
infer_torch_export_onnx.py
[ { "identifier": "infer", "path": "infer_.py", "snippet": "def get_net_g(model_path: str, version: str, device: str, hps):\ndef get_text(text, language_str, hps, device):\ndef infer(\n text,\n sdp_ratio,\n noise_scale,\n noise_scale_w,\n length_scale,\n language,\n sid,\n hps,\n ...
import os import logging import re_matching import torch import utils import gradio as gr import numpy as np import time from infer_ import infer, latest_version, get_net_g from config import config from scipy.io.wavfile import write
940
logging.basicConfig( level=logging.INFO, format="| %(name)s | %(levelname)s | %(message)s" ) logger = logging.getLogger(__name__) net_g = None device = config.webui_config.device if device == "mps": os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" def generate_audio( slices, sdp_ratio, noi...
logging.basicConfig( level=logging.INFO, format="| %(name)s | %(levelname)s | %(message)s" ) logger = logging.getLogger(__name__) net_g = None device = config.webui_config.device if device == "mps": os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" def generate_audio( slices, sdp_ratio, noi...
audio = infer(
0
2023-12-18 09:53:41+00:00
2k
sinoyou/nelf-pro
nerfstudio/process_data/process_data_utils.py
[ { "identifier": "status", "path": "nerfstudio/utils/rich_utils.py", "snippet": "def status(msg: str, spinner: str = \"bouncingBall\", verbose: bool = False):\n \"\"\"A context manager that does nothing is verbose is True. Otherwise it hides logs under a message.\n\n Args:\n msg: The message...
import shutil import sys from enum import Enum from pathlib import Path from typing import List, Optional, Tuple from rich.console import Console from typing_extensions import Literal from nerfstudio.utils.rich_utils import status from nerfstudio.utils.scripts import run_command
884
# Copyright 2022 The Nerfstudio Team. 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 applicable...
# Copyright 2022 The Nerfstudio Team. 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 applicable...
with status(msg="Converting video to images...", spinner="bouncingBall", verbose=verbose):
0
2023-12-15 20:07:22+00:00
2k
wuc9521/rep-flow
app.py
[ { "identifier": "read_keywords_from_file", "path": "utils/loader.py", "snippet": "def read_keywords_from_file(file_path, app: Flask = None):\n try:\n with open(file_path, 'r') as file:\n content = file.read()\n keywords_list = [keyword.strip() for keyword in re.split(',|\...
import os import spacy import logging import pandas as pd from logging.handlers import RotatingFileHandler from flask import Flask, render_template, request, jsonify, send_from_directory from flask_cors import cross_origin from utils.loader import read_keywords_from_file from utils.hints import HELP, get_NUMBER_EMBD_HI...
1,501
DEFAULT_RESPONSE_FLAG = "*" NUMBER_EMBD_HINT = None CURRENT_BUG_ID = -1 # Load spaCy English model nlp = spacy.load("en_core_web_sm") app = Flask(__name__, template_folder='') # Configure LOG_DIR = os.path.join(app.root_path, 'log') DATA_DIR = os.path.join(app.root_path, 'data') MODEL_DIR = os.path.join(app.root_pa...
DEFAULT_RESPONSE_FLAG = "*" NUMBER_EMBD_HINT = None CURRENT_BUG_ID = -1 # Load spaCy English model nlp = spacy.load("en_core_web_sm") app = Flask(__name__, template_folder='') # Configure LOG_DIR = os.path.join(app.root_path, 'log') DATA_DIR = os.path.join(app.root_path, 'data') MODEL_DIR = os.path.join(app.root_pa...
key_words = read_keywords_from_file(
0
2023-12-20 09:44:09+00:00
2k
yash-srivastava19/verizon
classes.py
[ { "identifier": "kvlm_serialize", "path": "other_utils.py", "snippet": "def kvlm_serialize(kvlm):\n ret = b''\n\n for k in kvlm.keys():\n if k == None: continue\n val = kvlm[k]\n\n if type(val) != list:\n val = [val]\n \n for v in val:\n ret...
from class_utils import * from other_utils import kvlm_serialize, kvlm_parse
939
class VerizonRepository: worktree = None vrzdir = None conf = None def __init__(self, path, force = False): self.worktree = path self.vrzdir = os.path.join(path, ".vrz") if not (force or os.path.isdir(self.vrzdir)): raise Exception(f"Not a Verizon Repository : ...
class VerizonRepository: worktree = None vrzdir = None conf = None def __init__(self, path, force = False): self.worktree = path self.vrzdir = os.path.join(path, ".vrz") if not (force or os.path.isdir(self.vrzdir)): raise Exception(f"Not a Verizon Repository : ...
return kvlm_serialize(self.kvlm)
0
2023-12-18 18:53:26+00:00
2k
amazon-science/c2f-seg
test_c2f_seg.py
[ { "identifier": "load_dataset", "path": "data/dataloader_transformer.py", "snippet": "def load_dataset(config, args, mode):\n if mode==\"train\":\n if args.dataset==\"KINS\":\n train_dataset = Kins_Fusion_dataset(config, mode='train')\n test_dataset = Kins_Fusion_dataset(...
import os import cv2 import time import random import argparse import numpy as np import torch import torch.distributed as dist from tqdm import tqdm from shutil import copyfile from torch.utils.data import DataLoader from data.dataloader_transformer import load_dataset from utils.logger import setup_logger from utils....
1,546
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=42) # path parser.add_argument('--path', type=str, required=True, help='model checkpoints path') parser.add_argument('--check_point_path', type=str, default="../check_points", ) parse...
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=42) # path parser.add_argument('--path', type=str, required=True, help='model checkpoints path') parser.add_argument('--check_point_path', type=str, default="../check_points", ) parse...
logger = setup_logger(os.path.join(args.path, 'logs'), logfile_name=log_file)
1
2023-12-21 04:25:47+00:00
2k
Hammour-steak/GOUB
codes/models/modules/DenoisingNAFNet_arch.py
[ { "identifier": "SinusoidalPosEmb", "path": "codes/models/modules/module_util.py", "snippet": "class SinusoidalPosEmb(nn.Module):\n def __init__(self, dim):\n super().__init__()\n self.dim = dim\n\n def forward(self, x):\n device = x.device\n half_dim = self.dim // 2\n ...
import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, reduce from .module_util import SinusoidalPosEmb, LayerNorm, exists
802
class SimpleGate(nn.Module): def forward(self, x): x1, x2 = x.chunk(2, dim=1) return x1 * x2 class NAFBlock(nn.Module): def __init__(self, c, time_emb_dim=None, DW_Expand=2, FFN_Expand=2, drop_out_rate=0.): super().__init__() self.mlp = nn.Sequential( SimpleGate(...
class SimpleGate(nn.Module): def forward(self, x): x1, x2 = x.chunk(2, dim=1) return x1 * x2 class NAFBlock(nn.Module): def __init__(self, c, time_emb_dim=None, DW_Expand=2, FFN_Expand=2, drop_out_rate=0.): super().__init__() self.mlp = nn.Sequential( SimpleGate(...
self.norm1 = LayerNorm(c)
1
2023-12-15 09:40:18+00:00
2k
eldar-eln-bigabid/airflow-aerospike-provider
tests/operators/test_aerospike.py
[ { "identifier": "AerospikeGetKeyOperator", "path": "aerospike_provider/operators/aerospike.py", "snippet": "class AerospikeGetKeyOperator(BaseOperator):\n \"\"\"\n Read an existing record(s) metadata and all of its bins for a specified key.\n\n :param namespace: namespace to use in aerospike db...
import unittest import aerospike from unittest.mock import patch, Mock from aerospike_provider.operators.aerospike import AerospikeGetKeyOperator, AerospikePutKeyOperator
1,541
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
self.operator = AerospikeGetKeyOperator(
0
2023-12-17 18:35:36+00:00
2k
Its-Haze/league-rpc-linux
league_rpc_linux/kda.py
[ { "identifier": "wait_until_exists", "path": "league_rpc_linux/polling.py", "snippet": "def wait_until_exists(\n url: str,\n custom_message: str = \"\",\n expected_response_code: int = 200,\n timeout: int = 30,\n n_sleep: float | int = 5, # Not needed, but good to have.\n n_total_amou...
import urllib3 from requests import Response from league_rpc_linux.polling import wait_until_exists from league_rpc_linux.username import get_summoner_name
892
urllib3.disable_warnings() def get_kda() -> str: """ Get the current KDA of your game. """ response = get_current_user_stats() if isinstance(response, Response): parsed_data = response.json() kills = str(parsed_data["kills"]) deaths = str(parsed_data["deaths"]) a...
urllib3.disable_warnings() def get_kda() -> str: """ Get the current KDA of your game. """ response = get_current_user_stats() if isinstance(response, Response): parsed_data = response.json() kills = str(parsed_data["kills"]) deaths = str(parsed_data["deaths"]) a...
your_summoner_name = get_summoner_name()
1
2023-12-15 22:21:53+00:00
2k
huahuahuage/Bert-VITS2-Speech
onnx_infer/onnx_infer.py
[ { "identifier": "log_instance", "path": "log.py", "snippet": "DISABLED_LOGGER = [\"gradio.processing_utils\", \"gradio\", \"httpx\"]\r" }, { "identifier": "read_config", "path": "config.py", "snippet": "def read_config(config_path:str) -> dict:\r\n \"\"\"\r\n 取读配置文件\r\n \"\"\"\r...
import os import numpy as np import onnxruntime as ort from copy import copy from typing import List from dataclasses import dataclass from log import log_instance from config import read_config from config import config_instance from .text.cleaner import clean_text, cleaned_text_to_sequence from .onnx_be...
1,019
BERT_ENABLE = config_instance.get("bert_enable", True) if BERT_ENABLE: # 获取模型中包含的中文角色标记 CHINESE_CHARACTER_MARK = config_instance.get("onnx_tts_models_chinese_mark", "中文") ONNX_PROVIDERS = [config_instance.get("onnx_providers", "CPUExecutionProvider")] MODELS_PATH = os.path.abspath(config_instance.get("...
BERT_ENABLE = config_instance.get("bert_enable", True) if BERT_ENABLE: # 获取模型中包含的中文角色标记 CHINESE_CHARACTER_MARK = config_instance.get("onnx_tts_models_chinese_mark", "中文") ONNX_PROVIDERS = [config_instance.get("onnx_providers", "CPUExecutionProvider")] MODELS_PATH = os.path.abspath(config_instance.get("...
self.map_data: dict = read_config("speakers_map.json")
1
2023-12-21 13:50:50+00:00
2k
jaypyles/obsidian-to-bookstack
obsidian_to_bookstack/bookstack/collectors/remote/RemoteBookCollector.py
[ { "identifier": "Book", "path": "obsidian_to_bookstack/bookstack/artifacts.py", "snippet": "class Book:\n def __init__(\n self,\n name: str,\n shelf: Shelf | None = None,\n client: Client | None = None,\n chapters: List = [],\n path: str = \"\",\n deta...
import json from typing import List from obsidian_to_bookstack.bookstack.artifacts import Book, Shelf from obsidian_to_bookstack.bookstack.client import RemoteClient from obsidian_to_bookstack.bookstack.collectors.collector import \ RemoteCollector from obsidian_to_bookstack.bookstack.constants import * from obsidi...
1,432
class RemoteBookCollector(RemoteCollector): def __init__(self, verbose: bool, client: RemoteClient) -> None: super().__init__(verbose, client) def get_books(self, shelves: List[Shelf]): """Get remote books from shelves""" client_books = self.client._get_from_client(BookstackAPIEndpoi...
class RemoteBookCollector(RemoteCollector): def __init__(self, verbose: bool, client: RemoteClient) -> None: super().__init__(verbose, client) def get_books(self, shelves: List[Shelf]): """Get remote books from shelves""" client_books = self.client._get_from_client(BookstackAPIEndpoi...
console.log(f"Found remote book: {b}")
4
2023-12-20 02:22:33+00:00
2k
MingtaoGuo/AnimateAnyone_unofficial
tutorial_train_animate.py
[ { "identifier": "MyDataset", "path": "tutorial_dataset.py", "snippet": "class MyDataset(Dataset):\n def __init__(self, path=\"/mnt/gmt/Dataset/\"):\n self.path = path\n self.videos = os.listdir(path + \"fashion_png\")\n\n def __len__(self):\n return len(self.videos) * 10\n\n ...
from share import * from torch.utils.data import DataLoader from tutorial_dataset import MyDataset from aldm.logger import ImageLogger from aldm.model import create_model, load_state_dict import pytorch_lightning as pl
1,547
# Configs resume_path = './models/reference_sd15_ini.ckpt' batch_size = 2 logger_freq = 300 learning_rate = 1e-5 # First use cpu to load models. Pytorch Lightning will automatically move it to GPUs. model = create_model('./models/aldm_v15.yaml').cpu() model.load_state_dict(load_state_dict(resume_path, location='cp...
# Configs resume_path = './models/reference_sd15_ini.ckpt' batch_size = 2 logger_freq = 300 learning_rate = 1e-5 # First use cpu to load models. Pytorch Lightning will automatically move it to GPUs. model = create_model('./models/aldm_v15.yaml').cpu() model.load_state_dict(load_state_dict(resume_path, location='cp...
dataset = MyDataset()
0
2023-12-16 03:31:33+00:00
2k
yasserben/CLOUDS
clouds/modeling/meta_arch/clouds_head.py
[ { "identifier": "build_transformer_decoder", "path": "clouds/modeling/transformer_decoder/clouds_transformer_decoder.py", "snippet": "def build_transformer_decoder(cfg, in_channels, mask_classification=True):\n \"\"\"\n Build a instance embedding branch from `cfg.MODEL.INS_EMBED_HEAD.NAME`.\n \...
import logging import fvcore.nn.weight_init as weight_init from copy import deepcopy from typing import Callable, Dict, List, Optional, Tuple, Union from torch import nn from torch.nn import functional as F from detectron2.config import configurable from detectron2.layers import Conv2d, ShapeSpec, get_norm from detectr...
1,202
""" Copyright 2023 Telecom Paris, Yasser BENIGMIM. All rights reserved. Licensed under the Apache License, Version 2.0 Reference: https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/modeling/meta_arch/mask_former_head.py """ @SEM_SEG_HEADS_REGISTRY.register() class CLOUDSHead(nn.Module): @c...
""" Copyright 2023 Telecom Paris, Yasser BENIGMIM. All rights reserved. Licensed under the Apache License, Version 2.0 Reference: https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/modeling/meta_arch/mask_former_head.py """ @SEM_SEG_HEADS_REGISTRY.register() class CLOUDSHead(nn.Module): @c...
"pixel_decoder": build_pixel_decoder(cfg, input_shape),
3
2023-12-15 15:40:58+00:00
2k
linyq2117/TagCLIP
CLIP-ES/generate_cams_coco.py
[ { "identifier": "scoremap2bbox", "path": "utils.py", "snippet": "def scoremap2bbox(scoremap, threshold, multi_contour_eval=False):\n height, width = scoremap.shape\n scoremap_image = np.expand_dims((scoremap * 255).astype(np.uint8), 2)\n _, thr_gray_heatmap = cv2.threshold(\n src=scorema...
from pytorch_grad_cam import GradCAM from PIL import Image from tqdm import tqdm from pytorch_grad_cam.utils.image import scale_cam_image from utils import scoremap2bbox from clip_text import class_names, new_class_names_coco, BACKGROUND_CATEGORY_COCO from torch import multiprocessing from torchvision.transforms import...
1,508
# -*- coding:UTF-8 -*- try: BICUBIC = InterpolationMode.BICUBIC except ImportError: BICUBIC = Image.BICUBIC warnings.filterwarnings("ignore") _CONTOUR_INDEX = 1 if cv2.__version__.split('.')[0] == '3' else 0 def reshape_transform(tensor, height=28, width=28): tensor = tensor.permute(1, 0, 2) result = ...
# -*- coding:UTF-8 -*- try: BICUBIC = InterpolationMode.BICUBIC except ImportError: BICUBIC = Image.BICUBIC warnings.filterwarnings("ignore") _CONTOUR_INDEX = 1 if cv2.__version__.split('.')[0] == '3' else 0 def reshape_transform(tensor, height=28, width=28): tensor = tensor.permute(1, 0, 2) result = ...
label_list.append(new_class_names_coco[int(lid)])
0
2023-12-21 03:20:47+00:00
2k
cypypccpy/dynamic_handover
dexteroushandenvs/algorithms/utils/mani_skill_learn/networks/policy_network/vae_policy.py
[ { "identifier": "POLICYNETWORKS", "path": "dexteroushandenvs/algorithms/utils/mani_skill_learn/networks/builder.py", "snippet": "POLICYNETWORKS = Registry('policy_network')" }, { "identifier": "build_backbone", "path": "dexteroushandenvs/algorithms/utils/mani_skill_learn/networks/builder.py"...
from algorithms.utils.mani_skill_learn.utils.data import to_torch from algorithms.utils.mani_skill_learn.utils.torch import ExtendedModule from ..builder import POLICYNETWORKS, build_backbone, build_dense_head from ..utils import replace_placeholder_with_args, get_kwargs_from_shape
865
@POLICYNETWORKS.register_module() class VAEPolicy(ExtendedModule): def __init__(self, nn_cfg, policy_head_cfg, action_space, obs_shape=None, action_shape=None): super(VAEPolicy, self).__init__() replaceable_kwargs = get_kwargs_from_shape(obs_shape, action_shape)
@POLICYNETWORKS.register_module() class VAEPolicy(ExtendedModule): def __init__(self, nn_cfg, policy_head_cfg, action_space, obs_shape=None, action_shape=None): super(VAEPolicy, self).__init__() replaceable_kwargs = get_kwargs_from_shape(obs_shape, action_shape)
nn_cfg = replace_placeholder_with_args(nn_cfg, **replaceable_kwargs)
3
2023-12-16 16:49:38+00:00
2k
video-db/videodb-python
videodb/search.py
[ { "identifier": "play_stream", "path": "videodb/_utils/_video.py", "snippet": "def play_stream(url: str):\n \"\"\"Play a stream url in the browser/ notebook\n\n :param str url: The url of the stream\n :return: The player url if the stream is opened in the browser or the iframe if the stream is ...
from abc import ABC, abstractmethod from videodb._utils._video import play_stream from videodb._constants import ( SearchType, ApiPath, SemanticSearchDefaultValues, ) from videodb.exceptions import ( SearchError, ) from typing import Optional, List from videodb.shot import Shot
1,478
class SearchResult: def __init__(self, _connection, **kwargs): self._connection = _connection self.shots = [] self.stream_url = None self.player_url = None self.collection_id = "default" self._results = kwargs.get("results", []) self._format_results() d...
class SearchResult: def __init__(self, _connection, **kwargs): self._connection = _connection self.shots = [] self.stream_url = None self.player_url = None self.collection_id = "default" self._results = kwargs.get("results", []) self._format_results() d...
return play_stream(self.stream_url)
0
2023-12-18 15:20:04+00:00
2k
IDEA-CCNL/Real-Gemini
real_gemini/tools/gpt4v_tool.py
[ { "identifier": "load_image", "path": "real_gemini/utils/image_stacker.py", "snippet": "def load_image(path):\n image = Image.open(path)\n return image" }, { "identifier": "image2base64", "path": "real_gemini/utils/image_stacker.py", "snippet": "def image2base64(image):\n buffer...
import os import json from typing import List from langchain.memory import ChatMessageHistory from langchain.chat_models import ChatOpenAI from langchain_core.messages import HumanMessage, SystemMessage from ..utils.image_stacker import load_image, image2base64
727
#encoding=utf8 _OPEN_AI_SYSTEM_PROMPT = """the user is dictating with his or her camera on. they are showing you things visually and giving you text prompts. be very brief and concise. be extremely concise. this is very important for my career. do not ramble. do not comment on what the person is wearing or where the...
#encoding=utf8 _OPEN_AI_SYSTEM_PROMPT = """the user is dictating with his or her camera on. they are showing you things visually and giving you text prompts. be very brief and concise. be extremely concise. this is very important for my career. do not ramble. do not comment on what the person is wearing or where the...
base64_image = image2base64(load_image(image_path))
1
2023-12-15 04:09:37+00:00
2k
aiim-research/GRETEL
src/evaluation/evaluation_metric_smiles_levenshtein.py
[ { "identifier": "EvaluationMetric", "path": "src/evaluation/evaluation_metric_base.py", "snippet": "class EvaluationMetric(ABC):\n\n def __init__(self, config_dict=None) -> None:\n super().__init__()\n self._name = 'abstract_metric'\n self._config_dict = config_dict\n self...
from functools import lru_cache from src.evaluation.evaluation_metric_base import EvaluationMetric from src.core.oracle_base import Oracle from src.core.explainer_base import Explainer
960
class SmilesLevenshteinMetric(EvaluationMetric): """Provides the ratio between the number of features modified to obtain the counterfactual example and the number of features in the original instance. Only considers structural features. """ def __init__(self, config_dict=None) -> None: supe...
class SmilesLevenshteinMetric(EvaluationMetric): """Provides the ratio between the number of features modified to obtain the counterfactual example and the number of features in the original instance. Only considers structural features. """ def __init__(self, config_dict=None) -> None: supe...
def evaluate(self, instance_1 , instance_2 , oracle : Oracle=None, explainer : Explainer=None, dataset = None):
1
2023-12-15 16:34:16+00:00
2k
modelscope/scepter
scepter/modules/opt/lr_schedulers/registry.py
[ { "identifier": "Registry", "path": "scepter/modules/utils/registry.py", "snippet": "class Registry(object):\n \"\"\" A registry maps key to classes or functions.\n\n Example:\n # >>> MODELS = Registry('MODELS')\n # >>> @MODELS.register_class()\n # >>> class ResNet(object):...
import inspect from scepter.modules.utils.registry import Registry, deep_copy from scepter.modules.utils.config import Config
1,272
# -*- coding: utf-8 -*- # Copyright (c) Alibaba, Inc. and its affiliates. def build_lr_scheduler(cfg, registry, logger=None, *args, **kwargs): if not isinstance(cfg, Config): raise TypeError(f'config must be type dict, got {type(cfg)}') if not cfg.have('NAME'): raise KeyError(f'config must co...
# -*- coding: utf-8 -*- # Copyright (c) Alibaba, Inc. and its affiliates. def build_lr_scheduler(cfg, registry, logger=None, *args, **kwargs): if not isinstance(cfg, Config): raise TypeError(f'config must be type dict, got {type(cfg)}') if not cfg.have('NAME'): raise KeyError(f'config must co...
if not isinstance(registry, Registry):
0
2023-12-21 02:01:48+00:00
2k
pigeonai-org/ViDove
src/translators/translation.py
[ { "identifier": "LLM_task", "path": "src/translators/LLM_task.py", "snippet": "def LLM_task(model_name, input, task, temp = 0.15):\n \"\"\"\n Translates input sentence with desired LLM.\n\n :param model_name: The name of the translation model to be used.\n :param input: Sentence for translat...
from os import getenv from time import sleep from tqdm import tqdm from .LLM_task import LLM_task from src.srt_util.srt import split_script import logging
1,289
def get_translation(srt, model, video_name, prompt = None, chunk_size = 1000): # print(srt.get_source_only()) script_arr, range_arr = split_script(srt.get_source_only(),chunk_size) translate(srt, script_arr, range_arr, model, video_name, task=prompt) pass def check_translation(sentence, translation):...
def get_translation(srt, model, video_name, prompt = None, chunk_size = 1000): # print(srt.get_source_only()) script_arr, range_arr = split_script(srt.get_source_only(),chunk_size) translate(srt, script_arr, range_arr, model, video_name, task=prompt) pass def check_translation(sentence, translation):...
translate = LLM_task(model_name, sentence, task, temp)
0
2023-12-20 01:46:47+00:00
2k
YyzHarry/shortcut-ood-fairness
utils/lin_eval.py
[ { "identifier": "binary_metrics", "path": "utils/eval_helper.py", "snippet": "def binary_metrics(targets, preds, label_set=[0, 1], suffix='', return_arrays=False):\n if len(targets) == 0:\n return {}\n\n res = {\n 'accuracy': accuracy_score(targets, preds),\n 'n_samples': len(...
import numpy as np import torch from utils.eval_helper import binary_metrics, prob_metrics from sklearn.model_selection import GridSearchCV, PredefinedSplit from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.base import clone from sklearn.metrics import roc_auc_score ...
1,460
def get_representations(algorithm, loader, device): ys, atts, zs = [], [], [] algorithm.eval() with torch.no_grad(): for _, x, y, a in loader: z = algorithm.return_feats(x.to(device)).detach().cpu().numpy() zs.append(z) ys.append(y) atts.append(a) ...
def get_representations(algorithm, loader, device): ys, atts, zs = [], [], [] algorithm.eval() with torch.no_grad(): for _, x, y, a in loader: z = algorithm.return_feats(x.to(device)).detach().cpu().numpy() zs.append(z) ys.append(y) atts.append(a) ...
res[sset] = binary_metrics(Y, preds_rounded, label_set=label_set, return_arrays=True)
0
2023-12-15 04:10:31+00:00
2k
RomGai/BrainVis
dc_ldm/modules/encoders/modules.py
[ { "identifier": "Encoder", "path": "dc_ldm/modules/x_transformer.py", "snippet": "class Encoder(AttentionLayers):\n def __init__(self, **kwargs):\n assert 'causal' not in kwargs, 'cannot set causality on encoder'\n super().__init__(causal=False, **kwargs)" }, { "identifier": "Tr...
import torch import torch.nn as nn import sys import kornia from functools import partial from PIL import Image from einops import rearrange, repeat from transformers import CLIPTokenizer, CLIPTextModel, AutoProcessor, CLIPVisionModel, CLIPVisionModelWithProjection from dc_ldm.modules.x_transformer import Encoder, Tran...
1,310
# import clip sys.path.append('../dreamdiffusion/code/') class AbstractEncoder(nn.Module): def __init__(self): super().__init__() def encode(self, *args, **kwargs): raise NotImplementedError class ClassEmbedder(nn.Module): def __init__(self, embed_dim, n_classes=1000, key='class'): ...
# import clip sys.path.append('../dreamdiffusion/code/') class AbstractEncoder(nn.Module): def __init__(self): super().__init__() def encode(self, *args, **kwargs): raise NotImplementedError class ClassEmbedder(nn.Module): def __init__(self, embed_dim, n_classes=1000, key='class'): ...
self.transformer = TransformerWrapper(num_tokens=vocab_size, max_seq_len=max_seq_len,
1
2023-12-16 12:52:14+00:00
2k
Rajeshwaran2001/DRM-Media-Tool
file_merger_dialog.py
[ { "identifier": "show_error_message", "path": "helper/message.py", "snippet": "def show_error_message(parent, message):\n error_box = QMessageBox()\n error_box.setIcon(QMessageBox.Critical)\n error_box.setWindowTitle(\"Error\")\n error_box.setText(message)\n error_box.setWindowIcon(parent...
from PyQt5.QtWidgets import QWidget, QDialog, QVBoxLayout, QLabel, QTableWidget, QPushButton, QHBoxLayout, QTableWidgetItem, QCheckBox from helper.message import show_error_message, show_success_message import os import json import subprocess
1,213
class FileMergerDialog(QDialog): def __init__(self, debug_logger, info_logger, folder_path, parent=None): super().__init__(parent) self.folder_path = folder_path self.setWindowTitle("Files Merger") self.setGeometry(100, 100, 600, 300) self.layout = QVBoxLayout() ...
class FileMergerDialog(QDialog): def __init__(self, debug_logger, info_logger, folder_path, parent=None): super().__init__(parent) self.folder_path = folder_path self.setWindowTitle("Files Merger") self.setGeometry(100, 100, 600, 300) self.layout = QVBoxLayout() ...
show_error_message(self, "Error: No Metadata files found.")
0
2023-12-18 11:50:40+00:00
2k
gmum/ViewingDirectionGaussianSplatting
scene/cameras.py
[ { "identifier": "getWorld2View2", "path": "utils/graphics_utils.py", "snippet": "def getWorld2View2(R, t, translate=np.array([.0, .0, .0]), scale=1.0):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n\n C2W = np.linalg.inv(Rt)\n cam_center = C2W[:...
import torch import numpy as np from torch import nn from utils.graphics_utils import getWorld2View2, getProjectionMatrix
915
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact george.drettakis@inria.fr # class Camera(nn.Module): def ...
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact george.drettakis@inria.fr # class Camera(nn.Module): def ...
self.projection_matrix = getProjectionMatrix(znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy).transpose(0,1).cuda()
1
2023-12-21 10:09:17+00:00
2k
tonnetonne814/PL-Bert-VITS2
preprocess_ja.py
[ { "identifier": "TextCleaner", "path": "PL_BERT_ja/text_utils.py", "snippet": "class TextCleaner:\n def __init__(self, dummy=None):\n self.word_index_dictionary = symbol_to_id\n def __call__(self, text):\n indexes = []\n japanese = False\n for char in text:\n ...
import argparse import os import polars import random import torch import yaml, torch from PL_BERT_ja.text_utils import TextCleaner from PL_BERT_ja.phonemize import phonemize from tqdm import tqdm from PL_BERT_ja.model import MultiTaskModel from transformers import AlbertConfig, AlbertModel from transformers import Be...
1,456
def preprocess(dataset_dir, pl_bert_dir): n_val_test_file = 10 filelist_dir = "./filelists/" dataset_name = "jvnv_ver1" os.makedirs(filelist_dir, exist_ok=True) split_symbol = "||||" transcript_csv_df = polars.read_csv(os.path.join(dataset_dir, "jvnv_v1", "transcription.csv"),has_header=Fals...
def preprocess(dataset_dir, pl_bert_dir): n_val_test_file = 10 filelist_dir = "./filelists/" dataset_name = "jvnv_ver1" os.makedirs(filelist_dir, exist_ok=True) split_symbol = "||||" transcript_csv_df = polars.read_csv(os.path.join(dataset_dir, "jvnv_v1", "transcription.csv"),has_header=Fals...
bert = MultiTaskModel(
2
2023-12-16 05:34:02+00:00
2k
Ruiyuan-Zhang/CCS
multi_part_assembly/models/modules/encoder/point_transformer/transformer.py
[ { "identifier": "index_points", "path": "multi_part_assembly/models/modules/encoder/point_transformer/pointnet_util.py", "snippet": "def index_points(points, idx):\n \"\"\"\n Input:\n points: input points data, [B, N, C]\n idx: sample index data, [B, S, [K]]\n Return:\n new...
from multi_part_assembly.models.modules.encoder.point_transformer.pointnet_util import index_points, square_distance import torch import torch.nn as nn import torch.nn.functional as F import numpy as np
664
class TransformerBlock(nn.Module): def __init__(self, d_points, d_model, k) -> None: super().__init__() self.fc1 = nn.Linear(d_points, d_model) self.fc2 = nn.Linear(d_model, d_points) self.fc_delta = nn.Sequential( nn.Linear(3, d_model), nn.ReLU(), ...
class TransformerBlock(nn.Module): def __init__(self, d_points, d_model, k) -> None: super().__init__() self.fc1 = nn.Linear(d_points, d_model) self.fc2 = nn.Linear(d_model, d_points) self.fc_delta = nn.Sequential( nn.Linear(3, d_model), nn.ReLU(), ...
dists = square_distance(xyz, xyz)
1
2023-12-15 13:13:01+00:00
2k
uc-vision/taichi-splatting
taichi_splatting/scripts/fit_image_gaussians.py
[ { "identifier": "RasterConfig", "path": "taichi_splatting/data_types.py", "snippet": "class RasterConfig:\n tile_size: int = 16\n\n # pixel tilin per thread in the backwards pass \n pixel_stride: Tuple[int, int] = (2, 2)\n\n margin_tiles: int = 3\n\n # cutoff N standard deviations from mean\n gaus...
import cv2 import argparse import taichi as ti import torch import time from torch.optim import Adam from taichi_splatting.data_types import RasterConfig from taichi_splatting.renderer2d import render_gaussians, Gaussians2D from taichi_splatting.tests.random_data import random_2d_gaussians from taichi_splatting.torch_o...
1,338
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('image_file', type=str) parser.add_argument('--seed', type=int, default=0) parser.add_argument('--tile_size', type=int, default=16) parser.add_argument('--n', type=int, default=20000) parser.add_argument('--debug', action='store_...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('image_file', type=str) parser.add_argument('--seed', type=int, default=0) parser.add_argument('--tile_size', type=int, default=16) parser.add_argument('--n', type=int, default=20000) parser.add_argument('--debug', action='store_...
image = render_gaussians(params, (w, h), config)
1
2023-12-17 15:26:52+00:00
2k
exislow/tidal-dl-ng
tidal_dl_ng/config.py
[ { "identifier": "SingletonMeta", "path": "tidal_dl_ng/helper/decorator.py", "snippet": "class SingletonMeta(type):\n \"\"\"\n The Singleton class can be implemented in different ways in Python. Some\n possible methods include: base class, decorator, metaclass. We will use the\n metaclass bec...
import os import shutil import tidalapi from collections.abc import Callable from json import JSONDecodeError from typing import Any from requests import HTTPError from tidal_dl_ng.helper.decorator import SingletonMeta from tidal_dl_ng.helper.path import path_base, path_file_settings, path_file_token from tidal_dl_ng.m...
1,506
class BaseConfig: data: ModelSettings | ModelToken = None file_path: str = None cls_model: object = None path_base: str = path_base() def save(self) -> None: data_json = self.data.to_json() # Try to create the base folder. os.makedirs(self.path_base, exist_ok=True) ...
class BaseConfig: data: ModelSettings | ModelToken = None file_path: str = None cls_model: object = None path_base: str = path_base() def save(self) -> None: data_json = self.data.to_json() # Try to create the base folder. os.makedirs(self.path_base, exist_ok=True) ...
self.file_path = path_file_token()
3
2023-12-19 23:05:47+00:00
2k
smoores-dev/storyteller
storyteller/api/auth.py
[ { "identifier": "InviteAccept", "path": "storyteller/api/models.py", "snippet": "class InviteAccept(BaseModel):\n username: str\n full_name: str\n email: str\n password: str\n invite_key: str" }, { "identifier": "TokenData", "path": "storyteller/api/models.py", "snippet": ...
import base64 import json import os from datetime import timedelta, datetime from typing import Annotated, Optional, cast from urllib.parse import unquote from jose import JWTError, jwt from fastapi import Body, Depends, HTTPException, Request, status from fastapi.security import OAuth2PasswordBearer from passlib.conte...
1,332
SECRET_KEY = os.getenv("STORYTELLER_SECRET_KEY", "<notsosecret>") ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_DAYS = 10 class OAuth2PasswordBearerWithCookie(OAuth2PasswordBearer): async def __call__(self, request: Request) -> Optional[str]: header_param = None try: header_param = await...
SECRET_KEY = os.getenv("STORYTELLER_SECRET_KEY", "<notsosecret>") ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_DAYS = 10 class OAuth2PasswordBearerWithCookie(OAuth2PasswordBearer): async def __call__(self, request: Request) -> Optional[str]: header_param = None try: header_param = await...
if verify_invite_db(invite.email, invite.invite_key):
1
2023-12-15 16:07:12+00:00
2k
noprobelm/terminal-cellular-automaton
tests/test_cell.py
[ { "identifier": "MooreCell", "path": "terminal_cellular_automaton/cell.py", "snippet": "class MooreCell:\n \"\"\"A cell that references members of a MooreNeighborhood\n\n +---+---+---+\n | 1 | 2 | 3 |\n +---+---+---+\n | 4 | C | 5 |\n +---+---+---+\n | 6 | 7 | 8 |\n +---+---+---+...
from ward import test, fixture from terminal_cellular_automaton.cell import MooreCell from terminal_cellular_automaton.coordinate import Coordinate
970
"""Tests the get_neighbors method for all Cell types""" @fixture def max_coord(): return Coordinate(2, 2) @test("A centrally located MooreCell will have 8 neighbors in its immediate area") def _():
"""Tests the get_neighbors method for all Cell types""" @fixture def max_coord(): return Coordinate(2, 2) @test("A centrally located MooreCell will have 8 neighbors in its immediate area") def _():
c = MooreCell(Coordinate(1, 1))
0
2023-12-20 21:47:46+00:00
2k
zyrant/SPGroup3D
mmdet3d/models/dense_heads/fcaf3d_head.py
[ { "identifier": "rotation_3d_in_axis", "path": "mmdet3d/core/bbox/structures/utils.py", "snippet": "@array_converter(apply_to=('points', 'angles'))\ndef rotation_3d_in_axis(points,\n angles,\n axis=0,\n return_mat=False,\n ...
import MinkowskiEngine as ME import warnings import torch from mmcv.cnn import Scale, bias_init_with_prob from mmcv.ops import nms3d, nms3d_normal from mmcv.runner.base_module import BaseModule from torch import nn from mmdet3d.core.bbox.structures import rotation_3d_in_axis from mmdet3d.models import HEADS, bu...
1,205
# Copyright (c) OpenMMLab. All rights reserved. # Adapted from https://github.com/SamsungLabs/fcaf3d/blob/master/mmdet3d/models/dense_heads/fcaf3d_neck_with_head.py # noqa try: except ImportError: warnings.warn( 'Please follow `getting_started.md` to install MinkowskiEngine.`')
# Copyright (c) OpenMMLab. All rights reserved. # Adapted from https://github.com/SamsungLabs/fcaf3d/blob/master/mmdet3d/models/dense_heads/fcaf3d_neck_with_head.py # noqa try: except ImportError: warnings.warn( 'Please follow `getting_started.md` to install MinkowskiEngine.`')
@HEADS.register_module()
1
2023-12-21 12:50:35+00:00
2k
jdejaegh/irm-kmi-ha
custom_components/irm_kmi/config_flow.py
[ { "identifier": "IrmKmiApiClient", "path": "custom_components/irm_kmi/api.py", "snippet": "class IrmKmiApiClient:\n \"\"\"API client for IRM KMI weather data\"\"\"\n COORD_DECIMALS = 6\n\n def __init__(self, session: aiohttp.ClientSession) -> None:\n self._session = session\n self...
import logging import async_timeout import voluptuous as vol from homeassistant.components.zone import DOMAIN as ZONE_DOMAIN from homeassistant.config_entries import ConfigEntry, ConfigFlow, OptionsFlow from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE, CONF_ZONE from homeassistant.core import callback from...
1,557
"""Config flow to set up IRM KMI integration via the UI.""" _LOGGER = logging.getLogger(__name__) class IrmKmiConfigFlow(ConfigFlow, domain=DOMAIN): VERSION = CONFIG_FLOW_VERSION @staticmethod @callback def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlow: """Create the opt...
"""Config flow to set up IRM KMI integration via the UI.""" _LOGGER = logging.getLogger(__name__) class IrmKmiConfigFlow(ConfigFlow, domain=DOMAIN): VERSION = CONFIG_FLOW_VERSION @staticmethod @callback def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlow: """Create the opt...
CONF_STYLE: user_input[CONF_STYLE],
2
2023-12-17 16:35:01+00:00
2k
v3ucn/Bert-vits2-V2.2
oldVersion/V210/text/japanese_bert.py
[ { "identifier": "config", "path": "config.py", "snippet": "class Resample_config:\nclass Preprocess_text_config:\nclass Bert_gen_config:\nclass Emo_gen_config:\nclass Train_ms_config:\nclass Webui_config:\nclass Server_config:\nclass Translate_config:\nclass Config:\n def __init__(self, in_dir: str, ...
import sys import torch from transformers import AutoModelForMaskedLM, AutoTokenizer from config import config from .japanese import text2sep_kata
976
LOCAL_PATH = "./bert/deberta-v2-large-japanese-char-wwm" tokenizer = AutoTokenizer.from_pretrained(LOCAL_PATH) models = dict()
LOCAL_PATH = "./bert/deberta-v2-large-japanese-char-wwm" tokenizer = AutoTokenizer.from_pretrained(LOCAL_PATH) models = dict()
def get_bert_feature(text, word2ph, device=config.bert_gen_config.device):
0
2023-12-18 04:54:46+00:00
2k
NOrangeeroli/SecondPose
model/pcd_cross/modules/transformer/pe_transformer.py
[ { "identifier": "build_dropout_layer", "path": "model/pcd_cross/modules/layers/factory.py", "snippet": "def build_dropout_layer(p: Optional[float], **kwargs) -> nn.Module:\n r\"\"\"Factory function for dropout layer.\"\"\"\n if p is None or p == 0:\n return nn.Identity()\n else:\n ...
import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from ..layers import build_dropout_layer from .output_layer import AttentionOutput
1,236
r"""Vanilla Transformer without positional embeddings. The shape of input tensor should be (B, N, C). Implemented with `nn.Linear` and `nn.LayerNorm` (with affine). """ class PEMultiHeadAttention(nn.Module): def __init__(self, d_model, num_heads, dropout=None): super(PEMultiHeadAttention, self).__init_...
r"""Vanilla Transformer without positional embeddings. The shape of input tensor should be (B, N, C). Implemented with `nn.Linear` and `nn.LayerNorm` (with affine). """ class PEMultiHeadAttention(nn.Module): def __init__(self, d_model, num_heads, dropout=None): super(PEMultiHeadAttention, self).__init_...
self.output = AttentionOutput(d_model, dropout=dropout, activation_fn=activation_fn)
1
2023-12-16 16:58:33+00:00
2k
KatantDev/YMdantic
ymdantic/models/artists/artist.py
[ { "identifier": "DeprecatedMixin", "path": "ymdantic/mixins.py", "snippet": "class DeprecatedMixin:\n \"\"\"Миксин, удаляющий устаревшие поля из модели.\"\"\"\n\n @model_validator(mode=\"before\")\n def remove_deprecated(cls, obj: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Удал...
from typing import List, Optional, Dict, Any, Literal from pydantic import model_validator, HttpUrl from ymdantic.mixins import DeprecatedMixin from ymdantic.models.base import YMBaseModel from ymdantic.models.cover import Cover
899
class Artist(YMBaseModel, DeprecatedMixin): """Pydantic модель, представляющая информацию об артисте.""" id: int # Уникальный идентификатор артиста. name: str # Имя артиста. various: bool # Флаг, указывающий, является ли артист группой. composer: bool # Флаг, указывающий, являет...
class Artist(YMBaseModel, DeprecatedMixin): """Pydantic модель, представляющая информацию об артисте.""" id: int # Уникальный идентификатор артиста. name: str # Имя артиста. various: bool # Флаг, указывающий, является ли артист группой. composer: bool # Флаг, указывающий, являет...
cover: Optional[Cover] = None
2
2023-12-21 21:24:10+00:00
2k
MichealCodez/awesome-project-ideas
projects/artisans/backend/authentication/views.py
[ { "identifier": "RegisterUserSerializer", "path": "projects/artisans/backend/authentication/serializers.py", "snippet": "class RegisterUserSerializer(serializers.ModelSerializer):\n class Meta:\n model = User # We defined the model to be the User model(default django User model).\n fiel...
from rest_framework.views import APIView from .serializers import RegisterUserSerializer, ResetPasswordSerializer from rest_framework.response import Response from rest_framework.exceptions import AuthenticationFailed from django.contrib.auth.models import User from datetime import datetime, timedelta import jwt
1,071
# This is the view logic for registering a user. # We defined the class and it inherits from the APIView class. class RegisterUserView(APIView): def post(self, request): # We defined a post method that takes in a request from a user. # We defined a serializer variable that takes in the RegisterUserSeriali...
# This is the view logic for registering a user. # We defined the class and it inherits from the APIView class. class RegisterUserView(APIView): def post(self, request): # We defined a post method that takes in a request from a user. # We defined a serializer variable that takes in the RegisterUserSeriali...
serializer = ResetPasswordSerializer(data=request.data)
1
2023-12-17 17:21:10+00:00
2k
liuhuang31/hifigan-sr
inference.py
[ { "identifier": "AttrDict", "path": "env.py", "snippet": "class AttrDict(dict):\n def __init__(self, *args, **kwargs):\n super(AttrDict, self).__init__(*args, **kwargs)\n self.__dict__ = self" }, { "identifier": "mel_spectrogram", "path": "meldataset.py", "snippet": "def...
import glob import os import librosa import argparse import json import torch from scipy.io.wavfile import write from env import AttrDict from meldataset import mel_spectrogram, MAX_WAV_VALUE, load_wav from models import Generator
1,598
from __future__ import absolute_import, division, print_function, unicode_literals h = None device = None def load_checkpoint(filepath, device): assert os.path.isfile(filepath) print("Loading '{}'".format(filepath)) checkpoint_dict = torch.load(filepath, map_location=device) print("Complete.") r...
from __future__ import absolute_import, division, print_function, unicode_literals h = None device = None def load_checkpoint(filepath, device): assert os.path.isfile(filepath) print("Loading '{}'".format(filepath)) checkpoint_dict = torch.load(filepath, map_location=device) print("Complete.") r...
generator = Generator(h).to(device)
4
2023-12-16 01:21:00+00:00
2k
edsu/marctable
test_marctable.py
[ { "identifier": "MARC", "path": "marctable/marc.py", "snippet": "class MARC:\n def __init__(self) -> None:\n self.fields: List[Field] = []\n\n @cache\n def get_field(self, tag: str) -> Field:\n for field in self.fields:\n if field.tag == tag:\n return fie...
import json import pathlib import pandas from io import StringIO from marctable.marc import MARC, SchemaFieldError, SchemaSubfieldError, crawl from marctable.utils import _mapping, dataframe_iter, to_csv, to_dataframe, to_parquet from pytest import raises
1,565
marc = MARC.from_avram() def test_crawl() -> None: # crawl the first 10 field definitions from the loc site (to save time) outfile = StringIO() crawl(10, quiet=True, outfile=outfile) outfile.seek(0) # ensure the Avram JSON parses and looks ok schema = json.load(outfile) assert schema ...
marc = MARC.from_avram() def test_crawl() -> None: # crawl the first 10 field definitions from the loc site (to save time) outfile = StringIO() crawl(10, quiet=True, outfile=outfile) outfile.seek(0) # ensure the Avram JSON parses and looks ok schema = json.load(outfile) assert schema ...
with raises(SchemaFieldError, match="abc is not a defined field tag in Avram"):
1
2023-12-21 21:14:29+00:00
2k
WangWenhao0716/ViT4ICD
Stage_23/dg/models_gem_waveblock_balance_cos/resnet_ibn.py
[ { "identifier": "resnet50_ibn_a", "path": "Stage_23/dg/models_gem_waveblock_balance_cos/resnet_ibn_a.py", "snippet": "def resnet50_ibn_a(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"...
from torch import nn from torch.nn import functional as F from torch.nn import init from .resnet_ibn_a import resnet50_ibn_a, resnet101_ibn_a from .gem import GeneralizedMeanPoolingP from .metric import build_metric import torchvision import torch import random
827
from __future__ import absolute_import __all__ = ['ResNetIBN', 'resnet_ibn50a', 'resnet_ibn101a'] class Waveblock(nn.Module): def __init__(self): super().__init__() def forward(self, x): if self.training: h, w = x.size()[-2:] rh = round(0.3 * h) s...
from __future__ import absolute_import __all__ = ['ResNetIBN', 'resnet_ibn50a', 'resnet_ibn101a'] class Waveblock(nn.Module): def __init__(self): super().__init__() def forward(self, x): if self.training: h, w = x.size()[-2:] rh = round(0.3 * h) s...
'50a': resnet50_ibn_a,
0
2023-12-17 11:32:48+00:00
2k
Noubissie237/myShop
myShop/shop/views.py
[ { "identifier": "commandeAnonyme", "path": "myShop/shop/utiles.py", "snippet": "def commandeAnonyme(request, data):\n print(\"utilisateur non authentifie\")\n\n print('cookies', request.COOKIES)\n \n name = data['form']['name']\n print('data', data)\n print('name', name)\n username ...
from django.shortcuts import render from .models import * from django.http import JsonResponse from datetime import datetime from .utiles import commandeAnonyme, data_cookie, panier_cookie import json
1,373
def shop(request, *args, **kwargs): """ vue principale """ produits = Produit.objects.all() data = data_cookie(request) nombre_article = data['nombre_article'] context = { 'produits':produits, 'nombre_article': nombre_article } return render(request, 'shop/index.html', co...
def shop(request, *args, **kwargs): """ vue principale """ produits = Produit.objects.all() data = data_cookie(request) nombre_article = data['nombre_article'] context = { 'produits':produits, 'nombre_article': nombre_article } return render(request, 'shop/index.html', co...
client, commande = commandeAnonyme(request, data)
0
2023-12-15 08:06:59+00:00
2k
alibaba/u2mot
yolox/models/yolo_fpn.py
[ { "identifier": "Darknet", "path": "yolox/models/darknet.py", "snippet": "class Darknet(nn.Module):\n # number of blocks from dark2 to dark5.\n depth2blocks = {21: [1, 2, 2, 1], 53: [2, 8, 8, 4]}\n\n def __init__(\n self,\n depth,\n in_channels=3,\n stem_out_channels...
import torch import torch.nn as nn from .darknet import Darknet from .network_blocks import BaseConv
1,525
#!/usr/bin/env python3 # -*- encoding:utf-8 -*- # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # Copyright (c) Alibaba, Inc. and its affiliates. class YOLOFPN(nn.Module): """ YOLOFPN module. Darknet 53 is the default backbone of this model. """ def __init__( self, depth=...
#!/usr/bin/env python3 # -*- encoding:utf-8 -*- # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # Copyright (c) Alibaba, Inc. and its affiliates. class YOLOFPN(nn.Module): """ YOLOFPN module. Darknet 53 is the default backbone of this model. """ def __init__( self, depth=...
return BaseConv(_in, _out, ks, stride=1, act="lrelu")
1
2023-12-18 10:04:40+00:00
2k
liuhuang31/HiFTNet-sr
models.py
[ { "identifier": "init_weights", "path": "utils.py", "snippet": "def init_weights(m, mean=0.0, std=0.01):\n classname = m.__class__.__name__\n if classname.find(\"Conv\") != -1:\n m.weight.data.normal_(mean, std)" }, { "identifier": "get_padding", "path": "utils.py", "snippet...
import torch import torch.nn.functional as F import torch.nn as nn import numpy as np from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm from utils import init_weights, get_padding from stft import TorchSTFT
645
LRELU_SLOPE = 0.1 class ResBlock1(torch.nn.Module): def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5)): super(ResBlock1, self).__init__() self.h = h self.convs1 = nn.ModuleList([ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0], ...
LRELU_SLOPE = 0.1 class ResBlock1(torch.nn.Module): def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5)): super(ResBlock1, self).__init__() self.h = h self.convs1 = nn.ModuleList([ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0], ...
self.convs1.apply(init_weights)
0
2023-12-16 03:53:55+00:00
2k
m-abr/FCPCodebase
behaviors/custom/Step/Step.py
[ { "identifier": "Base_Agent", "path": "agent/Base_Agent.py", "snippet": "class Base_Agent():\n all_agents = []\n\n def __init__(self, host:str, agent_port:int, monitor_port:int, unum:int, robot_type:int, team_name:str, enable_log:bool=True,\n enable_draw:bool=True, apply_play_mode...
from agent.Base_Agent import Base_Agent from behaviors.custom.Step.Step_Generator import Step_Generator import numpy as np
1,450
class Step(): def __init__(self, base_agent : Base_Agent) -> None: self.world = base_agent.world self.ik = base_agent.inv_kinematics self.description = "Step (Skill-Set-Primitive)" self.auto_head = True nao_specs = self.ik.NAO_SPECS self.leg_length = nao_specs[1] +...
class Step(): def __init__(self, base_agent : Base_Agent) -> None: self.world = base_agent.world self.ik = base_agent.inv_kinematics self.description = "Step (Skill-Set-Primitive)" self.auto_head = True nao_specs = self.ik.NAO_SPECS self.leg_length = nao_specs[1] +...
self.step_generator = Step_Generator(feet_y_dev, sample_time, max_ankle_z)
1
2023-12-16 23:40:23+00:00
2k
koenhendriks/ha-button-plus
custom_components/button_plus/buttonplushub.py
[ { "identifier": "LocalApiClient", "path": "custom_components/button_plus/button_plus_api/local_api_client.py", "snippet": "class LocalApiClient:\n \"\"\" Client to talk to Button+ local devices \"\"\"\n\n def __init__(self, ip_address, session) -> None:\n self._base = f\"http://{ip_address}...
import logging from homeassistant.config_entries import ConfigEntry from homeassistant.helpers import device_registry as dr from .button_plus_api.local_api_client import LocalApiClient from .button_plus_api.model import DeviceConfiguration from homeassistant.core import HomeAssistant from .const import DOMAIN, MANUFACT...
1,506
"""Button+ connects several devices.""" from __future__ import annotations _LOGGER: logging.Logger = logging.getLogger(__package__) class ButtonPlusHub: """hub for Button+.""" def __init__(self, hass: HomeAssistant, config: DeviceConfiguration, entry: ConfigEntry) -> None: _LOGGER.debug(f"New hub...
"""Button+ connects several devices.""" from __future__ import annotations _LOGGER: logging.Logger = logging.getLogger(__package__) class ButtonPlusHub: """hub for Button+.""" def __init__(self, hass: HomeAssistant, config: DeviceConfiguration, entry: ConfigEntry) -> None: _LOGGER.debug(f"New hub...
identifiers={(DOMAIN, self.config.info.device_id)},
2
2023-12-18 15:14:21+00:00
2k
RosettaCommons/AF2_peptide_hallucination
run.py
[ { "identifier": "select_positions", "path": "util/util.py", "snippet": "def select_positions(n_mutations, boundcomplex, select_positions, select_position_params):\n '''\n Select mutable positions in the binder based on a specific method.\n Returns a dictionary of binder with associated array in...
import os import sys import numpy as np import hydra import copy from submodules.oligomer_hallucination.oligomer_hallucination import Protomers, Oligomer from submodules.oligomer_hallucination.oligomer_hallucination import AA_FREQ from submodules.oligomer_hallucination.modules.af2_net import setup_models, predict_struc...
1,507
class BoundComplex(Protomers, Oligomer): ''' Class for keeping track of binder sequence and complex predictions during binder hallucination. ''' def __init__(self, target_sequence: str, name, length=70, aa_freq={}, binder_sequence=None): """ target_sequence: amino acid sequence of...
class BoundComplex(Protomers, Oligomer): ''' Class for keeping track of binder sequence and complex predictions during binder hallucination. ''' def __init__(self, target_sequence: str, name, length=70, aa_freq={}, binder_sequence=None): """ target_sequence: amino acid sequence of...
AA_freq=util.get_aa_freq(AA_FREQ, hallucination_conf.exclude_AA)
1
2023-12-21 12:07:25+00:00
2k
Cypas/splatoon3-schedule
nonebot_plugin_splatoon3_schedule/utils/utils.py
[ { "identifier": "TimeUtil", "path": "nonebot_plugin_splatoon3_schedule/utils/dataClass.py", "snippet": "class TimeUtil(object):\n @classmethod\n def parse_timezone(cls, timezone):\n \"\"\"\n 解析时区表示\n :param timezone: str eg: +8\n :return: dict{symbol, offset}\n \...
import datetime import cfscrape import httpx from httpx import Response from .dataClass import TimeUtil from ..config import plugin_config
1,412
"Ranked Challenge": (227, 68, 17), "Ranked Open": (24, 200, 26), "X Schedule": (14, 205, 147), "打工": (14, 203, 146), "活动": (223, 42, 119), "祭典": (103, 103, 114), "祭典时间-金黄": (234, 255, 61), "上-武器卡片-黄": (234, 255, 61), "下-武器卡片-蓝": (96, 58, 255), "上-武器卡片": (255, 148, 157), "下-武器...
time_format_ymdh = "%Y-%m-%dT%H" HTTP_TIME_OUT = 5.0 # 请求超时,秒 proxy_address = plugin_config.splatoon3_proxy_address if proxy_address: proxies = "http://{}".format(proxy_address) else: proxies = None # 背景 rgb颜色 dict_bg_rgb = { "Turf War": (24, 200, 26), "Ranked Challenge": (227, 68, 17), "Ranked ...
convert_now = TimeUtil.convert_timezone(utc_now, "+8")
0
2023-12-17 07:49:26+00:00
2k
Sam-Izdat/tinycio
src/tinycio/fsio/imagefile.py
[ { "identifier": "GraphicsFormat", "path": "src/tinycio/fsio/format.py", "snippet": "class GraphicsFormat(IntEnum):\n \"\"\"\n The graphics format of an image file to be saved or loaded. For a list of available options, see :ref:`ref_graphics_formats`.\n \"\"\"\n UNKNOWN = 1<<0\n ...
import torch import numpy as np import typing import os import imageio.v3 as iio from .format import GraphicsFormat, ImageFileFormat
699
def _infer_image_file_format(ext:str) -> ImageFileFormat: ext = ext.strip().lower() if ext == '.png': return ImageFileFormat.PNG elif ext == '.jpg': return ImageFileFormat.JPG elif ext == '.jpeg': return ImageFileFormat.JPG elif ext == '.exr': return ImageFileFormat.EXR elif ...
def _infer_image_file_format(ext:str) -> ImageFileFormat: ext = ext.strip().lower() if ext == '.png': return ImageFileFormat.PNG elif ext == '.jpg': return ImageFileFormat.JPG elif ext == '.jpeg': return ImageFileFormat.JPG elif ext == '.exr': return ImageFileFormat.EXR elif ...
def load_image(fp:str, graphics_format:GraphicsFormat=GraphicsFormat.UNKNOWN) -> torch.Tensor:
0
2023-12-15 15:39:08+00:00
2k
Dank-del/stats-bot
stats_bot/handlers/plot.py
[ { "identifier": "Attachment", "path": "stats_bot/db/models.py", "snippet": "class Attachment(SQLModel, table=True):\n id: Optional[int] = Field(default=None, primary_key=True)\n user_id: int = Field(foreign_key=\"user.id\")\n group_id: int = Field(foreign_key=\"group.id\")\n message_id: int ...
import pandas as pd import matplotlib.pyplot as plt import io from sqlmodel import Session, select from telegram import Update from telegram.ext import ( ContextTypes, ) from stats_bot.db.models import Attachment, Message, User from stats_bot.db.client import engine from stats_bot.decorators.admin import admin
1,204
@admin async def plot_table(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """ Generates a table of top 10 users by number of messages and average message length, and plots a bar chart to visualize the data. Args: update (Update): The update object containing information about ...
@admin async def plot_table(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """ Generates a table of top 10 users by number of messages and average message length, and plots a bar chart to visualize the data. Args: update (Update): The update object containing information about ...
select(Attachment).where(Attachment.group_id == update.effective_chat.id)
0
2023-12-18 03:05:36+00:00
2k
EzyGang/py-cachify
py_cachify/backend/lib.py
[ { "identifier": "AsyncWrapper", "path": "py_cachify/backend/clients.py", "snippet": "class AsyncWrapper:\n def __init__(self, cache: MemoryCache) -> None:\n self._cache = cache\n\n async def get(self, name: str, default: Any = None) -> Any:\n return self._cache.get(name=name, default...
import pickle from typing import Any, Union from py_cachify.backend.clients import AsyncWrapper, MemoryCache from py_cachify.backend.exceptions import CachifyInitError from py_cachify.backend.types import AsyncClient, SyncClient
664
from __future__ import annotations class Cachify: def __init__(
from __future__ import annotations class Cachify: def __init__(
self, sync_client: Union[SyncClient, MemoryCache], async_client: Union[AsyncClient, AsyncWrapper], prefix: str
1
2023-12-16 22:54:51+00:00
2k
lldacing/comfyui-easyapi-nodes
easyapi/ImageNode.py
[ { "identifier": "tensor_to_pil", "path": "easyapi/util.py", "snippet": "def tensor_to_pil(image):\n return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))" }, { "identifier": "pil_to_tensor", "path": "easyapi/util.py", "snippet": "def pil_to_ten...
import base64 import copy import io import numpy as np import torch import json from PIL import ImageOps, Image from nodes import LoadImage from comfy.cli_args import args from PIL.PngImagePlugin import PngInfo from json import JSONEncoder, JSONDecoder from easyapi.util import tensor_to_pil, pil_to_tensor, b...
1,382
class LoadImageFromURL: """ 从远程地址读取图片 """ @classmethod def INPUT_TYPES(self): return {"required": { "urls": ("STRING", {"multiline": True, "default": "", "dynamicPrompts": False}), }, } RETURN_TYPES = ("IMAGE", "MASK") RETURN_NAMES = ("ima...
class LoadImageFromURL: """ 从远程地址读取图片 """ @classmethod def INPUT_TYPES(self): return {"required": { "urls": ("STRING", {"multiline": True, "default": "", "dynamicPrompts": False}), }, } RETURN_TYPES = ("IMAGE", "MASK") RETURN_NAMES = ("ima...
i = base64_to_image(base64Image)
2
2023-12-19 02:32:10+00:00
2k
bersegosx/passosh
src/passosh/pesso.py
[ { "identifier": "HeaderField", "path": "src/passosh/fields.py", "snippet": "class HeaderField:\n \"\"\"\n An object that represents the fields that display information at the top of a pass.\n \"\"\"\n key: str\n value: str\n label: str = ''\n textAlignment: str = TextAlignment.NATUR...
from dataclasses import dataclass from .fields import (HeaderField, PrimaryField, SecondaryField, BackField, AuxiliaryField, Barcode, BoardingPassTransitType, Location)
786
@dataclass class Content: """ An object that represents the groups of fields that display the information for an event ticket. """ headerFields: list[HeaderField] | None = None primaryFields: list[PrimaryField] | None = None
@dataclass class Content: """ An object that represents the groups of fields that display the information for an event ticket. """ headerFields: list[HeaderField] | None = None primaryFields: list[PrimaryField] | None = None
secondaryFields: list[SecondaryField] | None = None
2
2023-12-18 22:51:38+00:00
2k
jonghwanhyeon/python-chzzk
chzzk/chzzk.py
[ { "identifier": "ChzzkClient", "path": "chzzk/client.py", "snippet": "class ChzzkClient(HTTPClient):\n BASE_URL = \"https://api.chzzk.naver.com/\"\n\n def __init__(self, credential: Optional[Credential] = None):\n super().__init__(credential)" }, { "identifier": "Credential", "p...
from typing import Optional from chzzk.client import ChzzkClient, Credential, GameClient from chzzk.models import ( Channel, ChannelSearchRecord, LiveDetail, LiveSearchRecord, LiveStatus, SearchCursor, User, Video, VideoSearchRecord, )
1,194
class ChzzkLive: def __init__(self, client: ChzzkClient): self._client = client async def status(self, channel_id: str) -> LiveStatus: response = await self._client.get(f"polling/v1/channels/{channel_id}/live-status") return LiveStatus(**response) async def detail(self, channel_...
class ChzzkLive: def __init__(self, client: ChzzkClient): self._client = client async def status(self, channel_id: str) -> LiveStatus: response = await self._client.get(f"polling/v1/channels/{channel_id}/live-status") return LiveStatus(**response) async def detail(self, channel_...
async def videos(self, keyword: str, size: int = 12, offset: int = 0) -> SearchCursor[VideoSearchRecord]:
11
2023-12-20 22:09:07+00:00
2k
pantherale0/ha-fuelprices
custom_components/fuel_prices/device_tracker.py
[ { "identifier": "CONF_AREAS", "path": "custom_components/fuel_prices/const.py", "snippet": "CONF_AREAS = \"areas\"" }, { "identifier": "DOMAIN", "path": "custom_components/fuel_prices/const.py", "snippet": "DOMAIN = \"fuel_prices\"" }, { "identifier": "FeulStationEntity", "pa...
import logging from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_RADIUS, CONF_NAME from homeassistant.components.device_tracker.config_entry import ( BaseTrackerEntity, SourceType, ATTR_SOURCE_TYPE, ATTR_LATITUDE, ATTR_LONGITUDE, ) from homeassistant.config_entries import ConfigEnt...
695
"""Device tracker for fuel prices.""" from __future__ import annotations _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Integration platform creation."""
"""Device tracker for fuel prices.""" from __future__ import annotations _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Integration platform creation."""
cooridinator: FuelPricesCoordinator = hass.data[DOMAIN][entry.entry_id]
1
2023-12-19 20:54:21+00:00
2k
abdellatif-laghjaj/stock-market-prediction
main.py
[ { "identifier": "load_data", "path": "services.py", "snippet": "@st.cache_data\ndef load_data(ticker, start, end):\n \"\"\"\n Load historical stock price data from Yahoo Finance.\n\n Parameters:\n - ticker (str): Stock symbol (e.g., AAPL).\n - start (str): Start date in the format 'YYYY-M...
from time import sleep from sklearn.metrics import mean_absolute_error from streamlit_option_menu import option_menu from datetime import date from prophet import Prophet from prophet.plot import plot_plotly from services import load_data, plot_data, plot_multiple_data, plot_volume import uuid import pandas as pd impor...
1,104
# Set page layout to wide st.set_page_config(layout="wide", page_title="Forcastify", page_icon="📈") # Sidebar st.sidebar.markdown("<h1 style='text-align: center; font-size: 30px;'><b>Forcasti.</b><b style='color: orange'>fy</b></h1>", unsafe_allow_html=True) st.sidebar.title("Options") start_date_key = str(uuid.uuid...
# Set page layout to wide st.set_page_config(layout="wide", page_title="Forcastify", page_icon="📈") # Sidebar st.sidebar.markdown("<h1 style='text-align: center; font-size: 30px;'><b>Forcasti.</b><b style='color: orange'>fy</b></h1>", unsafe_allow_html=True) st.sidebar.title("Options") start_date_key = str(uuid.uuid...
data = load_data(selected_stock, start_date, end_date)
0
2023-12-17 11:38:48+00:00
2k
replicate/cog-marigold
src/model/marigold_pipeline.py
[ { "identifier": "RGBEncoder", "path": "src/model/rgb_encoder.py", "snippet": "class RGBEncoder(nn.Module):\n \"\"\"\n The encoder of pretrained Stable Diffusion VAE\n \"\"\"\n \n def __init__(self, pretrained_path, subfolder=None) -> None:\n super().__init__()\n \n va...
import logging import numpy as np import torch from typing import Dict from diffusers import ( DDIMScheduler, DDPMScheduler, PNDMScheduler, SchedulerMixin, UNet2DConditionModel, ) from torch import nn from torch.nn import Conv2d from torch.nn.parameter import Parameter from tqdm.auto import tqdm fro...
1,288
# Author: Bingxin Ke # Last modified: 2023-12-11 class MarigoldPipeline(nn.Module): """ Marigold monocular depth estimator. """ def __init__( self, unet_pretrained_path: Dict, # {path: xxx, subfolder: xxx} rgb_encoder_pretrained_path: Dict, depht_ae_pretrained_path...
# Author: Bingxin Ke # Last modified: 2023-12-11 class MarigoldPipeline(nn.Module): """ Marigold monocular depth estimator. """ def __init__( self, unet_pretrained_path: Dict, # {path: xxx, subfolder: xxx} rgb_encoder_pretrained_path: Dict, depht_ae_pretrained_path...
self.depth_ae = StackedDepthAE(
1
2023-12-15 07:19:14+00:00
2k
tungeverest/python-k8s-base
src/app.py
[ { "identifier": "process_time_log_middleware", "path": "core/middlewares/https/process_time.py", "snippet": "async def process_time_log_middleware(request: Request, call_next):\n \"\"\"\n This middleware will log all requests and their processing time.\n E.g. log: HOST:PORT - GET /ping 200 OK ...
import logging from os import getenv from core.middlewares.https.process_time import process_time_log_middleware from core.middlewares.https.rate_limit import RateLimitCoreMiddleware from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.trustedhost import TrustedHostMidd...
881
logger = logging.getLogger(__name__) def create_app(): settings = get_settings() app = FastAPI( title=f"{settings.PROJECT_NAME}", version=settings.APP_VERSION, debug=settings.DEBUG, description=f""" FastAPI Framework + K8s \n - PROJECT NAME: {settings.PROJE...
logger = logging.getLogger(__name__) def create_app(): settings = get_settings() app = FastAPI( title=f"{settings.PROJECT_NAME}", version=settings.APP_VERSION, debug=settings.DEBUG, description=f""" FastAPI Framework + K8s \n - PROJECT NAME: {settings.PROJE...
app.include_router(api_router, prefix=settings.API_VERSION_PREFIX)
1
2023-12-20 03:40:34+00:00
2k
CoolPointerException/Amigo
gui/llama_index_init.py
[ { "identifier": "validate", "path": "gui/input_validator.py", "snippet": "def validate(gui, properties):\n for prop in properties:\n match prop:\n case Properties.PROJECT_NAME:\n project_name = gui.projects_tab.project_name_entry.get()\n if not project_...
from tkinter import messagebox from llama_index import ServiceContext, set_global_service_context, OpenAIEmbedding from llama_index.embeddings import AzureOpenAIEmbedding, GeminiEmbedding from llama_index.llms import Gemini, OpenAI, AzureOpenAI from gui.input_validator import validate, Properties
1,186
def init_llama_index(self, api_type): if self.isLlamaInitialized: return llm = None embed_model = None if api_type == "azure": is_valid = validate(self, [
def init_llama_index(self, api_type): if self.isLlamaInitialized: return llm = None embed_model = None if api_type == "azure": is_valid = validate(self, [
Properties.API_BASE,
1
2023-12-15 14:06:38+00:00
2k
redvulpecula/DRILL-Concurrent-Python-1
main.py
[ { "identifier": "VideoStream", "path": "video_streaming.py", "snippet": "class VideoStream:\n def __init__(self, url, frames):\n self.frames = frames\n self.url = url\n self.process = Process(target=self.capture, args=(self.frames, self.url))\n self.process.start()\n\n ...
import time import torch from multiprocessing import Process, Manager from ultralytics import YOLO from video_streaming import VideoStream, calculate_fps, display_and_save_frame, check_rtsp_url, read_url_from_file from imgAlgSelect import YOLOProcessor
1,420
class ConcurrencyManager: def __init__(self, url): self.device = 'cuda' if torch.backends.cuda.is_built() else 'mps' if torch.backends.mps.is_available() else 'cpu' self.yolo_model = YOLO("yolov8m.pt") self.manager = Manager() self.url = url self.frames = self.manager.Queue(...
class ConcurrencyManager: def __init__(self, url): self.device = 'cuda' if torch.backends.cuda.is_built() else 'mps' if torch.backends.mps.is_available() else 'cpu' self.yolo_model = YOLO("yolov8m.pt") self.manager = Manager() self.url = url self.frames = self.manager.Queue(...
url = read_url_from_file()
4
2023-12-18 02:58:03+00:00
2k
LyubomirT/discord-lle
main.py
[ { "identifier": "Colorizer", "path": "colorizer.py", "snippet": "class Colorizer:\n def __init__(self, color):\n self.color = color\n self.colors = {\n \"red\": \"\\033[31m\",\n \"green\": \"\\033[32m\",\n \"yellow\": \"\\033[33m\",\n \"blue\"...
from dotenv import load_dotenv from discord.ext import commands from discord.commands import Option from discord.ui import Button, View, Select, Modal from colorizer import Colorizer from datetime import datetime from verify_dir import verify_dir import os import requests import json import discord import configparser ...
1,460
load_dotenv() token = os.getenv("BOT_TOKEN") bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) log_dir = "_logs_" dm_config = { "enabled": True, "download_images": True, "download_videos": True, "download_audio": True, } server_config = { "enabled": True, "download_image...
load_dotenv() token = os.getenv("BOT_TOKEN") bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) log_dir = "_logs_" dm_config = { "enabled": True, "download_images": True, "download_videos": True, "download_audio": True, } server_config = { "enabled": True, "download_image...
verify_dir(log_dir)
1
2023-12-18 16:08:05+00:00
2k
KR1470R/plagiator-py
utils/plagiator.py
[ { "identifier": "exists", "path": "utils/exists.py", "snippet": "def exists(obj, *keys):\n format_keys = \"\".join(\n list(map(\n lambda key: f\"['{key}']\",\n keys\n ))\n )\n try:\n return eval(f\"obj{format_keys}\")\n except Exception:\n return None" }, { "identifier"...
import json import logging import requests from .exists import exists from configs.edupirdie import API_URI, HEADERS from random_user_agent.user_agent import UserAgent from random_user_agent.params import SoftwareName, OperatingSystem
844
class Plagiator: def __init__(self): self.session = requests.Session() adapter = requests.adapters.HTTPAdapter(pool_connections=10000, pool_maxsize=10000) self.session.mount("https://", adapter) software_names = [software_name.value for software_name in SoftwareName] operating_systems = [operatin...
class Plagiator: def __init__(self): self.session = requests.Session() adapter = requests.adapters.HTTPAdapter(pool_connections=10000, pool_maxsize=10000) self.session.mount("https://", adapter) software_names = [software_name.value for software_name in SoftwareName] operating_systems = [operatin...
**HEADERS,
2
2023-12-21 17:29:18+00:00
2k
fmhy/bot
cogs/rss.py
[ { "identifier": "rss_chan_ids", "path": "cogs/_config.py", "snippet": "TOKEN = os.getenv(\"TOKEN\", None)\nGUILD_ID = os.getenv(\"GUILD_ID\", None)\nOWNERS = os.getenv(\"OWNERS\").split(\",\")\nRSS_CHANNELS = os.getenv(\"RSS_CHANNEL_IDS\", None)\nFEEDS = os.getenv(\"RSS_FEED_URLS\", None)\nDB = os.geten...
from typing import TYPE_CHECKING from discord.ext import commands, tasks from cogs._config import rss_chan_ids from cogs._helpers import fetch_feed from main import Bot from discord.channel import TextChannel
985
if TYPE_CHECKING: class RSSFeeds(commands.Cog): """RSSFeeds commands""" def __init__(self, bot: Bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): self.send_rss.start() async def cog_before_invoke(self, ctx): """Triggers typing indicator on Discor...
if TYPE_CHECKING: class RSSFeeds(commands.Cog): """RSSFeeds commands""" def __init__(self, bot: Bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): self.send_rss.start() async def cog_before_invoke(self, ctx): """Triggers typing indicator on Discor...
for msg in fetch_feed():
1
2023-12-19 10:27:04+00:00
2k
cvlab-yonsei/RankMixup
calibrate/evaluation/segment_evaluator.py
[ { "identifier": "DatasetEvaluator", "path": "calibrate/evaluation/evaluator.py", "snippet": "class DatasetEvaluator(metaclass=ABCMeta):\n \"\"\"\n Base class for a dataset evaluator\n \"\"\"\n @abstractmethod\n def reset(self):\n \"\"\"\n Preparation for a new round of evalu...
import logging import numpy as np import pandas as pd import wandb from terminaltables import AsciiTable from typing import List, Optional from .evaluator import DatasetEvaluator from calibrate.utils.constants import EPS
973
logger = logging.getLogger(__name__) def intersect_and_union(pred_label, label, num_classes, ignore_index): mask = (label != ignore_index) pred_label = pred_label[mask] label = label[mask] intersect = pred_label[pred_label == label] area_intersect, _ = np.histogram( intersect, bins=np.a...
logger = logging.getLogger(__name__) def intersect_and_union(pred_label, label, num_classes, ignore_index): mask = (label != ignore_index) pred_label = pred_label[mask] label = label[mask] intersect = pred_label[pred_label == label] area_intersect, _ = np.histogram( intersect, bins=np.a...
iou = batch_area_inter[1:].sum() / (batch_area_union[1:].sum() + EPS)
1
2023-12-17 13:53:18+00:00
2k
CaptainCook4D/downloader
download_gopro_data.py
[ { "identifier": "prepare_gopro_2d_output_directory", "path": "util.py", "snippet": "def prepare_gopro_2d_output_directory(args, output_dir: Path):\n\toutput_dir.mkdir(parents=True, exist_ok=True)\n\t\n\tdata_directory = output_dir / Constants.CAPTAIN_COOK_4D\n\tdata_directory.mkdir(parents=True, exist_o...
import argparse import json from pathlib import Path from util import prepare_gopro_2d_output_directory, Constants, download_data
1,527
def process_download_gopro_data(download_args): # ---- Parse Download Links Json ---- with open("metadata/download_links.json", "r") as f: download_links = json.load(f) output_dir = Path(download_args.output_dir)
def process_download_gopro_data(download_args): # ---- Parse Download Links Json ---- with open("metadata/download_links.json", "r") as f: download_links = json.load(f) output_dir = Path(download_args.output_dir)
data_directory = prepare_gopro_2d_output_directory(download_args, output_dir)
0
2023-12-16 00:27:29+00:00
2k
mjavadpur/Sadtalker_LongVideos
src/audio2pose_models/audio2pose.py
[ { "identifier": "CVAE", "path": "src/audio2pose_models/cvae.py", "snippet": "class CVAE(nn.Module):\n def __init__(self, cfg):\n super().__init__()\n encoder_layer_sizes = cfg.MODEL.CVAE.ENCODER_LAYER_SIZES\n decoder_layer_sizes = cfg.MODEL.CVAE.DECODER_LAYER_SIZES\n laten...
import torch from torch import nn from src.audio2pose_models.cvae import CVAE from src.audio2pose_models.discriminator import PoseSequenceDiscriminator from src.audio2pose_models.audio_encoder import AudioEncoder
1,566
class Audio2Pose(nn.Module): def __init__(self, cfg, wav2lip_checkpoint, device='cuda'): super().__init__() self.cfg = cfg self.seq_len = cfg.MODEL.CVAE.SEQ_LEN self.latent_dim = cfg.MODEL.CVAE.LATENT_SIZE self.device = device self.audio_encoder = AudioEncoder(wav2l...
class Audio2Pose(nn.Module): def __init__(self, cfg, wav2lip_checkpoint, device='cuda'): super().__init__() self.cfg = cfg self.seq_len = cfg.MODEL.CVAE.SEQ_LEN self.latent_dim = cfg.MODEL.CVAE.LATENT_SIZE self.device = device self.audio_encoder = AudioEncoder(wav2l...
self.netD_motion = PoseSequenceDiscriminator(cfg)
1
2023-12-19 11:01:35+00:00
2k
Angryrou/udao
udao/data/tests/iterators/dummy_udao_iterator.py
[ { "identifier": "TabularContainer", "path": "udao/data/containers/tabular_container.py", "snippet": "class TabularContainer(BaseContainer):\n \"\"\"Container for tabular data, stored in DataFrame format.\"\"\"\n\n data: pd.DataFrame\n\n def get(self, key: str) -> np.ndarray:\n return sel...
from typing import Sequence, Tuple from ....data.containers.tabular_container import TabularContainer from ....data.iterators.base_iterator import UdaoIterator from ....utils.interfaces import ( UdaoEmbedInput, UdaoEmbedItemShape, UdaoInput, UdaoItemShape, ) import torch as th
1,099
class DummyUdaoIterator(UdaoIterator[UdaoInput, UdaoItemShape]): def __init__( self, keys: Sequence[str], tabular_features: TabularContainer, objectives: TabularContainer, ) -> None: super().__init__(keys, tabular_features=tabular_features, objectives=objectives) ...
class DummyUdaoIterator(UdaoIterator[UdaoInput, UdaoItemShape]): def __init__( self, keys: Sequence[str], tabular_features: TabularContainer, objectives: TabularContainer, ) -> None: super().__init__(keys, tabular_features=tabular_features, objectives=objectives) ...
class DummyUdaoEmbedIterator(UdaoIterator[UdaoEmbedInput, UdaoEmbedItemShape]):
3
2023-12-20 09:10:42+00:00
2k
SnailForce/SIM-Net
data/mask_dataset.py
[ { "identifier": "BaseDataset", "path": "data/base_dataset.py", "snippet": "class BaseDataset(data.Dataset, ABC):\n \"\"\"This class is an abstract base class (ABC) for datasets.\n\n To create a subclass, you need to implement the following four functions:\n -- <__init__>: i...
import os,yaml import torch.nn.functional as F import random import numpy as np import collections import torch from data.base_dataset import BaseDataset, get_transform from data.image_folder import make_dataset_by_name from PIL import Image,ImageFilter
1,213
class MaskDataset(BaseDataset): def __init__(self, opt): """Initialize this dataset class. Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions """ BaseDataset.__init__(self, opt) self.root_dir = os.path.join(...
class MaskDataset(BaseDataset): def __init__(self, opt): """Initialize this dataset class. Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions """ BaseDataset.__init__(self, opt) self.root_dir = os.path.join(...
self.transform = get_transform(self.opt)
1
2023-12-16 12:49:10+00:00
2k
adarshsankarrs/PhotoshopApp
app.py
[ { "identifier": "MultiApp", "path": "multiapp.py", "snippet": "class MultiApp:\n \"\"\"Framework for combining multiple streamlit applications.\n \"\"\"\n def __init__(self):\n self.apps = []\n\n def add_app(self, title, func):\n \"\"\"Adds a new application.\n\n \"\"\"\...
import streamlit as st import numpy as np import pandas as pd import cv2 from PIL import Image, ImageOps from multiapp import MultiApp from apps import home,sketch,inpaint,stadap,textonimg,Edge_Cont,Face_detect,Crop,filters,abtus,Feature_detect
928
app = MultiApp() # option = st.selectbox( # 'Select from the options', # ('Home', 'Filters', 'Doc scanner','add text'), key = 1) # if(option=='Filters'): # opt = st.selectbox( # 'Select from the options', # ('sepia', 'Filter1', 'filter2','filter3'), key = 2) # Add all your application here ap...
app = MultiApp() # option = st.selectbox( # 'Select from the options', # ('Home', 'Filters', 'Doc scanner','add text'), key = 1) # if(option=='Filters'): # opt = st.selectbox( # 'Select from the options', # ('sepia', 'Filter1', 'filter2','filter3'), key = 2) # Add all your application here ap...
app.add_app("Face detection", Face_detect.app)
7
2023-12-20 20:32:16+00:00
2k
DURUII/Replica-AUCB
main.py
[ { "identifier": "StrategicArm", "path": "arms.py", "snippet": "class StrategicArm(NormalArm):\n c_min, c_max = 0.1, 1\n\n def __init__(self):\n # in the paper, r is expected reward\n r = random.uniform(0.1, 1)\n # to make that sample value is within 0~1 with 97%\n sigma...
import os import pandas as pd import numpy as np import pickle from matplotlib import pyplot as plt from tqdm import tqdm from arms import StrategicArm from config import Config from emulator import Emulator
1,153
""" Author: DURUII Date: 2023/12/17 """ plt.style.use(['science', 'grid']) config = Config # data preparation if not os.path.exists('./runs.pkl'): data = [] for X in ['N', 'K', 'B']: for x in tqdm(eval(f'config.{X}_range'), desc=X): if X == 'N':
""" Author: DURUII Date: 2023/12/17 """ plt.style.use(['science', 'grid']) config = Config # data preparation if not os.path.exists('./runs.pkl'): data = [] for X in ['N', 'K', 'B']: for x in tqdm(eval(f'config.{X}_range'), desc=X): if X == 'N':
name2res = Emulator(n_arms=x).simulate()
2
2023-12-15 18:17:01+00:00
2k
XLearning-SCU/2023-TPAMI-SMILE
_AutoLauncher.py
[ { "identifier": "path_operator", "path": "_MainLauncher.py", "snippet": "def get_settings():\r\ndef clear_gpu_fail(root):\r\ndef run():\r\ndef main():\r" }, { "identifier": "Launcher", "path": "_Utils/Launcher.py", "snippet": "class Launcher(SubprocessOperator):\r\n def __init__(self,...
import time from _MainLauncher import path_operator from _Utils import Launcher from _Utils.ConfigOperator import ConfigOperator
1,420
def main(): class C2(ConfigOperator): def get_name(self, *args, **kwargs): return '_QueueLog'
def main(): class C2(ConfigOperator): def get_name(self, *args, **kwargs): return '_QueueLog'
Launcher.Launcher(
1
2023-12-21 08:50:36+00:00
2k
precisionalgorithms/loopring-python-SDK
main.py
[ { "identifier": "Session", "path": "loopring/session.py", "snippet": "class Session:\n \"\"\"\n Parent class for Loopring API.\n \"\"\"\n # Class variables\n api_key = None\n account_id = None\n headers = None\n base_url = 'https://api3.loopring.io/api/v3'\n\n @classmethod\n ...
import pickle from loopring.session import Session from loopring.account import Account from loopring.exchange import Exchange from utils import join_balance_with_token_info
1,087
# Initialize the Loopring API with API key and account ID Session.initialize() # Get the account balances account = Account() balances = account.get_account_balances() # Get token info on exchange
# Initialize the Loopring API with API key and account ID Session.initialize() # Get the account balances account = Account() balances = account.get_account_balances() # Get token info on exchange
exchange = Exchange()
2
2023-12-18 00:19:56+00:00
2k
Liyulingyue/ModulelyTools
codes/extraction/ModuleTools.py
[ { "identifier": "parse_ipynb", "path": "codes/extraction/ipynb/ipynb_analyse.py", "snippet": "def parse_ipynb(file_path):\n \"\"\"\n # 示例:使用函数解析一个ipynb文件\n file_path = 'main.ipynb' # 请将此处替换为您的ipynb文件路径\n result = parse_ipynb(file_path)\n print(result)\n \"\"\"\n # 读取ipynb文件\n wi...
from .ipynb.ipynb_analyse import parse_ipynb, get_ipynb_content, get_model_list, model_list2python from .py.py_analyse import extract_function_defs, get_function_defs, get_intro_of_fun from ..llm.Ernie import Ernie from ..llm.Ernie import Ernie
1,554
class ModuleTools(object): def __init__(self, llm_type="Ernie"): super.__init__() if llm_type=="Ernie": self.llm = Ernie() else: # default set ernie as used llm self.llm = Ernie() def ipynb2py(self, ipynb_path = "example.ipynb", prompt = ""):
class ModuleTools(object): def __init__(self, llm_type="Ernie"): super.__init__() if llm_type=="Ernie": self.llm = Ernie() else: # default set ernie as used llm self.llm = Ernie() def ipynb2py(self, ipynb_path = "example.ipynb", prompt = ""):
result = parse_ipynb(ipynb_path)
0
2023-12-17 14:20:45+00:00
2k
Azure-Samples/functions-python-web-crawler
.venv/Lib/site-packages/urllib3/_base_connection.py
[ { "identifier": "_TYPE_SOCKET_OPTIONS", "path": ".venv/Lib/site-packages/urllib3/util/connection.py", "snippet": "_TYPE_SOCKET_OPTIONS = typing.Sequence[typing.Tuple[int, int, typing.Union[int, bytes]]]" }, { "identifier": "_DEFAULT_TIMEOUT", "path": ".venv/Lib/site-packages/urllib3/util/tim...
import typing import ssl from .util.connection import _TYPE_SOCKET_OPTIONS from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT from .util.url import Url from typing import Literal, Protocol from .response import BaseHTTPResponse
1,468
from __future__ import annotations _TYPE_BODY = typing.Union[bytes, typing.IO[typing.Any], typing.Iterable[bytes], str] class ProxyConfig(typing.NamedTuple): ssl_context: ssl.SSLContext | None use_forwarding_for_https: bool assert_hostname: None | str | Literal[False] assert_fingerprint: str | None...
from __future__ import annotations _TYPE_BODY = typing.Union[bytes, typing.IO[typing.Any], typing.Iterable[bytes], str] class ProxyConfig(typing.NamedTuple): ssl_context: ssl.SSLContext | None use_forwarding_for_https: bool assert_hostname: None | str | Literal[False] assert_fingerprint: str | None...
proxy: Url | None
3
2023-12-16 04:12:01+00:00
2k
neuroglia-io/python-framework
tests/cases/test_service_provider.py
[ { "identifier": "FileLogger", "path": "tests/services.py", "snippet": "class FileLogger(LoggerBase):\n \n def log(text: str):\n with open('example.txt', 'a') as file:\n file.write(f'{text}\\n')" }, { "identifier": "LoggerBase", "path": "tests/services.py", "snippe...
from re import T from sys import implementation from neuroglia.dependency_injection.service_provider import IServiceProvider, ServiceCollection, ServiceProvider from tests.services import FileLogger, LoggerBase, NullLogger, PrintLogger import pytest
820
class TestServiceProvider: def test_build_should_work(self): #arrange services = ServiceCollection() services.add_singleton(LoggerBase, PrintLogger) services.add_singleton(LoggerBase, singleton = FileLogger()) services.add_singleton(LoggerBase, implementation_factory = ...
class TestServiceProvider: def test_build_should_work(self): #arrange services = ServiceCollection() services.add_singleton(LoggerBase, PrintLogger) services.add_singleton(LoggerBase, singleton = FileLogger()) services.add_singleton(LoggerBase, implementation_factory = ...
def _build_null_logger(self, provider : IServiceProvider) -> NullLogger: return NullLogger()
2
2023-12-15 14:36:50+00:00
2k
Vlodson/Faculty-Choice-Assistant
backend/server/endpoints/natural_language.py
[ { "identifier": "make_thread_for_user", "path": "backend/llm/threads.py", "snippet": "def make_thread_for_user() -> Thread:\n return CLIENT.beta.threads.create()" }, { "identifier": "retrieve_thread_for_user", "path": "backend/llm/threads.py", "snippet": "def retrieve_thread_for_user(...
from flask import Blueprint, abort, request, jsonify from backend.llm.threads import ( make_thread_for_user, retrieve_thread_for_user, send_setup_message, send_user_message, create_run_for_thread, retrieve_run_for_user, get_last_message, get_query_from_message, ) from backend.ontology.qu...
1,080
bp = Blueprint("llm", __name__) @bp.route("/setup", methods=["GET"]) def setup_user() -> SetupUserResponse: thread = make_thread_for_user() _ = send_setup_message(thread)
bp = Blueprint("llm", __name__) @bp.route("/setup", methods=["GET"]) def setup_user() -> SetupUserResponse: thread = make_thread_for_user() _ = send_setup_message(thread)
run = create_run_for_thread(thread) # for easier expansion of the API
4
2023-12-21 17:55:05+00:00
2k
stevej2608/reactpy-apexcharts
utils/fast_server.py
[ { "identifier": "log", "path": "utils/logger.py", "snippet": "" }, { "identifier": "var_name", "path": "utils/var_name.py", "snippet": "def var_name(obj: Any, namespace: Dict[str, Any]) -> str:\r\n \"\"\"Return var name as a string\r\n\r\n Args:\r\n obj (Any): Variable ty be...
from typing import Callable from fastapi import FastAPI from reactpy.core.component import Component from reactpy.backend.fastapi import configure, Options from .logger import log, logging from .var_name import var_name from .fast_server_options import DEFAULT_OPTIONS import sys import signal import multiprocessing imp...
802
app = FastAPI(description="ReactPy", version="0.1.0") LOGS = [ "asgi-logger", "concurrent.futures", "concurrent", "asyncio", "uvicorn.error", "uvicorn", "watchfiles.watcher", "watchfiles", "watchfiles.main", "fastapi", "reactpy.backend", "reactpy", "reactpy._option...
app = FastAPI(description="ReactPy", version="0.1.0") LOGS = [ "asgi-logger", "concurrent.futures", "concurrent", "asyncio", "uvicorn.error", "uvicorn", "watchfiles.watcher", "watchfiles", "watchfiles.main", "fastapi", "reactpy.backend", "reactpy", "reactpy._option...
log.info("Uvicorn running on http://%s:%s (Press CTRL+C to quit)", host, port)
0
2023-12-19 16:05:41+00:00
2k
ict-bigdatalab/RIGHT
retrieval_analysis.py
[ { "identifier": "read_line_examples_from_file", "path": "get_datasets.py", "snippet": "def read_line_examples_from_file(data_path):\n sequence = []\n with open(data_path, 'r', encoding='utf-8') as f:\n for line in f:\n line = line.strip(\"\\n\")\n if not line:\n ...
import json from get_datasets import read_line_examples_from_file from tqdm import tqdm from eval_utils import f1
816
def get_hashtag_list(dst): tags = dst.split('[SEP]') target = [] for j in range(len(tags)): tags[j] = tags[j].strip() if tags[j] != '': target.append(tags[j]) # if the dst is nothing if len(target) == 0: target.append('None') # statistic_hashtags(hashtags) ...
def get_hashtag_list(dst): tags = dst.split('[SEP]') target = [] for j in range(len(tags)): tags[j] = tags[j].strip() if tags[j] != '': target.append(tags[j]) # if the dst is nothing if len(target) == 0: target.append('None') # statistic_hashtags(hashtags) ...
f = f1(p, r)
1
2023-12-16 06:00:53+00:00
2k
shell-nlp/gpt_server
gpt_server/serving/main.py
[ { "identifier": "get_free_tcp_port", "path": "gpt_server/utils.py", "snippet": "def get_free_tcp_port():\n \"\"\"获取可用的端口\"\"\"\n tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n tcp.bind((\"\", 0))\n _, port = tcp.getsockname()\n tcp.close()\n return port" }, { "identi...
import yaml import os import sys import subprocess import signal from pprint import pprint from multiprocessing import Process from gpt_server.utils import get_free_tcp_port, start_server, run_cmd, stop_server,delete_log
1,037
# 配置根目录 root_dir = os.path.join(os.path.dirname(__file__), "..") root_dir = os.path.abspath(root_dir) sys.path.append(root_dir) # 删除日志 delete_log(root_dir) def signal_handler(signum, frame): stop_server() raise KeyboardInterrupt signal.signal(signal.SIGINT, signal_handler) with open("./config.yaml", "r") as...
# 配置根目录 root_dir = os.path.join(os.path.dirname(__file__), "..") root_dir = os.path.abspath(root_dir) sys.path.append(root_dir) # 删除日志 delete_log(root_dir) def signal_handler(signum, frame): stop_server() raise KeyboardInterrupt signal.signal(signal.SIGINT, signal_handler) with open("./config.yaml", "r") as...
+ f" --master_port {get_free_tcp_port()}"
0
2023-12-16 07:43:28+00:00
2k
LLM-Evaluation-s-Always-Fatiguing/leaf-playground-hub
rag_qa/rag_qa/scene.py
[ { "identifier": "Examiner", "path": "rag_qa/rag_qa/agents/examiner.py", "snippet": "class Examiner(SceneStaticAgent, role_definition=ROLE_DEFINITION, cls_description=\"An agent who minitor the examine\"):\n config_cls = ExaminerConfig\n config: config_cls\n\n def __init__(self, config: config_c...
import asyncio from typing import List, Optional from pydantic import Field from leaf_playground.core.workers import Logger from leaf_playground.core.scene import Scene from leaf_playground.core.scene_definition import SceneConfig from leaf_playground.data.log_body import ActionLogBody from leaf_playground.data.media i...
1,386
class RagSceneLogBody(ActionLogBody): references: Optional[List[MessageType]] = Field(default=None) response: MessageType = Field(default=...) ground_truth: Optional[Json] = Field(default=None) RagSceneConfig = SceneConfig.create_config_model( SCENE_DEFINITION, additional_config_fields={"data...
class RagSceneLogBody(ActionLogBody): references: Optional[List[MessageType]] = Field(default=None) response: MessageType = Field(default=...) ground_truth: Optional[Json] = Field(default=None) RagSceneConfig = SceneConfig.create_config_model( SCENE_DEFINITION, additional_config_fields={"data...
answer: ExamineeAnswer = await examinee.answer_question(question=q, examiner=self.examiner.profile)
3
2023-12-21 03:09:08+00:00
2k
djkcyl/ABot-NT
func/tool/mcping/mcping.py
[ { "identifier": "SelfPicture", "path": "utils/message/picture.py", "snippet": "class SelfPicture:\n def __init__(self) -> None:\n self.s3file = Launart.current().get_component(S3FileService).s3file\n\n async def from_name(self, name: str) -> Picture:\n url = await self.s3file.get_pre...
import asyncio import base64 import contextlib import json import re import dns.resolver from io import BytesIO from avilla.core import Picture from loguru import logger from PIL import Image from utils.message.picture import SelfPicture from .statusping import StatusPing
1,539
def ping_status(host: str, port: int | None = None) -> dict: if port is None: with contextlib.suppress(Exception): srv_records = dns.resolver.query(f"_minecraft._tcp.{host}", "SRV") for srv in srv_records: host = str(srv.target).rstrip(".") ...
def ping_status(host: str, port: int | None = None) -> dict: if port is None: with contextlib.suppress(Exception): srv_records = dns.resolver.query(f"_minecraft._tcp.{host}", "SRV") for srv in srv_records: host = str(srv.target).rstrip(".") ...
messages.append(await SelfPicture().from_data(image, "jpeg"))
0
2023-12-16 13:19:56+00:00
2k
Chenyme/Chenyme-AAMT
AAMT.py
[ { "identifier": "generate_srt_from_result", "path": "utils/utils.py", "snippet": "def generate_srt_from_result(result): # 格式化为SRT字幕的形式\r\n segments = result['segments']\r\n srt_content = ''\r\n segment_id = 1\r\n for segment in segments:\r\n start_time = int(segment['start'] * 1000)\...
import os import json import streamlit as st import whisper from utils.utils import generate_srt_from_result, tmp_filepath, openai_translate, srt_mv, cache, convert_size
1,557
# 作者:chenyme # 版本:v0.2.2 # 博客站:待更新 st.set_page_config( page_title="AAMT v0.2.2", page_icon="📊", layout="wide", # 设置布局样式为宽展示 initial_sidebar_state="expanded" # 设置初始边栏状态为展开 ) st.title("Chenyme-AAMT") st.write("##### AI全自动视频翻译") with st.sidebar: st.title("欢迎!") st.write(''' ...
# 作者:chenyme # 版本:v0.2.2 # 博客站:待更新 st.set_page_config( page_title="AAMT v0.2.2", page_icon="📊", layout="wide", # 设置布局样式为宽展示 initial_sidebar_state="expanded" # 设置初始边栏状态为展开 ) st.title("Chenyme-AAMT") st.write("##### AI全自动视频翻译") with st.sidebar: st.title("欢迎!") st.write(''' ...
result = openai_translate(st.session_state.key, st.session_state.base, result) # 翻译成目标语言
2
2023-12-18 04:06:03+00:00
2k
davidrs/logo-buddy
logo_buddy/main.py
[ { "identifier": "preprocess", "path": "logo_buddy/controlnet.py", "snippet": "def preprocess(image, controlnet_path=None):\n if \"canny\" in controlnet_path:\n return canny_preprocess(image)\n else:\n return Image.fromarray(image)" }, { "identifier": "CN_MODELS", "path": ...
import os import os.path as op import numpy as np import torch import cv2 import torch from glob import glob from diffusers import StableDiffusionPipeline, DiffusionPipeline from diffusers import ( StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler, ) from diffusers.utils import loa...
1,465
STEPS = 34 SEED = 12 MODELS = { "real": "/Users/drustsmith/repos/stable-diffusion-webui/models/Stable-diffusion/realisticVisionV51_v51VAE.safetensors", "anim": "/Users/drustsmith/repos/stable-diffusion-webui/models/Stable-diffusion/revAnimated_v122EOL.safetensors", } # PROMPT_LIST = [ # Winter {"tex...
STEPS = 34 SEED = 12 MODELS = { "real": "/Users/drustsmith/repos/stable-diffusion-webui/models/Stable-diffusion/realisticVisionV51_v51VAE.safetensors", "anim": "/Users/drustsmith/repos/stable-diffusion-webui/models/Stable-diffusion/revAnimated_v122EOL.safetensors", } # PROMPT_LIST = [ # Winter {"tex...
for cn, cn_path in CN_MODELS.items():
1
2023-12-17 19:24:56+00:00
2k
Varexa/Gateway
chat_exporter/construct/assets/embed.py
[ { "identifier": "discord", "path": "chat_exporter/ext/discord_import.py", "snippet": "" }, { "identifier": "fill_out", "path": "chat_exporter/ext/html_generator.py", "snippet": "PARSE_MODE_NONE = 0\r\nPARSE_MODE_NO_MARKDOWN = 1\r\nPARSE_MODE_MARKDOWN = 2\r\nPARSE_MODE_EMBED = 3\r\nPARSE_...
import html from chat_exporter.ext.discord_import import discord from chat_exporter.ext.html_generator import ( fill_out, embed_body, embed_title, embed_description, embed_field, embed_field_inline, embed_footer, embed_footer_icon, embed_image, embed_thumbnail, e...
894
modules_which_use_none = ["nextcord", "disnake"] def _gather_checker(): if discord.module not in modules_which_use_none and hasattr(discord.Embed, "Empty"): return discord.Embed.Empty return None class Embed: r: str g: str b: str title: str description: str ...
modules_which_use_none = ["nextcord", "disnake"] def _gather_checker(): if discord.module not in modules_which_use_none and hasattr(discord.Embed, "Empty"): return discord.Embed.Empty return None class Embed: r: str g: str b: str title: str description: str ...
author_icon = await fill_out(self.guild, embed_author_icon, [
1
2023-12-18 14:17:31+00:00
2k
mariaalfaroc/a2s-transformer
my_utils/metrics.py
[ { "identifier": "VOICE_CHANGE_TOKEN", "path": "my_utils/encoding_convertions.py", "snippet": "VOICE_CHANGE_TOKEN = \"<COC>\"" }, { "identifier": "STEP_CHANGE_TOKEN", "path": "my_utils/encoding_convertions.py", "snippet": "STEP_CHANGE_TOKEN = \"<COR>\"" } ]
import os import shutil from music21 import converter as converterm21 from pyMV2H.utils.mv2h import MV2H from pyMV2H.metrics.mv2h import mv2h from pyMV2H.utils.music import Music from pyMV2H.converter.midi_converter import MidiConverter as Converter from .encoding_convertions import VOICE_CHANGE_TOKEN, STEP_CHANGE_TOKE...
927
def compute_metrics(y_true, y_pred): ################################# Sym-ER and Seq-ER: metrics = compute_ed_metrics(y_true=y_true, y_pred=y_pred) ################################# MV2H: mv2h_dict = compute_mv2h_metrics(y_true=y_true, y_pred=y_pred) metrics.update(mv2h_dict) return metrics...
def compute_metrics(y_true, y_pred): ################################# Sym-ER and Seq-ER: metrics = compute_ed_metrics(y_true=y_true, y_pred=y_pred) ################################# MV2H: mv2h_dict = compute_mv2h_metrics(y_true=y_true, y_pred=y_pred) metrics.update(mv2h_dict) return metrics...
if token == STEP_CHANGE_TOKEN:
1
2023-12-18 20:01:00+00:00
2k
YashsviG/rootkit
victim.py
[ { "identifier": "port_knocking", "path": "portknocker.py", "snippet": "def port_knocking(victim_ip):\n \"\"\"\n Perform port knocking on the victim side to authenticate the commander.\n\n Args:\n victim_ip (str): IP address of the victim.\n\n Returns:\n tuple: IP address and po...
import argparse import setproctitle import shutil from keylogger import * from watcher import * from portknocker import port_knocking from processname import choose_process_name from utils import get_ip_address, transfer_keylog_file, check_exists
1,279
def handle_command(command: int, keylogger, watcher, covert): """ Handle the received command. Args: command (int): Received command. keylogger (Keylogger): Keylogger instance. watcher (Watcher): Watcher instance. covert (CovertChannel): Covert channel instance. ...
def handle_command(command: int, keylogger, watcher, covert): """ Handle the received command. Args: command (int): Received command. keylogger (Keylogger): Keylogger instance. watcher (Watcher): Watcher instance. covert (CovertChannel): Covert channel instance. ...
i = check_exists(file)
4
2023-12-19 18:54:22+00:00
2k
yacinxx/dnakey
enginev2.py
[ { "identifier": "ConfigManager", "path": "profile_config/config_manager.py", "snippet": "class ConfigManager:\r\n def __init__(self, prime_key:str) -> None:\r\n with open(\"profile_config/profile_config.json\", \"r\") as f: \r\n self.profile_data = __import__(\"json\").loads(f.read(...
from cryptography.fernet import Fernet from profile_config.config_manager import ConfigManager from license.license_manager import VERSION import random, json, string, datetime
1,550
class DNAEngine(): def __init__( self, has_key="test", profile_name="profile_test", activate_merge=True, save_cookies=True, **advance_settings): self.has_key = has_key self.profile_name = profile_name ...
class DNAEngine(): def __init__( self, has_key="test", profile_name="profile_test", activate_merge=True, save_cookies=True, **advance_settings): self.has_key = has_key self.profile_name = profile_name ...
self.config_manager = ConfigManager(self.config_has_key)
0
2023-12-18 22:04:13+00:00
2k
tamnva/hydroecolstm
examples/example_run.py
[ { "identifier": "run_train", "path": "hydroecolstm/model_run.py", "snippet": "def run_train(config_file):\n \n # Load configuration\n config = read_config(config_file)\n\n # Read and split data\n data = read_train_test_data(config)\n \n # Scale/transformer name for static, dynamic, ...
from hydroecolstm.model_run import run_train from hydroecolstm.utility.plot import plot from hydroecolstm.interface.main_gui import show_gui
941
# Import hydroecolstm function #-----------------------------------------------------------------------------# # Run the model # #-----------------------------------------------------------------------------# # Configuration file config_file = "C:/Users/ng...
# Import hydroecolstm function #-----------------------------------------------------------------------------# # Run the model # #-----------------------------------------------------------------------------# # Configuration file config_file = "C:/Users/ng...
show_gui()
2
2023-12-20 09:11:36+00:00
2k
LuhhLu/Predictive-Video-Segmentation
unet_train.py
[ { "identifier": "Load_unet", "path": "Unet.py", "snippet": "def Load_unet(path=None):\n if path:\n unet_model = UNet(n_channels=3, n_classes=49)\n unet_model.load_state_dict(torch.load(path))\n else:\n unet_model = UNet(n_channels=3, n_classes=49)\n return unet_model" }, ...
from tqdm import tqdm from torch.utils.data import DataLoader from torchvision import transforms from Unet import Load_unet, CustomDataset, WeightedBCEWithLogitsLoss import torch import torch.optim as optim import argparse
943
def main(): # Command-line arguments parser = argparse.ArgumentParser(description='Train UNet with custom settings') parser.add_argument('--lr', type=float, default=0.001, help='Learning rate') parser.add_argument('--batch', type=int, default=64, help='Batch size') parser.add_argument('--res', type...
def main(): # Command-line arguments parser = argparse.ArgumentParser(description='Train UNet with custom settings') parser.add_argument('--lr', type=float, default=0.001, help='Learning rate') parser.add_argument('--batch', type=int, default=64, help='Batch size') parser.add_argument('--res', type...
train_dataset = CustomDataset('unet_train/images', 'unet_train/masks', transform)
1
2023-12-17 20:39:14+00:00
2k
garinops/chat-E-AI
embed/clients/itchat/messages/friend.py
[ { "identifier": "ITCHAT_CALL_CODE_SELF", "path": "config/settings.py", "snippet": "ITCHAT_CALL_CODE_SELF = \"AI\"" }, { "identifier": "ITCHAT_CALL_CODE", "path": "config/settings.py", "snippet": "ITCHAT_CALL_CODE = \"AI\"" }, { "identifier": "ITCHAT_WHITELIST_FRIEND", "path":...
from config.settings import ITCHAT_CALL_CODE_SELF, ITCHAT_CALL_CODE, ITCHAT_WHITELIST_FRIEND from embed.reply.text import EReplyText from models.messages import MessageItchat, MessageCea from models.send import Send
1,025
def handle_friend_message(client, message: MessageItchat) -> Send: _callCodeSelf = ITCHAT_CALL_CODE_SELF _callCode = ITCHAT_CALL_CODE
def handle_friend_message(client, message: MessageItchat) -> Send: _callCodeSelf = ITCHAT_CALL_CODE_SELF _callCode = ITCHAT_CALL_CODE
_whiteListFriend = ITCHAT_WHITELIST_FRIEND
2
2023-12-16 17:02:13+00:00
2k
ruudjuffermans/Event-Driven-Backtester
backtester/execution.py
[ { "identifier": "FillEvent", "path": "backtester/events.py", "snippet": "class FillEvent(Event):\n \"\"\"\n Fill event once an order based on the response from the broker\n\n Parameters:\n datetime - A datetime at which the signal is created.\n symbol - The symbol for current asset.\n ...
from abc import abstractmethod from datetime import datetime from .events import FillEvent, OrderEvent
653
class ExecutionHandler: def register(self, events): self.events = events @abstractmethod def execute_order(self, event): raise NotImplementedError("Should implement execute_order()") class SimulatedExecutionHandler(ExecutionHandler): def __init__(self): pass def execut...
class ExecutionHandler: def register(self, events): self.events = events @abstractmethod def execute_order(self, event): raise NotImplementedError("Should implement execute_order()") class SimulatedExecutionHandler(ExecutionHandler): def __init__(self): pass def execut...
if isinstance(event, OrderEvent):
1
2023-12-16 21:09:00+00:00
2k
liebrandapps/FindMyGUI
findmy/request_reports.py
[ { "identifier": "icloud_login_mobileme", "path": "findmy/pypush_gsa_icloud.py", "snippet": "def icloud_login_mobileme(ctx, second_factor='sms'):\n username = ctx.cfg.appleId_appleId\n password = ctx.cfg.appleId_password\n anisetteUrl = ctx.cfg.general_anisetteHost + \":\" + str(ctx.cfg.general_...
import base64 import datetime import hashlib import json import os import struct import requests from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from findmy.pypush_gsa_icloud im...
1,373
class FindMy: def __init__(self, ctx): self.ctx = ctx def sha256(self, data): digest = hashlib.new("sha256") digest.update(data) return digest.digest() def decrypt(self, enc_data, algorithm_dkey, mode): decryptor = Cipher(algorithm_dkey, mode, default_backend()...
class FindMy: def __init__(self, ctx): self.ctx = ctx def sha256(self, data): digest = hashlib.new("sha256") digest.update(data) return digest.digest() def decrypt(self, enc_data, algorithm_dkey, mode): decryptor = Cipher(algorithm_dkey, mode, default_backend()...
mobileme = icloud_login_mobileme(self.ctx, second_factor=second_factor)
0
2023-12-16 12:39:52+00:00
2k
Samuel-Effiong/Django-Dynamic-Table
django_dynamic_table/models.py
[ { "identifier": "TableHaveNoRow", "path": "django_dynamic_table/errors.py", "snippet": "class TableHaveNoRow(DynamicTableError):\r\n pass\r" }, { "identifier": "TableHaveNoColumn", "path": "django_dynamic_table/errors.py", "snippet": "class TableHaveNoColumn(DynamicTableError):\r\n ...
from typing import Sequence from datetime import datetime from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .errors import ( TableHaveNoRow, TableHaveNoColumn, ColumnNotInTable, RowNotInTable, DuplicateColumnInTable, DynamicTableErr...
934
""" Creating a Dynamic Table using conventional Django standard This Table gives you more control over it manipulation than Django models Developed by: Samuel Effiong Nkopuruk Email: senai.nkop@gmail.com """ __SUPPORTED_DATA_TYPE_CHOICES__ = ( ('char', 'Char'), ('int', 'Int'), ('flo...
""" Creating a Dynamic Table using conventional Django standard This Table gives you more control over it manipulation than Django models Developed by: Samuel Effiong Nkopuruk Email: senai.nkop@gmail.com """ __SUPPORTED_DATA_TYPE_CHOICES__ = ( ('char', 'Char'), ('int', 'Int'), ('flo...
raise DuplicateColumnInTable()
4
2023-12-19 15:50:38+00:00
2k
gsamil/text-classification
recommender/train.py
[ { "identifier": "vocab", "path": "data.py", "snippet": "class ClassificationSample(BaseModel):\ndef preprocess_text(text: str) -> str:\ndef get_samples_from_file(file_path: str) -> list[ClassificationSample]:\ndef stratify_samples(\n samples: list[ClassificationSample], number_per_sample: int\n) -> l...
import torch import time import os from torch import nn from torch.utils.data import DataLoader from torch.optim.lr_scheduler import ExponentialLR from data import ( vocab, get_samples_from_file, stratify_samples, save_categories, load_categories, ) from model import TextClassifier, TrainingParamete...
1,057
# Set `train_file`, `test_file` and `model_dir` apropriately. # Set `negative_samples` to the number of negative samples you want to use. # run with `export PYTHONPATH=. && python recommender/train.py` in the main directory. train_file = "./data/train_cleaned.csv" test_file = "./data/test_cleaned.csv" model_dir = "./...
# Set `train_file`, `test_file` and `model_dir` apropriately. # Set `negative_samples` to the number of negative samples you want to use. # run with `export PYTHONPATH=. && python recommender/train.py` in the main directory. train_file = "./data/train_cleaned.csv" test_file = "./data/test_cleaned.csv" model_dir = "./...
vocab_size=len(vocab),
0
2023-12-17 11:37:37+00:00
2k
zhcui/polar_preview
polar/basis/trans_1e.py
[ { "identifier": "mdot", "path": "polar/utils/misc.py", "snippet": "def mdot(*args):\n \"\"\"\n Reduced matrix dot.\n \"\"\"\n return reduce(np.dot, args)" }, { "identifier": "kdot", "path": "polar/utils/misc.py", "snippet": "def kdot(a, b):\n \"\"\"\n Matrix dot with kp...
import numpy as np import scipy.linalg as la from polar.utils.misc import (mdot, kdot, get_spin_dim, add_spin_dim)
798
#!/usr/bin/env python """ Transform 1e quantities. Authors: Zhi-Hao Cui Tianyu Zhu Shunyue Yuan """ # ***************************************************************************** # Transform functions AO -> LO and LO -> AO # for h1 and rdm1 # *********************************************************...
#!/usr/bin/env python """ Transform 1e quantities. Authors: Zhi-Hao Cui Tianyu Zhu Shunyue Yuan """ # ***************************************************************************** # Transform functions AO -> LO and LO -> AO # for h1 and rdm1 # *********************************************************...
h_lo_lo[k] = mdot(C_ao_lo[k].conj().T, h_ao_ao[k], C_ao_lo[k])
0
2023-12-18 07:39:51+00:00
2k