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 |
|---|---|---|---|---|---|---|---|---|---|---|
WU-CVGL/BAD-NeRFstudio | badnerf/badnerf_method_config.py | [
{
"identifier": "BadNerfCameraOptimizerConfig",
"path": "badnerf/cameras/badnerf_camera_optimizer.py",
"snippet": "class BadNerfCameraOptimizerConfig(InstantiateConfig):\n \"\"\"Configuration of BAD-NeRF camera optimizer.\"\"\"\n\n _target: Type = field(default_factory=lambda: BadNerfCameraOptimiz... | from nerfstudio.configs.base_config import ViewerConfig
from nerfstudio.engine.optimizers import AdamOptimizerConfig
from nerfstudio.engine.schedulers import ExponentialDecaySchedulerConfig
from nerfstudio.plugins.types import MethodSpecification
from badnerf.cameras.badnerf_camera_optimizer import BadNerfCameraOptimiz... | 902 | """
BAD-NeRF config.
"""
badnerf_nerfacto = MethodSpecification(
config=BadNerfTrainerConfig(
method_name="bad-nerfacto",
steps_per_eval_all_images=500,
steps_per_save=2000,
max_num_iterations=30001,
mixed_precision=False,
use_grad_scaler=True,
| """
BAD-NeRF config.
"""
badnerf_nerfacto = MethodSpecification(
config=BadNerfTrainerConfig(
method_name="bad-nerfacto",
steps_per_eval_all_images=500,
steps_per_save=2000,
max_num_iterations=30001,
mixed_precision=False,
use_grad_scaler=True, | pipeline=BadNerfPipelineConfig( | 5 | 2023-11-10 07:40:22+00:00 | 2k |
nttcom/WASB-SBDT | src/runners/train_and_test.py | [
{
"identifier": "BaseRunner",
"path": "src/runners/base.py",
"snippet": "class BaseRunner:\n def __init__(\n self,\n cfg: DictConfig,\n ):\n self._cfg = cfg\n log.info('run {}'.format(self._cfg['runner']['name']))\n self._output_dir = cfg['output_dir']\n\... | import os
import os.path as osp
import shutil
import time
import logging
import hydra
import numpy as np
import torch
from tqdm import tqdm
from omegaconf import DictConfig, OmegaConf
from hydra.core.hydra_config import HydraConfig
from torch import nn
from models import build_model
from dataloaders import build_datalo... | 889 |
log = logging.getLogger(__name__)
def update_fp1_example(epoch,
model,
vi_runner,
fp1_fpath,
):
vi_results = vi_runner.run(model=model)
print(vi_results['fp1_im_list_dict'])
print(fp1_fpath)
fp1_im_list_dict = vi_results['fp1_im_l... |
log = logging.getLogger(__name__)
def update_fp1_example(epoch,
model,
vi_runner,
fp1_fpath,
):
vi_results = vi_runner.run(model=model)
print(vi_results['fp1_im_list_dict'])
print(fp1_fpath)
fp1_im_list_dict = vi_results['fp1_im_l... | class Trainer(BaseRunner): | 0 | 2023-11-15 02:11:00+00:00 | 2k |
barkure/white-dove-backend | services/users.py | [
{
"identifier": "SessionLocal",
"path": "db.py",
"snippet": "DATABASE_URL = \"sqlite:///./data.db\""
},
{
"identifier": "Users",
"path": "models.py",
"snippet": "class Users(Base):\n __tablename__ = \"Users\"\n\n # fields\n user_id = Column(Integer,primary_key=True, index=True)... | from datetime import timedelta
from db import SessionLocal
from models import Users, BlogSettings
from services.auth_utils import create_access_token
from config import GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, ACCESS_TOKEN_EXPIRE_MINUTES
import requests | 1,295 | "email": user.email,
"GitHub_id": user.GitHub_id
}
else:
return ["User not found"]
# 更新用户
def update_user(payload: dict):
user_id = payload.get("user_id")
userName = payload.get("userName")
password = payload.get("password")
email = payload.get("email")
... |
# 添加用户
def create_user(payload: dict):
userName = payload.get("userName")
password = payload.get("password")
email = payload.get("email")
db = SessionLocal()
new_user = Users(userName=userName, password=password, email=email)
db.add(new_user)
db.commit()
db.close()
return "User crea... | resp1 = requests.post("https://github.com/login/oauth/access_token?"+"client_id="+GITHUB_CLIENT_ID+"&client_secret="+GITHUB_CLIENT_SECRET+"&code="+code, headers={"Accept": "application/json"}) | 4 | 2023-11-11 04:46:58+00:00 | 2k |
BobaZooba/xllm-demo | xllm_demo/core/registry.py | [
{
"identifier": "DATASET_KEY",
"path": "xllm_demo/core/constants.py",
"snippet": "DATASET_KEY = \"antropic\""
},
{
"identifier": "COLLATOR_KEY",
"path": "xllm_demo/core/constants.py",
"snippet": "COLLATOR_KEY = \"last_part\""
},
{
"identifier": "TRAINER_KEY",
"path": "xllm_de... | from xllm.datasets import datasets_registry
from xllm.collators import collators_registry
from xllm.trainers import trainers_registry
from xllm.experiments import experiments_registry
from xllm_demo.core.constants import DATASET_KEY, COLLATOR_KEY, TRAINER_KEY, EXPERIMENT_KEY
from xllm_demo.core.dataset import AntropicD... | 1,238 | # Copyright 2023 Boris Zubarev. 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 law o... | # Copyright 2023 Boris Zubarev. 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 law o... | experiments_registry.add(key=EXPERIMENT_KEY, value=MyExperiment) | 3 | 2023-11-10 17:56:14+00:00 | 2k |
Kiyliy/openai_speech_to_text | openai_audio.py | [
{
"identifier": "send_to_openai_api",
"path": "send_to_openai.py",
"snippet": "def send_to_openai_api(api_key,url,audio_file_path)->str:\n print(\"DEBUD: api_key:\",api_key)\n if not api_key or not url:\n raise ValueError(\"API密钥和URL必须设置\")\n headers = {\n 'Authorization': f'Beare... | import pyaudio
import wave
import requests
import json
import base64
import pyautogui
import threading
import logging
import pyperclip
import os
import random
import time
import get_api_key
from threading import Lock
from send_to_openai import send_to_openai_api , paste_text | 923 |
logging.basicConfig(level=logging.INFO)
# 确保在模块加载时调用load_config
get_api_key.load_config()
# API和URL变量
api_key = get_api_key.get_api_key()
url = get_api_key.get_api_url()
# 录音参数
chunk = 1024
format = pyaudio.paInt16
channels = 1
rate = 44100
# 录音控制变量
is_recording = False
frames = []
frames_lock = Lock()
def start... |
logging.basicConfig(level=logging.INFO)
# 确保在模块加载时调用load_config
get_api_key.load_config()
# API和URL变量
api_key = get_api_key.get_api_key()
url = get_api_key.get_api_url()
# 录音参数
chunk = 1024
format = pyaudio.paInt16
channels = 1
rate = 44100
# 录音控制变量
is_recording = False
frames = []
frames_lock = Lock()
def start... | paste_text(transcription) | 1 | 2023-11-11 09:28:31+00:00 | 2k |
globality-corp/deboiler | deboiler/models/page.py | [
{
"identifier": "logger",
"path": "deboiler/logger.py",
"snippet": "def logger(obj):\n \"\"\"\n logging decorator, assigning an object the `logger` property.\n Can be used on a Python class, e.g:\n @logger\n class MyClass:\n ...\n \"\"\"\n\n obj.logger = logging.g... | import re
from dataclasses import dataclass
from io import StringIO
from logging import Logger
from typing import Optional, Union
from lxml.etree import HTMLParser, _Element, parse as parse_html
from deboiler.logger import logger
from deboiler.lxml_query import get_candidate_nodes
from deboiler.models.lxml_node import ... | 981 |
EMPTY_HTML = "<html></html>"
@dataclass
class RawPage:
"""
A crawled page with raw (string or binary) content.
"""
url: str
content: Union[bytes, str]
def __repr__(self):
return f"RawPage(url={self.url}, content={self.content[:20]}...)"
def parse(self):
return Parsed... |
EMPTY_HTML = "<html></html>"
@dataclass
class RawPage:
"""
A crawled page with raw (string or binary) content.
"""
url: str
content: Union[bytes, str]
def __repr__(self):
return f"RawPage(url={self.url}, content={self.content[:20]}...)"
def parse(self):
return Parsed... | for node in get_candidate_nodes(self.content) | 1 | 2023-11-17 23:11:45+00:00 | 2k |
solovieff/kibernikto | kibernikto/plugins/_weblink_summarizator.py | [
{
"identifier": "_is_image",
"path": "kibernikto/plugins/_img_summarizator.py",
"snippet": "def _is_image(url):\n parsed = urlparse(url)\n path = parsed.path\n\n # Get the file extension from the path\n ext = os.path.splitext(path)[1].lower()\n\n # Check if the extension is a known image ... | import logging
import re
from kibernikto.plugins._img_summarizator import _is_image
from openai.types.chat import ChatCompletion
from kibernikto.constants import OPENAI_MAX_TOKENS
from kibernikto.utils.text import get_website_as_text, get_website_html
from ._kibernikto_plugin import KiberniktoPlugin, KiberniktoPluginEx... | 914 |
class WeblinkSummaryPlugin(KiberniktoPlugin):
"""
This plugin is used to get video transcript and then get text summary from it.
"""
def __init__(self, model: str, base_url: str, api_key: str, summarization_request: str):
super().__init__(model=model, base_url=base_url, api_key=api_key, pos... |
class WeblinkSummaryPlugin(KiberniktoPlugin):
"""
This plugin is used to get video transcript and then get text summary from it.
"""
def __init__(self, model: str, base_url: str, api_key: str, summarization_request: str):
super().__init__(model=model, base_url=base_url, api_key=api_key, pos... | if _is_image(web_link): | 0 | 2023-11-11 18:39:28+00:00 | 2k |
leeyuentuen/tibber_ev | custom_components/tibber_ev/sensor.py | [
{
"identifier": "MAX_CHARGE_RANGE",
"path": "custom_components/tibber_ev/const.py",
"snippet": "MAX_CHARGE_RANGE = 375"
},
{
"identifier": "TibberEVEntity",
"path": "custom_components/tibber_ev/entity.py",
"snippet": "class TibberEVEntity(Entity):\n\n def __init__(self, device: Tibber... | import logging
from typing import Final
from dataclasses import dataclass
from datetime import timedelta
from .const import MAX_CHARGE_RANGE
from .entity import TibberEVEntity
from homeassistant.helpers.typing import StateType
from homeassistant import const
from homeassistant.config_entries import ConfigEntry
from hom... | 1,577 | path="battery",
subpath="percent",
unit=PERCENTAGE,
round_digits=None,
state_class=SensorStateClass.MEASUREMENT,
device_class=SensorDeviceClass.BATTERY,
),
TibberSensorDescription(
key="battery_charge_limit",
name="battery charge limit",
ic... |
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(seconds=15)
@dataclass
class TibberSensorDescriptionMixin:
"""Define an entity description mixin for sensor entities."""
path: str
subpath: str | None
unit: str
round_digits: int | None
unit: str | None
@dataclass
c... | tibberApi: TibberApi | 3 | 2023-11-14 18:59:47+00:00 | 2k |
bytedance/LapNet | lapnet/configs/benzene_dimer/benzene_dimer.py | [
{
"identifier": "base_config",
"path": "lapnet/base_config.py",
"snippet": "class SystemType(enum.IntEnum):\n MOLECULE = enum.auto()\n def has_value(cls, value):\ndef default() -> ml_collections.ConfigDict:\ndef resolve(cfg):"
},
{
"identifier": "system",
"path": "lapnet/utils/system.py",
... | from lapnet import base_config
from lapnet.utils import system
from lapnet.utils.system import Atom | 1,044 | # Copyright 2023 Bytedance Ltd. and/or its affiliate
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2023 Bytedance Ltd. and/or its affiliate
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | cfg = base_config.default() | 0 | 2023-11-13 08:19:53+00:00 | 2k |
svetlovtech/gptize | gptize/gptizer.py | [
{
"identifier": "File",
"path": "gptize/models.py",
"snippet": "class File:\n \"\"\"Class representing a file in the project.\"\"\"\n def __init__(self, file_name: str, directory: str):\n self.file_name = file_name\n self.directory = directory\n self.content = \"\"\n se... | import logging
import os
import pathspec
from .models import File, Project
from .settings import Settings
from .output_builder import OutputBuilder | 1,396 |
class GPTizer:
def __init__(self):
self._project = None
self._gitignore = None
def process_directory(self, root_path: str):
"""
Processes all the files within a given directory. This method initializes
the Project object for the specified directory, loads the .gitignor... |
class GPTizer:
def __init__(self):
self._project = None
self._gitignore = None
def process_directory(self, root_path: str):
"""
Processes all the files within a given directory. This method initializes
the Project object for the specified directory, loads the .gitignor... | file_obj = File(file_name, file_path) | 0 | 2023-11-11 20:59:01+00:00 | 2k |
civrealm/civrealm | src/civrealm/envs/freeciv_wrapper/tensor_base_wrapper.py | [
{
"identifier": "Wrapper",
"path": "src/civrealm/envs/freeciv_wrapper/core.py",
"snippet": "class Wrapper(gymnasium.Wrapper):\n def reset(self, *, seed=None, options=None, **kwargs):\n return self.env.reset(seed=seed, options=options, **kwargs)"
},
{
"identifier": "onehotifier_maker",
... | import numpy as np
from civrealm.envs import FreecivBaseEnv
from civrealm.envs.freeciv_wrapper.config import default_tensor_config
from .core import Wrapper
from .utils import onehotifier_maker | 1,273 |
class TensorBase(Wrapper):
"""
A basic wrapper that deals with config loading and entity id recording,
required by all tensor-related wrappers.
Parameters
----------
env: FreecivBaseEnv
config: dict
tensor env configuration
Attributes
---------
config: dict
... |
class TensorBase(Wrapper):
"""
A basic wrapper that deals with config loading and entity id recording,
required by all tensor-related wrappers.
Parameters
----------
env: FreecivBaseEnv
config: dict
tensor env configuration
Attributes
---------
config: dict
... | self.config["obs_ops"]["unit"]["type_rule_name"] = onehotifier_maker( | 1 | 2023-11-18 19:35:50+00:00 | 2k |
Sheppsu/discord-ext-listening | discord/ext/listening/sink.py | [
{
"identifier": "RTCPMessageType",
"path": "discord/ext/listening/enums.py",
"snippet": "class RTCPMessageType(Enum):\n sender_report = 200\n receiver_report = 201\n source_description = 202\n goodbye = 203\n application_defined = 204"
},
{
"identifier": "Decoder",
"path": "di... | import asyncio
import logging
import os
import queue
import struct
import subprocess
import threading
import wave
from collections import defaultdict
from dataclasses import dataclass
from time import monotonic
from typing import TYPE_CHECKING, Any, BinaryIO, Callable, Dict, List, Optional, Sequence, Tuple, Union
from ... | 1,343 | c: :class:`int`
The total number of RTP data packets from source SSRC that have
been lost since the beginning of reception.
ehsn: :class:`int`
The low 16 bits contain the highest sequence number received in an RTP
data packet from source SSRC, and the most significant 16 bits ext... |
if TYPE_CHECKING:
__all__ = (
"AudioFrame",
"AudioSink",
"AudioHandlingSink",
"AudioFileSink",
"AudioFile",
"WaveAudioFile",
"MP3AudioFile",
"RTCPPacket",
"RTCPSenderReportPacket",
"RTCPReceiverReportPacket",
"RTCPSourceDescriptionPacket",
"RTCPGoodbyePacket",
"R... | pt: RTCPMessageType | 0 | 2023-11-15 00:16:36+00:00 | 2k |
RAIVNLab/MatFormer-OLMo | olmo/data/iterable_dataset.py | [
{
"identifier": "PathOrStr",
"path": "olmo/aliases.py",
"snippet": ""
},
{
"identifier": "barrier",
"path": "olmo/util.py",
"snippet": "def barrier() -> None:\n if dist.is_available() and dist.is_initialized():\n dist.barrier()"
},
{
"identifier": "get_global_rank",
... | import logging
import math
import numpy as np
import torch
import torch.utils.data
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional, Sequence, Union
from ..aliases import PathOrStr
from ..util import barrier, get_global_rank, get_world_size | 803 |
__all__ = ["IterableDataset"]
log = logging.getLogger(__name__)
class IterableDataset(torch.utils.data.IterableDataset[Dict[str, Any]]):
"""
Adapted from PyTorch's DistributedSampler, this wraps a Dataset or arbitrary sequence
as an IterableDataset that can be deterministically restarted at any point... |
__all__ = ["IterableDataset"]
log = logging.getLogger(__name__)
class IterableDataset(torch.utils.data.IterableDataset[Dict[str, Any]]):
"""
Adapted from PyTorch's DistributedSampler, this wraps a Dataset or arbitrary sequence
as an IterableDataset that can be deterministically restarted at any point... | barrier() | 1 | 2023-11-14 02:24:07+00:00 | 2k |
1in-oos/ccplus | caringcaribou/utils/can_actions.py | [
{
"identifier": "ARBITRATION_ID_MAX",
"path": "caringcaribou/utils/constants.py",
"snippet": "ARBITRATION_ID_MAX = 0x7FF"
},
{
"identifier": "ARBITRATION_ID_MAX_EXTENDED",
"path": "caringcaribou/utils/constants.py",
"snippet": "ARBITRATION_ID_MAX_EXTENDED = 0x18DAFFF1"
},
{
"iden... | from caringcaribou.utils.constants import ARBITRATION_ID_MAX, ARBITRATION_ID_MAX_EXTENDED, ARBITRATION_ID_MIN, BYTE_MAX, BYTE_MIN
from sys import stdout, version_info
import can
import time | 1,521 | if print_results:
time_left = end_time - time.time()
num_matches = len(blacklist)
print("\r{0:> 5.1f} seconds left, {1} found".format(time_left, num_matches), end="")
stdout.flush()
# Receive message
msg = bus.recv(0.1)
if msg is None:
... | from __future__ import print_function
# Handle large ranges efficiently in both python 2 and 3
if version_info[0] == 2:
range = xrange
MESSAGE_DELAY = 0.1
DELAY_STEP = 0.02
NOTIFIER_STOP_DURATION = 0.5
# Global CAN interface setting, which can be set through the -i flag to cc.py
# The value None corresponds to ... | def bruteforce_data(self, data, bruteforce_index, callback, min_value=BYTE_MIN, max_value=BYTE_MAX, | 3 | 2023-11-13 05:05:46+00:00 | 2k |
L1bra1/WeakMotion | predict_FGBG_mask.py | [
{
"identifier": "PreSegNet",
"path": "weak_model.py",
"snippet": "class PreSegNet(nn.Module):\n def __init__(self, FGBG_category_num=2, height_feat_size=13):\n super(PreSegNet, self).__init__()\n\n self.FGBG_classify = FGBGEstimation(motion_category_num=FGBG_category_num)\n self.... | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import time
import sys
import argparse
import os
from weak_model import PreSegNet
from data.weak_utils import remove_close, filter_pc, convert_semantic_to_FGBG, gen_voxel_indices_for_pc, convert_semantic_to... | 1,233 |
def check_folder(folder_path):
if not os.path.exists(folder_path):
os.mkdir(folder_path)
return folder_path
height_feat_size = 13 # The size along the height dimension
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--data', default='/path_to/nuScenes/weak-data/train', type=str, hel... |
def check_folder(folder_path):
if not os.path.exists(folder_path):
os.mkdir(folder_path)
return folder_path
height_feat_size = 13 # The size along the height dimension
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--data', default='/path_to/nuScenes/weak-data/train', type=str, hel... | model = PreSegNet(FGBG_category_num=2, height_feat_size=height_feat_size) | 0 | 2023-11-12 07:03:29+00:00 | 2k |
c3exchange/c3-smartcontracts-v1 | contracts_unified/core/state_handler/global_handler.py | [
{
"identifier": "InstrumentId",
"path": "contracts_unified/library/c3types.py",
"snippet": "class SignedInstrumentAmount(abi.NamedTuple):\nclass LiquidationFactors(abi.NamedTuple):\nclass InstrumentListElement(abi.NamedTuple):\nclass UserInstrumentData(abi.NamedTuple):\nclass OnChainOrderData(abi.NamedT... | from typing import cast
from pyteal import (
ABIReturnSubroutine,
App,
Assert,
Btoi,
Bytes,
Expr,
Global,
Int,
Len,
MinBalance,
Pop,
Seq,
abi,
)
from contracts_unified.library.c3types import (
InstrumentId,
InstrumentListElement,
LiquidationFactors,
)
from... | 1,428 |
@staticmethod
def set_pricecaster_id(pricecaster_id) -> Expr:
"""Sets the App id of the pricecaster"""
return App.globalPut(KEY_PRICECASTER_ID, Btoi(pricecaster_id))
@staticmethod
def get_wormhole_bridge_id() -> Expr:
"""Gets the App id of the wormhole bridge"""
retur... | """Implements core contract global state handler"""
KEY_INIT_TIMESTAMP = Bytes("t")
KEY_INSTRUMENT_COUNT = Bytes("c")
KEY_MBR_FUND = Bytes("m")
KEY_PRICECASTER_ID = Bytes("p")
KEY_WORMHOLE_BRIDGE_ID = Bytes("b")
KEY_LIQUIDATION_FACTORS = Bytes("l")
KEY_SIGNATURE_VALIDATOR = Bytes("s")
KEY_WITHDRAW_BUFFER = Bytes("w... | instrument_id: InstrumentId, | 0 | 2023-11-17 20:54:15+00:00 | 2k |
gunderson-dettmer/CE2OCF | CE2OCF/ocf/mocks/stockholders.py | [
{
"identifier": "fake_phone_number",
"path": "CE2OCF/ocf/mocks/company.py",
"snippet": "def fake_phone_number() -> str:\n \"\"\"\n Generates a valid US phone number with the international calling code.\n\n The format is +1 (XXX) XXX-XXXX, with the following rules for the area code:\n 1. The ... | import random
import uuid
from faker import Faker
from CE2OCF.ocf.mocks.company import fake_phone_number
from CE2OCF.types.enums import (
DoubleTriggerTypesEnum,
PaidWithOptionsEnum,
SingleTriggerTypesEnum,
VestingTypesEnum,
)
from CE2OCF.types.models import Stockholder | 1,487 |
fake = Faker()
def sum_shares(stockholder_list: list[Stockholder]) -> tuple[int, int]:
total_FFPreferredShares = 0
total_Shares = 0
for stockholder in stockholder_list:
if stockholder.FFPreferredShares is not None:
total_FFPreferredShares += stockholder.FFPreferredShares
i... |
fake = Faker()
def sum_shares(stockholder_list: list[Stockholder]) -> tuple[int, int]:
total_FFPreferredShares = 0
total_Shares = 0
for stockholder in stockholder_list:
if stockholder.FFPreferredShares is not None:
total_FFPreferredShares += stockholder.FFPreferredShares
i... | DoubleTrigger=random.choice(list(DoubleTriggerTypesEnum)), | 1 | 2023-11-13 15:50:53+00:00 | 2k |
Hellohistory/EbookDataRename.py | main.py | [
{
"identifier": "queryDatabaseForFileNames",
"path": "model/database_handler.py",
"snippet": "def queryDatabaseForFileNames(db_folder_path, folder_path, tableWidget):\n try:\n db_files = get_files_from_directory(db_folder_path, recursive=True)\n db_files = [f for f in db_files if f.ends... | import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLineEdit, QProgressBar, QTableWidget,
QRadioButton, QCheckBox, QFileDialog, QTableWidgetItem)
from PyQt5.QtCore import QSize
from opencc import Op... | 1,131 |
class MainGUI(QMainWindow):
def __init__(self):
super().__init__()
self.cc = OpenCC('s2t')
self.original_names = {}
self.initUI()
def applyTraditionalSimplifiedConversion(self):
total_rows = self.tableWidget.rowCount()
for row in range(total_rows):
... |
class MainGUI(QMainWindow):
def __init__(self):
super().__init__()
self.cc = OpenCC('s2t')
self.original_names = {}
self.initUI()
def applyTraditionalSimplifiedConversion(self):
total_rows = self.tableWidget.rowCount()
for row in range(total_rows):
... | queryDatabaseForFileNames(db_path, folder_path, self.tableWidget) | 0 | 2023-11-10 19:42:58+00:00 | 2k |
fleet-ai/code-pilot | scripts.py | [
{
"identifier": "batch",
"path": "utils/utils.py",
"snippet": "def batch(iterable, n=1):\n l = len(iterable)\n for ndx in range(0, l, n):\n yield iterable[ndx : min(ndx + n, l)]"
},
{
"identifier": "INDEX_NAME",
"path": "constants.py",
"snippet": "INDEX_NAME = \"\" # TODO a... | import os
import argparse
import pinecone
from dotenv import load_dotenv
from context import download_embeddings
from utils.utils import batch
from constants import (
INDEX_NAME,
INDEX_ENVIRONMENT,
NAMESPACE,
PATH_TO_SRC_CODE,
)
from code_indexer import CodeIndexer | 1,525 |
load_dotenv()
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
pinecone.init(api_key=PINECONE_API_KEY, environment=INDEX_ENVIRONMENT)
index = pinecone.Index(INDEX_NAME)
def read_and_upsert(library_name):
df = download_embeddings(library_name)
def convert_row_to_dict(row):
return {
"id"... |
load_dotenv()
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
pinecone.init(api_key=PINECONE_API_KEY, environment=INDEX_ENVIRONMENT)
index = pinecone.Index(INDEX_NAME)
def read_and_upsert(library_name):
df = download_embeddings(library_name)
def convert_row_to_dict(row):
return {
"id"... | _ = CodeIndexer(src_dir=PATH_TO_SRC_CODE) | 4 | 2023-11-14 01:45:16+00:00 | 2k |
bithuanglq/APF_RL | DQN_variant.py | [
{
"identifier": "RelativePosition",
"path": "gym_examples/wrappers/relative_position.py",
"snippet": "class RelativePosition(gym.ObservationWrapper):\n def __init__(self, env):\n super().__init__(env)\n self.observation_space = spaces.Box(shape=(2+25*6,), low=-np.inf, high=np.inf)\n\n\n... | import argparse
import os
import random
import time
import gym
import numpy as np
import tensorflow as tf
import tensorlayer as tl
from tqdm import tqdm
from gym_examples.wrappers import RelativePosition
from prioritized_memory import Memory | 1,008 | ''' 调试日志
1. 适配版本
https://medium.com/mlearning-ai/how-to-install-tensorflow-2-x-with-cuda-and-cudnn-on-ubuntu-20-04-lts-b73c209d8e88
2. 要用save_npz_dict 保存模型而不是 save_npz; 加载时同理
3. 用 APF 代替部分随机探索效果要好很多
4. 加入了PER: (https://blog.csdn.net/abcdefg90876/article/details/106270925), 也可以只用Original Replay Buffer
5. 超参数参考模块: hyper... | ''' 调试日志
1. 适配版本
https://medium.com/mlearning-ai/how-to-install-tensorflow-2-x-with-cuda-and-cudnn-on-ubuntu-20-04-lts-b73c209d8e88
2. 要用save_npz_dict 保存模型而不是 save_npz; 加载时同理
3. 用 APF 代替部分随机探索效果要好很多
4. 加入了PER: (https://blog.csdn.net/abcdefg90876/article/details/106270925), 也可以只用Original Replay Buffer
5. 超参数参考模块: hyper... | env = RelativePosition(env) # refer to gym_examples/wrappers/relative_position.py, observation space has changed! | 0 | 2023-11-10 02:45:37+00:00 | 2k |
ehennenfent/live_illustrate | live_illustrate/summarize.py | [
{
"identifier": "AsyncThread",
"path": "live_illustrate/util.py",
"snippet": "class AsyncThread:\n \"\"\"Generic thread that has a work queue and a callback to run on the result\"\"\"\n\n SLEEP_TIME = 0.25\n MAX_ERRORS = 5\n\n def __init__(self, logger_name=\"AsyncThread\") -> None:\n ... | from datetime import datetime
from openai import OpenAI
from .util import AsyncThread, Summary, Transcription, num_tokens_from_string | 697 |
SYSTEM_PROMPT = "You are a helpful assistant that describes scenes to an artist who wants to draw them. \
You will be given several lines of dialogue that contain details about the physical surroundings of the characters. \
Your job is to summarize the details of the scene in a bulleted list containing 4-7 bullet po... |
SYSTEM_PROMPT = "You are a helpful assistant that describes scenes to an artist who wants to draw them. \
You will be given several lines of dialogue that contain details about the physical surroundings of the characters. \
Your job is to summarize the details of the scene in a bulleted list containing 4-7 bullet po... | if (token_count := num_tokens_from_string(text)) == 0: | 3 | 2023-11-18 05:42:54+00:00 | 2k |
cyberark/ark-sdk-python | ark_sdk_python/models/services/dpa/policies/vm/ark_dpa_vm_authorization_rule.py | [
{
"identifier": "ArkProtocolType",
"path": "ark_sdk_python/models/common/ark_protocol_type.py",
"snippet": "class ArkProtocolType(str, MultiValueEnum):\n SSH = 'ssh', 'SSH'\n SCP = 'scp', 'SCP'\n SFTP = 'sftp', 'SFTP'\n RDP = 'rdp', 'RDP'\n CLI = 'cli', 'CLI'\n CONSOLE = 'console', 'Co... | from pydantic import Field, validator
from ark_sdk_python.models.common import ArkProtocolType
from ark_sdk_python.models.common.ark_workspace_type import ArkWorkspaceType
from ark_sdk_python.models.services.dpa.policies.common.ark_dpa_base_authorization_rule import ArkDPABaseAuthorizationRule
from ark_sdk_python.model... | 957 |
class ArkDPAVMConnectionInformation(ArkDPABaseConnectionInformation):
connect_as: ArkDPAVMProvidersConnectionDict = Field(description='In which fashion the connection is made')
# pylint: disable=no-self-use,no-self-argument
@validator('connect_as')
def validate_connect_as(cls, val):
for k, v... |
class ArkDPAVMConnectionInformation(ArkDPABaseConnectionInformation):
connect_as: ArkDPAVMProvidersConnectionDict = Field(description='In which fashion the connection is made')
# pylint: disable=no-self-use,no-self-argument
@validator('connect_as')
def validate_connect_as(cls, val):
for k, v... | if ArkWorkspaceType(k) not in [ArkWorkspaceType.AWS, ArkWorkspaceType.AZURE, ArkWorkspaceType.GCP, ArkWorkspaceType.ONPREM]: | 1 | 2023-11-13 09:24:31+00:00 | 2k |
Infineon/pharaoh-dev | src/pharaoh/templating/second_level/template_env.py | [
{
"identifier": "env_filters",
"path": "src/pharaoh/templating/second_level/env_filters.py",
"snippet": "DEFAULT = object()\ndef required(value):\ndef rep(value) -> str:\ndef or_default(value, default):\ndef oc_resolve(value: omegaconf.DictConfig):\ndef oc_get(cfg: omegaconf.DictConfig, key, default=DEF... | import copy
import functools
import os
import pprint
import shutil
import uuid
import jinja2
import omegaconf
import pharaoh.project
from functools import partial
from pathlib import Path
from types import ModuleType
from typing import TYPE_CHECKING, Callable
from jinja2_git import GitExtension
from pharaoh.log imp... | 1,113 | from __future__ import annotations
if TYPE_CHECKING:
class PharaohFileSystemLoader(jinja2.loaders.FileSystemLoader):
def get_source(self, environment: jinja2.Environment, template: str) -> tuple[str, str, Callable[[], bool]]:
# Overwrite to support absolute filenames as well as relative ones that h... | from __future__ import annotations
if TYPE_CHECKING:
class PharaohFileSystemLoader(jinja2.loaders.FileSystemLoader):
def get_source(self, environment: jinja2.Environment, template: str) -> tuple[str, str, Callable[[], bool]]:
# Overwrite to support absolute filenames as well as relative ones that h... | self.filters.update(env_filters) | 0 | 2023-11-10 11:33:02+00:00 | 2k |
CorentinJ/transcription-diff | transcription_diff/text_diff.py | [
{
"identifier": "normalize_text",
"path": "transcription_diff/text_normalization.py",
"snippet": "def normalize_text(raw_text: str, lang_id: str, fault_tolerant=False) -> Tuple[str, SliceMap]:\n \"\"\"\n :param fault_tolerant: issues arising in cleaning operations will not raise an exception if Tr... | import logging
import numpy as np
from dataclasses import dataclass
from pathlib import Path
from typing import List, Iterable, overload, Union
from minineedle import needle
from transcription_diff.text_normalization import normalize_text
from transcription_diff.whisper_asr import whisper_asr
from colorama import Fore ... | 1,565 | @dataclass
class TextDiffRegion:
reference_text: str
compared_text: str
pronunciation_match: bool
def clean_text_diff(ref_text: str, compared: str) -> List[TextDiffRegion]:
alignment = needle.NeedlemanWunsch(ref_text.split(" "), compared.split(" "))
alignment.align()
# Arrange
regions = [... |
logger = logging.getLogger(__name__)
@dataclass
class TextDiffRegion:
reference_text: str
compared_text: str
pronunciation_match: bool
def clean_text_diff(ref_text: str, compared: str) -> List[TextDiffRegion]:
alignment = needle.NeedlemanWunsch(ref_text.split(" "), compared.split(" "))
align... | asr_texts, lang_id = whisper_asr( | 1 | 2023-11-11 20:51:54+00:00 | 2k |
AI4HealthUOL/ECG-MIMIC | src/clinical_ts/inception1d.py | [
{
"identifier": "AdaptiveConcatPool1d",
"path": "src/clinical_ts/basic_conv1d.py",
"snippet": "class AdaptiveConcatPool1d(nn.Module):\n \"Layer that concats `AdaptiveAvgPool1d` and `AdaptiveMaxPool1d`.\"\n def __init__(self, sz=None):\n \"Output will be 2*sz or 2 if sz is None\"\n su... | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from .basic_conv1d import AdaptiveConcatPool1d,create_head1d | 1,342 | __all__ = ['conv', 'noop', 'InceptionBlock1d', 'Shortcut1d', 'InceptionBackbone', 'Inception1d', 'inception1d']
# Cell
# Cell
def conv(in_planes, out_planes, kernel_size=3, stride=1):
"convolution with padding"
return nn.Conv1d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
... | __all__ = ['conv', 'noop', 'InceptionBlock1d', 'Shortcut1d', 'InceptionBackbone', 'Inception1d', 'inception1d']
# Cell
# Cell
def conv(in_planes, out_planes, kernel_size=3, stride=1):
"convolution with padding"
return nn.Conv1d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
... | head = create_head1d(n_ks*nb_filters, nc=num_classes, lin_ftrs=lin_ftrs_head, ps=ps_head, bn_final=bn_final_head, bn=bn_head, act=act_head, concat_pooling=concat_pooling) | 1 | 2023-11-12 14:54:08+00:00 | 2k |
eblume/TyperAssistant | src/typerassistant/assistant.py | [
{
"identifier": "FunctionCall",
"path": "src/typerassistant/spec.py",
"snippet": "class FunctionCall:\n call_id: str\n function: FunctionSpec\n parameters: dict[str, Any]\n\n def dict(self) -> dict:\n return {\n \"call_id\": self.call_id,\n \"function\": self.fun... | import json
import time
from collections.abc import Iterable
from contextlib import redirect_stdout
from dataclasses import KW_ONLY, dataclass, field
from io import StringIO
from textwrap import shorten
from typing import Optional, Type, TypeVar
from openai import OpenAI
from openai.types.beta.assistant import Assistan... | 1,164 |
# The number of times to poll for a run to complete before giving up
MAX_RUN_ITERATIONS = 20
# The number of seconds to sleep between run iterations
RUN_ITERATION_SLEEP = 3
# The best usage guide for function calling seems to be:
# https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models
As... |
# The number of times to poll for a run to complete before giving up
MAX_RUN_ITERATIONS = 20
# The number of seconds to sleep between run iterations
RUN_ITERATION_SLEEP = 3
# The best usage guide for function calling seems to be:
# https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models
As... | def functions(self) -> Iterable[FunctionSpec]: | 1 | 2023-11-17 19:43:55+00:00 | 2k |
Mat931/digitalstrom-homeassistant | custom_components/digitalstrom/binary_sensor.py | [
{
"identifier": "CONF_DSUID",
"path": "custom_components/digitalstrom/const.py",
"snippet": "CONF_DSUID: str = \"dsuid\""
},
{
"identifier": "DOMAIN",
"path": "custom_components/digitalstrom/const.py",
"snippet": "DOMAIN = \"digitalstrom\""
},
{
"identifier": "DigitalstromEntity"... | import logging
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistan... | 1,365 | name="Brightness",
device_class=BinarySensorDeviceClass.LIGHT,
),
3: BinarySensorEntityDescription(
key="3",
name="Presence in darkness",
device_class=BinarySensorDeviceClass.PRESENCE,
),
4: BinarySensorEntityDescription(
key="4",
name="Twilight",
... |
_LOGGER = logging.getLogger(__name__)
BINARY_SENSORS_MAP: dict[int, BinarySensorEntityDescription] = {
-1: BinarySensorEntityDescription(
key="unknown",
name="Unknown binary input",
),
0: BinarySensorEntityDescription(
key="0",
name="Binary input",
),
1: BinarySen... | client = hass.data[DOMAIN][config_entry.data[CONF_DSUID]]["client"] | 0 | 2023-11-10 16:42:38+00:00 | 2k |
mohenghui/detectAuto_v8 | ultralytics/models/sam/modules/encoders.py | [
{
"identifier": "LayerNorm2d",
"path": "ultralytics/nn/modules/transformer.py",
"snippet": "class LayerNorm2d(nn.Module):\n \"\"\"\n 2D Layer Normalization module inspired by Detectron2 and ConvNeXt implementations.\n\n Original implementations in\n https://github.com/facebookresearch/detect... | from typing import Any, Optional, Tuple, Type
from ultralytics.nn.modules import LayerNorm2d, MLPBlock
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F | 1,374 | # Ultralytics YOLO 🚀, AGPL-3.0 license
class ImageEncoderViT(nn.Module):
"""
An image encoder using Vision Transformer (ViT) architecture for encoding an image into a compact latent space. The
encoder takes an image, splits it into patches, and processes these patches through a series of transformer b... | # Ultralytics YOLO 🚀, AGPL-3.0 license
class ImageEncoderViT(nn.Module):
"""
An image encoder using Vision Transformer (ViT) architecture for encoding an image into a compact latent space. The
encoder takes an image, splits it into patches, and processes these patches through a series of transformer b... | LayerNorm2d(out_chans), | 0 | 2023-11-16 12:49:59+00:00 | 2k |
i-super/Saleor | saleor/webhook/observability/tests/conftest.py | [
{
"identifier": "schema",
"path": "saleor/graphql/api.py",
"snippet": "API_PATH = SimpleLazyObject(lambda: reverse(\"api\"))\nclass Query(\n AccountQueries,\n AppQueries,\n AttributeQueries,\n ChannelQueries,\n CheckoutQueries,\n CoreQueries,\n CsvQueries,\n DiscountQueries,\n ... | from typing import Optional
from unittest.mock import patch
from django.core.cache import cache
from graphql import get_default_backend
from redis import ConnectionPool
from ....graphql.api import schema
from ..buffers import RedisBuffer
from ..utils import GraphQLOperationResponse, get_buffer_name
import fakeredis
imp... | 1,586 |
backend = get_default_backend()
BROKER_URL_HOST = "fake-redis"
BROKER_URL = f"redis://{BROKER_URL_HOST}"
KEY, MAX_SIZE, BATCH_SIZE = get_buffer_name(), 10, 5
@pytest.fixture
def gql_operation_factory():
def factory(
query_string: str,
operation_name: Optional[str] = None,
variables: Op... |
backend = get_default_backend()
BROKER_URL_HOST = "fake-redis"
BROKER_URL = f"redis://{BROKER_URL_HOST}"
KEY, MAX_SIZE, BATCH_SIZE = get_buffer_name(), 10, 5
@pytest.fixture
def gql_operation_factory():
def factory(
query_string: str,
operation_name: Optional[str] = None,
variables: Op... | query = backend.document_from_string(schema, query_string) | 0 | 2023-11-13 05:00:35+00:00 | 2k |
Aues6uen11Z/Zafkiel | zafkiel/ui/switch.py | [
{
"identifier": "ImageTemplate",
"path": "zafkiel/device/template.py",
"snippet": "class ImageTemplate(Template):\n def __init__(\n self,\n filename: str,\n record_pos: tuple = None,\n keyword: Keyword = None,\n threshold: float = None,\n ... | from zafkiel.device.template import ImageTemplate as Template
from zafkiel.exception import ScriptError | 1,484 |
class Switch:
"""
A wrapper to handle switches in game, switch among states with retries.
Main code comes from https://github.com/LmeSzinc/StarRailCopilot/blob/master/module/ui/switch.py
Examples:
# Definitions
submarine_hunt = Switch('Submarine_hunt', offset=120)
submarine_hu... |
class Switch:
"""
A wrapper to handle switches in game, switch among states with retries.
Main code comes from https://github.com/LmeSzinc/StarRailCopilot/blob/master/module/ui/switch.py
Examples:
# Definitions
submarine_hunt = Switch('Submarine_hunt', offset=120)
submarine_hu... | raise ScriptError(f'Switch {self.name} received an invalid state {state}') | 1 | 2023-11-12 09:33:35+00:00 | 2k |
medkit-lib/medkit | tests/unit/training/dummy_context_component/dummy_component.py | [
{
"identifier": "BatchData",
"path": "medkit/training/utils.py",
"snippet": "class BatchData(dict):\n \"\"\"A BatchData pack data allowing both column and row access\"\"\"\n\n def __getitem__(self, index: int) -> Dict[str, Union[List[Any], torch.Tensor]]:\n if isinstance(index, str):\n ... | import os
import torch
from typing import Optional
from medkit.training import BatchData
from .dummy_model import DummyTextCat, DummyTextCatConfig, DummyTokenizer | 746 |
PYTORCH_MODEL_NAME = "pytorch_model.bin"
class MockTrainableComponent:
def __init__(
self,
model_path: Optional[str] = None,
output_label: str = "category",
device="cpu",
):
self.tokenizer = DummyTokenizer()
# load architecture
|
PYTORCH_MODEL_NAME = "pytorch_model.bin"
class MockTrainableComponent:
def __init__(
self,
model_path: Optional[str] = None,
output_label: str = "category",
device="cpu",
):
self.tokenizer = DummyTokenizer()
# load architecture | self.model = DummyTextCat(config=DummyTextCatConfig()) | 2 | 2023-11-13 16:28:56+00:00 | 2k |
donahowe/VE-MLD | src_files/models/utils/factory.py | [
{
"identifier": "add_ml_decoder_head",
"path": "src_files/ml_decoder/ml_decoder.py",
"snippet": "def add_ml_decoder_head(model, num_classes=-1, num_of_groups=-1, decoder_embedding=768, zsl=0):\n if num_classes == -1:\n num_classes = model.num_classes\n num_features = model.num_features\n ... | import logging
import os
import torch
from urllib import request
from ...ml_decoder.ml_decoder import add_ml_decoder_head
from ..tresnet import TResnetM, TResnetL, TResnetXL
from ..vit import VE | 835 |
logger = logging.getLogger(__name__)
def create_model(args,load_head=False):
"""Create a model
"""
model_params = {'args': args, 'num_classes': args.num_classes, 'image_size': args.image_size}
args = model_params['args']
args.model_name = args.model_name.lower()
if args.model_name == 'vi... |
logger = logging.getLogger(__name__)
def create_model(args,load_head=False):
"""Create a model
"""
model_params = {'args': args, 'num_classes': args.num_classes, 'image_size': args.image_size}
args = model_params['args']
args.model_name = args.model_name.lower()
if args.model_name == 'vi... | model = TResnetL(model_params) | 2 | 2023-11-13 04:12:26+00:00 | 2k |
WindowsSov8forUs/bestdori_api | bestdori/utils/network.py | [
{
"identifier": "AssetsNotExistError",
"path": "bestdori/exceptions.py",
"snippet": "class AssetsNotExistError(AssetsException):\n '''资源不存在'''\n # 初始化\n def __init__(self, asset_name: str) -> None:\n msg = f'资源 {asset_name} 可能不存在。'\n super().__init__(msg)"
},
{
"identifier... | from json import dumps
from io import BufferedReader
from httpx._models import Cookies
from httpx import Response, Request, Client
from typing import Optional, Literal, cast, Any
from ..exceptions import (
AssetsNotExistError,
RequestException,
REQUEST_EXCEPTION
) | 1,202 | '''`bestdori.utils.network`
向 Bestdori 发送请求相关模块'''
# 向 Bestdori 发送 API 请求类
class Api:
'''向 Bestdori 发送 API 请求类
参数:
api (str): 请求的 API 地址
proxy (Optional[str]): 代理服务器'''
api: str
'''请求的 API 地址'''
proxy: Optional[str]=None
'''代理服务器'''
headers: dict[str, str]
''... | '''`bestdori.utils.network`
向 Bestdori 发送请求相关模块'''
# 向 Bestdori 发送 API 请求类
class Api:
'''向 Bestdori 发送 API 请求类
参数:
api (str): 请求的 API 地址
proxy (Optional[str]): 代理服务器'''
api: str
'''请求的 API 地址'''
proxy: Optional[str]=None
'''代理服务器'''
headers: dict[str, str]
''... | raise RequestException(self.api, code) | 1 | 2023-11-16 13:09:20+00:00 | 2k |
jidiai/Competition_OvercookedAI-2 | run_log.py | [
{
"identifier": "make",
"path": "env/chooseenv.py",
"snippet": "def make(env_type, seed=None, conf=None):\n file_path = os.path.join(os.path.dirname(__file__), 'config.json')\n if not conf:\n with open(file_path) as f:\n conf = json.load(f)[env_type]\n class_literal = conf['cl... | import os
import time
import json
import numpy as np
import argparse
import sys
from env.chooseenv import make
from utils.get_logger import get_logger
from env.obs_interfaces.observation import obs_type | 1,348 | # -*- coding:utf-8 -*-
sys.path.append("./olympics_engine")
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
... | # -*- coding:utf-8 -*-
sys.path.append("./olympics_engine")
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
... | logger = get_logger(log_path, g.game_name, json_file=render_mode) | 1 | 2023-11-15 09:09:01+00:00 | 2k |
AnonymGiant/ViLaM | lavis/processors/blip_processors.py | [
{
"identifier": "registry",
"path": "lavis/common/registry.py",
"snippet": "class Registry:\n def register_builder(cls, name):\n def wrap(builder_cls):\n def register_task(cls, name):\n def wrap(task_cls):\n def register_model(cls, name):\n def wrap(model_cls):\n def reg... | import re
from lavis.common.registry import registry
from lavis.processors.base_processor import BaseProcessor
from lavis.processors.randaugment import RandomAugment
from omegaconf import OmegaConf
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode | 832 | """
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
class BlipImageBaseProcessor(BaseProcessor):
def __init__(self, mean=None, std=None):
... | """
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
class BlipImageBaseProcessor(BaseProcessor):
def __init__(self, mean=None, std=None):
... | @registry.register_processor("blip_caption") | 0 | 2023-11-14 08:57:59+00:00 | 2k |
MorrisNein/pecapiku | pecapiku/single_value_cache.py | [
{
"identifier": "BaseCache",
"path": "pecapiku/base_cache.py",
"snippet": "class omnimethod(Generic[DecoratedCallable]):\nclass BaseCache(ABC):\n def __init__(self, func: DecoratedCallable):\n def __get__(self, instance, owner) -> DecoratedCallable:\n def __init__(self, file_path: os.PathLike |... | import os
from functools import partial, wraps
from typing import Any, Generic, Hashable
from pecapiku.base_cache import BaseCache, DecoratedCallable, Decorator, omnimethod
from pecapiku.cache_access import CacheAccess, _initialize_cache, _resolve_filepath, update_cache
from pecapiku.no_cache import NoCache | 912 | from __future__ import annotations
class SingleValueCache(BaseCache, Generic[DecoratedCallable]):
""" Decorator for caching of evaluation results.
Creates a "pickle" file at disk space on a specified path.
Wraps a function and stores its execution result in the file.
To apply, use the method ``Singl... | from __future__ import annotations
class SingleValueCache(BaseCache, Generic[DecoratedCallable]):
""" Decorator for caching of evaluation results.
Creates a "pickle" file at disk space on a specified path.
Wraps a function and stores its execution result in the file.
To apply, use the method ``Singl... | access: CacheAccess | None = None) -> DecoratedCallable | Decorator: | 0 | 2023-11-17 12:10:01+00:00 | 2k |
gerlaxrex/parrot | parrot1/audio/extraction/audio_extraction.py | [
{
"identifier": "get_extension",
"path": "parrot1/utils/file_utils.py",
"snippet": "def get_extension(filename: Union[str, os.PathLike]) -> str:\n return os.path.basename(filename).rsplit(\".\", 1)[1]"
},
{
"identifier": "split_on_silence",
"path": "parrot1/audio/utils/silence.py",
"s... | import logging
import os
from typing import List, Union
from pydub import AudioSegment
from tqdm import tqdm
from parrot1.utils.file_utils import get_extension
from parrot1.audio.utils.silence import split_on_silence | 653 |
__logger = logging.getLogger(__name__)
def get_audio_from_video(video_filename: Union[str, os.PathLike]) -> AudioSegment:
"""
Takes the audio from the video file
:param video_filename: (Union[str, os.PathLike]) path to the video
:return: (io.BytesIO) Audio bytes
"""
if not os.path.exists(v... |
__logger = logging.getLogger(__name__)
def get_audio_from_video(video_filename: Union[str, os.PathLike]) -> AudioSegment:
"""
Takes the audio from the video file
:param video_filename: (Union[str, os.PathLike]) path to the video
:return: (io.BytesIO) Audio bytes
"""
if not os.path.exists(v... | audio = AudioSegment.from_file(video_filename, format=get_extension(video_filename)) | 0 | 2023-11-14 22:33:32+00:00 | 2k |
chenaoxuan/UsfUtils | usfutils/config.py | [
{
"identifier": "master_only",
"path": "usfutils/dist.py",
"snippet": "def master_only(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n rank, _ = get_dist_info()\n if rank == 0:\n return func(*args, **kwargs)\n\n return wrapper"
},
{
"identifier... | import io
import os
import sys
import yaml
from shutil import copyfile
from typing import Union
from .dist import master_only
from .time import get_time_asc
from .dict import UsfDict | 669 |
__all__ = [
'load_yaml',
'dict_to_yaml',
'copy_opt_file'
]
|
__all__ = [
'load_yaml',
'dict_to_yaml',
'copy_opt_file'
]
| def load_yaml(path: str) -> UsfDict: | 2 | 2023-11-16 04:39:34+00:00 | 2k |
ErdemOzgen/DevSecOpsBuilder | main.py | [
{
"identifier": "pipeline_executer",
"path": "devsecopsbuilder/pipeline_executer.py",
"snippet": "def load_configuration(filepath):\ndef create_output_directory(directory):\ndef install_tools(tools):\ndef update_tools(tools):\ndef run_command(step, output_dir, **kwargs):\ndef execute_post_command(step, ... | import argparse
import networkx as nx
import matplotlib.pyplot as plt
from devsecopsbuilder import pipeline_executer
from devsecopsbuilder import convert_graph
from devsecopsbuilder import convert_pipeline
from devsecopsbuilder import generate_report # noqa: F401
from devsecopsbuilder import asciiart | 1,292 |
def main():
parser = argparse.ArgumentParser(description="Pipeline Execution Script")
parser.add_argument("--install", action="store_true", help="Install tools")
parser.add_argument("--update", action="store_true", help="Update tools")
parser.add_argument(
"--execute", action="store_true", hel... |
def main():
parser = argparse.ArgumentParser(description="Pipeline Execution Script")
parser.add_argument("--install", action="store_true", help="Install tools")
parser.add_argument("--update", action="store_true", help="Update tools")
parser.add_argument(
"--execute", action="store_true", hel... | workflow_graph = convert_graph.parse_yaml_and_create_graph(args.graph_yaml) # noqa: E501 | 1 | 2023-11-14 07:50:52+00:00 | 2k |
doodledood/chat-flock | chatflock/participants/user.py | [
{
"identifier": "ActiveChatParticipant",
"path": "chatflock/base.py",
"snippet": "class ActiveChatParticipant(ChatParticipant):\n symbol: str\n messages_hidden: bool = False\n\n def __init__(self, name: str, symbol: str = \"👤\", messages_hidden: bool = False):\n super().__init__(name=na... | from typing import Any
from chatflock.base import ActiveChatParticipant, Chat | 1,260 |
class UserChatParticipant(ActiveChatParticipant):
def __init__(self, name: str = "User", role: str = "User", symbol: str = "👤", **kwargs: Any):
super().__init__(name, messages_hidden=True, **kwargs)
self.role = role
self.symbol = symbol
|
class UserChatParticipant(ActiveChatParticipant):
def __init__(self, name: str = "User", role: str = "User", symbol: str = "👤", **kwargs: Any):
super().__init__(name, messages_hidden=True, **kwargs)
self.role = role
self.symbol = symbol
| def respond_to_chat(self, chat: Chat) -> str: | 1 | 2023-11-12 11:10:58+00:00 | 2k |
phidatahq/junior-de | app/pages/3_DuckGPT_S3.py | [
{
"identifier": "get_openai_key",
"path": "app/openai_key.py",
"snippet": "def get_openai_key() -> Optional[str]:\n \"\"\"Sidebar component to get OpenAI API key\"\"\"\n\n # Get OpenAI API key from environment variable\n openai_key: Optional[str] = getenv(\"OPENAI_API_KEY\")\n # If not found... | from typing import List
from phi.conversation import Conversation
from app.openai_key import get_openai_key
from app.password import check_password
from app.reload import reload_button
from app.user_name import get_user_name
from duckgpt.s3_tables import load_s3_tables
from llm.conversations.duckgpt_s3 import duckdb_s3... | 1,278 |
st.title(":snowman: DuckGPT")
st.markdown('<a href="https://github.com/phidatahq/phidata"><h4>by phidata</h4></a>', unsafe_allow_html=True)
def restart_conversation():
st.session_state["s3_conversation"] = None
st.session_state["s3_conversation_id"] = None
st.rerun()
def main() -> None:
# Get us... |
st.title(":snowman: DuckGPT")
st.markdown('<a href="https://github.com/phidatahq/phidata"><h4>by phidata</h4></a>', unsafe_allow_html=True)
def restart_conversation():
st.session_state["s3_conversation"] = None
st.session_state["s3_conversation_id"] = None
st.rerun()
def main() -> None:
# Get us... | user_name = get_user_name() | 3 | 2023-11-14 10:44:20+00:00 | 2k |
YoungJooHan/NM-FlowGAN | util/file_manager.py | [
{
"identifier": "tensor2np",
"path": "util/util.py",
"snippet": "def tensor2np(t:torch.Tensor):\n '''\n transform torch Tensor to numpy having opencv image form.\n RGB -> BGR\n (c,h,w) -> (h,w,c)\n '''\n t = t.cpu().detach()\n\n # gray\n if len(t.shape) == 2:\n return t.pe... | import os
import cv2
import numpy as np
import torch
from .util import tensor2np, save_img | 789 |
class FileManager:
def __init__(self, session_name, output_path=None):
if output_path is None:
self.output_folder = "./output"
else:
self.output_folder = output_path
if not os.path.isdir(self.output_folder):
os.makedirs(self.output_folder)
... |
class FileManager:
def __init__(self, session_name, output_path=None):
if output_path is None:
self.output_folder = "./output"
else:
self.output_folder = output_path
if not os.path.isdir(self.output_folder):
os.makedirs(self.output_folder)
... | save_img(self.get_dir(dir_name), '%s.%s'%(file_name, ext), np.squeeze(img, 2)) | 1 | 2023-11-16 02:22:32+00:00 | 2k |
VCasecnikovs/RAGAgainstTheMachine | sourcing.py | [
{
"identifier": "chat_inference",
"path": "chatting.py",
"snippet": "def chat_inference(\n messages: list[ChatMessage],\n client: OpenAI,\n model=\"gpt-4-1106-preview\",\n):\n formatted_messages = []\n for message in messages:\n formatted_messages.append(\n {\n ... | import requests
import os
import json
from dotenv import load_dotenv
from newspaper import Article
from chatting import chat_inference, ChatMessage, get_openAI_client, Role | 1,090 | YOU_HEADERS = {"X-API-Key": os.environ.get("YOUCOM_API_KEY", "")}
def _get_you_search_impl(
query: str, page_index: int = 0, limit: int = 20, country: str = ""
):
url = "https://api.ydc-index.io/search"
query_args = {"query": query}
if page_index:
query_args["offset"] = page_index
if limi... |
load_dotenv()
YOU_HEADERS = {"X-API-Key": os.environ.get("YOUCOM_API_KEY", "")}
def _get_you_search_impl(
query: str, page_index: int = 0, limit: int = 20, country: str = ""
):
url = "https://api.ydc-index.io/search"
query_args = {"query": query}
if page_index:
query_args["offset"] = page_i... | client = get_openAI_client() | 2 | 2023-11-18 22:12:07+00:00 | 2k |
TimeEnjoyed/TimeBot | core/bots.py | [
{
"identifier": "config",
"path": "core/config.py",
"snippet": ""
},
{
"identifier": "MBTI_TYPES",
"path": "core/constants.py",
"snippet": "MBTI_TYPES: list[str] = [\n \"ESTP\",\n \"ESTJ\",\n \"ESFP\",\n \"ESFJ\",\n \"ISTP\",\n \"ISTJ\",\n \"ISFP\",\n \"ISFJ\",\n ... | import asyncio
import json
import logging
import pathlib
import aiohttp
import discord
import twitchio
import wavelink
from typing import TYPE_CHECKING
from urllib.parse import quote
from discord.ext import commands
from twitchio.ext import commands as tcommands
from .config import config
from .constants import MBTI_TY... | 1,296 | if TYPE_CHECKING:
logger: logging.Logger = logging.getLogger(__name__)
LIVE_ROLE_ID: int = 1182206699969458226
SUBBED_ROLE_ID: int = 873044115279990836
class DiscordBot(commands.Bot):
tbot: TwitchBot
def __init__(self, *, database: Database) -> None:
self.database = database
intents: dis... | """Copyright 2023 TimeEnjoyed <https://github.com/TimeEnjoyed/>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or ... | mbti_dict: dict[str, int] = dict.fromkeys(MBTI_TYPES, 0) | 1 | 2023-11-15 23:04:42+00:00 | 2k |
henriquesebastiao/poupy | project/apps/app/views/transfer.py | [
{
"identifier": "TransferForm",
"path": "project/apps/app/forms.py",
"snippet": "class TransferForm(forms.Form):\n \"\"\"Form used to transfer money between accounts.\"\"\"\n\n description = forms.CharField(\n label='Description',\n widget=forms.TextInput(\n attrs={'placeh... | from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.views.generic import FormView
from ..forms import TransferForm
from ..models import Account, Transfer | 643 | """Views for transfer app."""
class TransferView(LoginRequiredMixin, FormView):
"""Transfer view page."""
login_url = 'login'
template_name = 'pages/app/new_transfer.html'
| """Views for transfer app."""
class TransferView(LoginRequiredMixin, FormView):
"""Transfer view page."""
login_url = 'login'
template_name = 'pages/app/new_transfer.html' | form_class = TransferForm | 0 | 2023-11-17 21:05:05+00:00 | 2k |
AuroraNemoia/yuusei | main.py | [
{
"identifier": "log",
"path": "utils.py",
"snippet": "def log(text, type=\"normal\"):\n types = {\n \"quiet\": \"\\x1b[33;90m\",\n \"warn\": \"\\x1b[33;20m⚠️ WARN: \",\n \"error\": \"\\x1b[31;1m❌ ERROR: \",\n \"normal\": \"\\x1b[33;0m\"\n }\n print(types.get(type, t... | import requests
import json
import jstyleson
import os
import time
import random
import generate
import history
from utils import log, basepath, tokenize | 701 |
# Constants
config = jstyleson.loads(open(basepath() + "/config.json", "r").read())
# Initialize self
self_name = config["personality"]["name"]
self_persona = config["personality"]["persona"]
self_instruct_pre = config["personality"]["pre"]
self_instruct_post = config["personality"]["post"]
use_chat_completions = con... |
# Constants
config = jstyleson.loads(open(basepath() + "/config.json", "r").read())
# Initialize self
self_name = config["personality"]["name"]
self_persona = config["personality"]["persona"]
self_instruct_pre = config["personality"]["pre"]
self_instruct_post = config["personality"]["post"]
use_chat_completions = con... | log(prompt) | 0 | 2023-11-14 05:04:40+00:00 | 2k |
gunyu1019/async-client-decorator | example/single_session.py | [
{
"identifier": "request",
"path": "async_client_decorator/request.py",
"snippet": "def request(\n method: str,\n path: str,\n directly_response: bool = False,\n header_parameter: list[str] = None,\n query_parameter: list[str] = None,\n form_parameter: list[str] = None,\n path_param... | import asyncio
import aiohttp
from typing import NamedTuple
from async_client_decorator import request, Session, Query | 1,277 |
loop = asyncio.get_event_loop()
class StationInfo(NamedTuple):
displayId: str
id: str
name: str
posX: float
posY: float
stationId: str
type: int
|
loop = asyncio.get_event_loop()
class StationInfo(NamedTuple):
displayId: str
id: str
name: str
posX: float
posY: float
stationId: str
type: int
| @Session.single_session("https://api.yhs.kr") | 2 | 2023-11-14 06:41:19+00:00 | 2k |
pmutua/CodeCraftGPT | components/lang_page.py | [
{
"identifier": "PROGRAMMING_LANGUAGES",
"path": "data/programming_languages.py",
"snippet": "PROGRAMMING_LANGUAGES = (\n \"Python\", \"JavaScript\", \"Java\", \"C++\", \"C#\", \"Ruby\", \"Swift\", \"Go\", \"PHP\", \"Rust\", \"VB.net\",\n \"Kotlin\", \"TypeScript\", \"Scala\", \"Haskell\", \"Perl\... | from typing import Type
from langchain.chains import LLMChain
from langchain.chat_models import ChatOpenAI
from data.programming_languages import PROGRAMMING_LANGUAGES
from prompts.translate_code_prompt import create_translation_prompt
import streamlit as st | 674 | """
LangLink - Code Translation and Cross-Language Compatibility
Overcome language barriers with LangLink, an AI-powered tool facilitating smooth code translation
between programming languages. Developers can confidently migrate codebases, ensuring compatibility
and seamless transitions across different languages.
"""... | """
LangLink - Code Translation and Cross-Language Compatibility
Overcome language barriers with LangLink, an AI-powered tool facilitating smooth code translation
between programming languages. Developers can confidently migrate codebases, ensuring compatibility
and seamless transitions across different languages.
"""... | chat_prompt = create_translation_prompt(target_language,source_code) | 1 | 2023-11-13 10:45:28+00:00 | 2k |
itzshukla/STRANGER-USERBOT2.0 | Zaid/modules/private/pmguard.py | [
{
"identifier": "get_approved_users",
"path": "Zaid/database/pmpermitdb.py",
"snippet": "async def get_approved_users():\n results = await collection.find_one({\"_id\": \"Approved\"})\n if results:\n return results[\"users\"]\n else:\n return []"
},
{
"identifier": "pm_gua... | from pyrogram import filters, Client
from pyrogram.types import Message
from pyrogram.methods import messages
from Zaid.database.pmpermitdb import get_approved_users, pm_guard
from config import LOG_GROUP, PM_LOGGER
import asyncio
import Zaid.database.pmpermitdb as Zaid | 894 |
FLOOD_CTRL = 0
ALLOWED = []
USERS_AND_WARNS = {}
async def denied_users(filter, client: Client, message: Message):
if not await pm_guard():
return False
if message.chat.id in (await get_approved_users()):
return False
else:
return True
def get_arg(message):
msg = message.text... |
FLOOD_CTRL = 0
ALLOWED = []
USERS_AND_WARNS = {}
async def denied_users(filter, client: Client, message: Message):
if not await pm_guard():
return False
if message.chat.id in (await get_approved_users()):
return False
else:
return True
def get_arg(message):
msg = message.text... | if PM_LOGGER: | 3 | 2023-11-13 18:19:50+00:00 | 2k |
UWNetworksLab/adn-compiler | compiler/element/optimize/consolidate.py | [
{
"identifier": "ELEMENT_LOG",
"path": "compiler/element/logger.py",
"snippet": "ELEMENT_LOG = logging.getLogger(\"ir\")"
},
{
"identifier": "Expr",
"path": "compiler/element/node.py",
"snippet": "class Expr(Node):\n def __init__(self, lhs: Expr, op: Operator, rhs: Expr):\n sel... | from copy import deepcopy
from typing import Callable, Dict, List, Optional, Protocol, Sequence, Tuple, TypeVar
from compiler.element.logger import ELEMENT_LOG as LOG
from compiler.element.node import *
from compiler.element.node import Expr, Identifier, Internal, MethodCall, Procedure
from compiler.element.visitor imp... | 952 |
def consolidate(irs: List[Program]) -> Program:
while len(irs) > 1:
left = irs.pop(0)
right = irs.pop(0)
new_prog = Program(
Internal([]),
Procedure("init", [], []),
Procedure("req", [], []),
Procedure("resp", [], []),
)
new... |
def consolidate(irs: List[Program]) -> Program:
while len(irs) > 1:
left = irs.pop(0)
right = irs.pop(0)
new_prog = Program(
Internal([]),
Procedure("init", [], []),
Procedure("req", [], []),
Procedure("resp", [], []),
)
new... | LOG.error("InitConsolidator: visitNode not implemented") | 1 | 2023-11-13 07:31:52+00:00 | 2k |
sunholo-data/sunholo-py | sunholo/components/llm.py | [
{
"identifier": "setup_logging",
"path": "sunholo/logging.py",
"snippet": "def setup_logging(self, log_level=logging.INFO, logger_name=None):\n if log_level:\n self.log_level = log_level\n if logger_name:\n self.logger_name = logger_name\n\n try:\n caller_info = self._get_c... | from ..logging import setup_logging
from ..utils.config import load_config_key, load_config, get_module_filepath
from langchain.chat_models import ChatOpenAI
from langchain.llms import VertexAI
from langchain.llms import VertexAI
from ..patches.langchain.vertexai import VertexAIModelGard... | 1,108 | # Copyright [2023] [Holosun ApS]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright [2023] [Holosun ApS]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | llm_str = load_config_key("llm", vector_name, filename = "config/llm_config.yaml") | 1 | 2023-11-14 14:53:19+00:00 | 2k |
atlantic-quantum/Shipyard | tests/passes/semantic_analysis/test_scoped_symbol_table.py | [
{
"identifier": "scoped_symbol_table",
"path": "shipyard/passes/semantic_analysis/scoped_symbol_table.py",
"snippet": "class ScopedSymbolTable:\nclass CalScopedSymbolTable(ScopedSymbolTable):\n def __init__(\n self,\n scope_name: str,\n enclosing_scope: \"ScopedSymbolTable\" = No... | import pytest
from shipyard.passes.semantic_analysis import scoped_symbol_table as sst
from shipyard.passes.semantic_analysis import symbols | 1,413 | """
The scoped symbol table is intended to be used by the Semantic Analyser module.
An 'end-to-end' use case example will be included in the tests for the Semantic Analyser
ToDo update working when adding semantic analyser tests
"""
SYMBOL_LISTS = [sst.BUILTIN_TYPES, sst.BUILTIN_ZI_EXP]
CAL_SYMBOL_LISTS = [sst.BUILT... | """
The scoped symbol table is intended to be used by the Semantic Analyser module.
An 'end-to-end' use case example will be included in the tests for the Semantic Analyser
ToDo update working when adding semantic analyser tests
"""
SYMBOL_LISTS = [sst.BUILTIN_TYPES, sst.BUILTIN_ZI_EXP]
CAL_SYMBOL_LISTS = [sst.BUILT... | c_symbol = symbols.ClassicalSymbol(name="test", kind=symbols.angle_type.name) | 1 | 2023-11-16 17:37:29+00:00 | 2k |
PrAsAnNaRePo/LocalAgent | localagent/interpreter.py | [
{
"identifier": "get_prompt_from_template",
"path": "localagent/utils.py",
"snippet": "def get_prompt_from_template(system, history, human_, assistant_, eos_token):\n for i in history:\n if i['role'] == 'user':\n system += f'{human_}{i[\"content\"]}{eos_token}'\n ... | import subprocess
import sys
from localagent.utils import get_prompt_from_template, internal_monologue
from localagent.gen import run, stream_run, ollama_generate
from rich.console import Console | 1,594 |
console = Console()
CODE_INTERPRETER = """You are Open Interpreter, a world-class programmer that can complete any goal by executing code.
First, write a plan. **Always recap the plan between each code block**.
When you execute code, it will be executed **on the user's machine**. The user has given you **full and com... |
console = Console()
CODE_INTERPRETER = """You are Open Interpreter, a world-class programmer that can complete any goal by executing code.
First, write a plan. **Always recap the plan between each code block**.
When you execute code, it will be executed **on the user's machine**. The user has given you **full and com... | internal_monologue("Interpreter is executing the code...\n") | 1 | 2023-11-10 07:47:41+00:00 | 2k |
Cymaphore/orfodon-service | orfodon_service.py | [
{
"identifier": "config",
"path": "config.py",
"snippet": ""
},
{
"identifier": "feeds",
"path": "feeds.py",
"snippet": ""
},
{
"identifier": "hashtag_replace",
"path": "hashtag_modification.py",
"snippet": ""
},
{
"identifier": "hashtag_blacklist",
"path": "h... | import re
import yaml
import copy
import feedparser
import time
import requests
import hashlib
from datetime import datetime
from bs4 import BeautifulSoup
from mastodon import Mastodon
from pprint import pprint
from config import config
from credentials import credentials
from feeds import feeds
from hashtag_modificati... | 1,155 | hashtag_wordlist = []
#############################################################################
##
# Main function
# Call all the stages in correct order
def main():
# Load hashtag wordlists
load_hashtags()
# Load previous state, initialize new state
load_state()
# Load the conf... | ##
# @mainpage ORFodon service script
#
# Quick and dirty solution to turn ORF.at into a Mastodon-site
#
# @Warning this is tailormade for ORF.at and will not work without modification
# with other RSS based news sites!
#
# Inspired by feediverse from Ed Summers
#
# Process configuration, fetch news entries and post t... | if not category in oewa_bypass: | 6 | 2023-11-10 10:25:43+00:00 | 2k |
Vitesco-Technologies/ldap-password-rotation | tests/test_lambda.py | [
{
"identifier": "lambda_function",
"path": "src/lambda_function.py",
"snippet": "SECRETS_MANAGER_KEY_USERNAME = (\n os.environ.get(\"SECRETS_MANAGER_KEY_USERNAME\") or \"username\"\n)\nSECRETS_MANAGER_KEY_PASSWORD = (\n os.environ.get(\"SECRETS_MANAGER_KEY_PASSWORD\") or \"password\"\n)\nSECRETS_M... | import json
import logging
import os
import boto3
import ldap3
import mock
import pytest
from uuid import uuid4
from moto import mock_lambda, mock_secretsmanager
from src import lambda_function
from .utilities import lambda_util
from .utilities.ldap_test import LdapServer | 1,047 | # Copyright 2023 Daniel Dias, Vitesco Technologies
#
# SPDX-License-Identifier: Apache-2.0
_region = "eu-central-1"
# server is defined as global to allow us to update it when we mock
# ldap3.extend.microsoft.modifyPassword.ad_modify_password with mock_ad_modify_password
_server = LdapServer()
logger = logging.get... | # Copyright 2023 Daniel Dias, Vitesco Technologies
#
# SPDX-License-Identifier: Apache-2.0
_region = "eu-central-1"
# server is defined as global to allow us to update it when we mock
# ldap3.extend.microsoft.modifyPassword.ad_modify_password with mock_ad_modify_password
_server = LdapServer()
logger = logging.get... | lambda_function.SECRETS_MANAGER_KEY_USERNAME = "bind_dn" | 0 | 2023-11-17 15:03:58+00:00 | 2k |
totallynotadi/vibrant-python | vibrant/main.py | [
{
"identifier": "generate",
"path": "vibrant/generator.py",
"snippet": "def generate(swatches: List[Swatch]) -> Palette:\n max_poplation = find_max_population(swatches)\n\n palette: Palette = generate_variation_colors(\n swatches, max_poplation, generator_opts\n )\n generate_empty_swa... | import io
from typing import Union
from PIL.Image import Image as PILImage
from vibrant.generator import generate
from vibrant.image import VibrantImage
from vibrant.models import Palette, Props | 1,052 |
class Vibrant:
props: Props
def __init__(self, color_count=64, quality=5) -> None:
self.props = Props(color_count=color_count, quality=quality)
def get_palette(
self,
src: Union[
bytes,
str,
io.BytesIO,
io.BufferedReader,
... |
class Vibrant:
props: Props
def __init__(self, color_count=64, quality=5) -> None:
self.props = Props(color_count=color_count, quality=quality)
def get_palette(
self,
src: Union[
bytes,
str,
io.BytesIO,
io.BufferedReader,
... | VibrantImage, | 1 | 2023-11-13 10:05:11+00:00 | 2k |
MAGICS-LAB/SparseModernHopfield | layers.py | [
{
"identifier": "Sparsemax",
"path": "utils/sparse_max.py",
"snippet": "class Sparsemax(nn.Module):\n __constants__ = [\"dim\"]\n\n def __init__(self, dim=-1):\n \"\"\"\n Sparsemax class as seen in https://arxiv.org/pdf/1602.02068.pdf\n Parameters\n ----------\n ... | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import math
from einops import rearrange, repeat
from math import sqrt
from utils.sparse_max import Sparsemax
from utils.entmax import Entmax15
from utils.general_entmax import EntmaxAlpha | 1,511 |
class FullAttention(nn.Module):
'''
The Attention operation
'''
def __init__(self, scale=None, attention_dropout=0.0):
super(FullAttention, self).__init__()
self.scale = scale
self.dropout = nn.Dropout(attention_dropout)
def forward(self, queries, keys, values, mask=None):... |
class FullAttention(nn.Module):
'''
The Attention operation
'''
def __init__(self, scale=None, attention_dropout=0.0):
super(FullAttention, self).__init__()
self.scale = scale
self.dropout = nn.Dropout(attention_dropout)
def forward(self, queries, keys, values, mask=None):... | self.softmax = Entmax15(dim=-1) | 1 | 2023-11-12 06:36:52+00:00 | 2k |
Kuba314/arcparse | arcparse/_partial_arguments.py | [
{
"identifier": "InvalidArgument",
"path": "arcparse/errors.py",
"snippet": "class InvalidArgument(InvalidParser):\n pass"
},
{
"identifier": "InvalidTypehint",
"path": "arcparse/errors.py",
"snippet": "class InvalidTypehint(InvalidArgument):\n pass"
},
{
"identifier": "Mis... | from abc import ABC, abstractmethod
from collections.abc import Callable, Collection
from dataclasses import dataclass
from typing import Any, Literal, get_origin
from arcparse.errors import InvalidArgument, InvalidTypehint, MissingConverter
from ._typehints import (
extract_collection_type,
extract_literal_str... | 1,109 |
@dataclass(kw_only=True, eq=False)
class PartialMxGroup:
required: bool = False
@dataclass(kw_only=True)
|
@dataclass(kw_only=True, eq=False)
class PartialMxGroup:
required: bool = False
@dataclass(kw_only=True) | class BasePartialArgument[R: ContainerApplicable](ABC): | 7 | 2023-11-15 08:58:37+00:00 | 2k |
rohitsinghlab/sceodesic | sceodesic/sceo_main/estimate_covariances.py | [
{
"identifier": "fn_timer",
"path": "sceodesic/utils/fn_timer.py",
"snippet": "def fn_timer(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n\n # run and time function\n start_time = time.time()\n result = func(*args, **kwargs)\n end_time = time.time()\n el... | import scipy
import pickle
import sys
from ..utils import fn_timer
from ..helper import compute_covariance_and_ncomps_pct_variance
from .default_keys import * | 1,070 |
# package-specific modules
@fn_timer
def estimate_covariances(adata, max_condition_number, pvd_pct=0.9,
copy=False, return_results=False,
top_genes=None, cohort_assn=None,
uns_key=None):
if uns_key is None:
uns_key = UNS_... |
# package-specific modules
@fn_timer
def estimate_covariances(adata, max_condition_number, pvd_pct=0.9,
copy=False, return_results=False,
top_genes=None, cohort_assn=None,
uns_key=None):
if uns_key is None:
uns_key = UNS_... | cluster_covar, var_count = compute_covariance_and_ncomps_pct_variance(cluster, max_condition_number, pvd_pct) | 1 | 2023-11-10 12:28:33+00:00 | 2k |
dacx/fcd-community | fcd_community/users/tests/test_views.py | [
{
"identifier": "UserAdminChangeForm",
"path": "fcd_community/users/forms.py",
"snippet": "class UserAdminChangeForm(admin_forms.UserChangeForm):\n class Meta(admin_forms.UserChangeForm.Meta):\n model = User\n field_classes = {\"email\": EmailField}"
},
{
"identifier": "User",
... | import pytest
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import AnonymousUser
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
from django.http import HttpRequest, HttpResponseRedir... | 863 |
pytestmark = pytest.mark.django_db
class TestUserUpdateView:
"""
TODO:
extracting view initialization code as class-scoped fixture
would be great if only pytest-django supported non-function-scoped
fixture db access -- this is a work-in-progress for now:
https://github.com/py... |
pytestmark = pytest.mark.django_db
class TestUserUpdateView:
"""
TODO:
extracting view initialization code as class-scoped fixture
would be great if only pytest-django supported non-function-scoped
fixture db access -- this is a work-in-progress for now:
https://github.com/py... | view = UserUpdateView() | 3 | 2023-11-10 08:23:29+00:00 | 2k |
fepegar/jvol | src/jvol/jvol.py | [
{
"identifier": "open_jvol",
"path": "src/jvol/io.py",
"snippet": "def open_jvol(path: Path) -> Tuple[np.ndarray, np.ndarray]:\n loaded = np.load(path)\n ijk_to_ras = fill_ijk_to_ras(loaded[FormatKeys.IJK_TO_RAS.value])\n quantization_block = loaded[FormatKeys.QUANTIZATION_BLOCK.value]\n arr... | import os
import numpy as np
import numpy.typing as npt
from pathlib import Path
from typing import Any
from typing import TypeAlias
from typing import Union
from .io import open_jvol
from .io import save_jvol | 1,265 | from __future__ import annotations
TypePath: TypeAlias = Union[str, os.PathLike]
class JpegVolume:
"""Base class for saving and loading JPEG-encoded volumes.
Args:
array: 3D NumPy array.
ijk_to_ras: 4×4 affine transformation matrix containing the mapping
from voxel indices to ... | from __future__ import annotations
TypePath: TypeAlias = Union[str, os.PathLike]
class JpegVolume:
"""Base class for saving and loading JPEG-encoded volumes.
Args:
array: 3D NumPy array.
ijk_to_ras: 4×4 affine transformation matrix containing the mapping
from voxel indices to ... | return cls(*open_jvol(path)) | 0 | 2023-11-12 18:41:36+00:00 | 2k |
iramluism/basel | tests/unit_tests/components/component_test.py | [
{
"identifier": "Component",
"path": "basel/components/components.py",
"snippet": "class Component(metaclass=abc.ABCMeta):\n def __init__(\n self,\n name: str,\n nodes: List[Node] = None,\n instability: Optional[float] = 1,\n abstraction: Optional[float] = 1,\n ... | from basel.components import Component
from basel.components.classes import ClassNode
from basel.components.modules import ModuleNode
import pytest | 777 |
@pytest.mark.parametrize(
"component,expected_classes",
[
(
Component(
name="Componant_A",
nodes=[
|
@pytest.mark.parametrize(
"component,expected_classes",
[
(
Component(
name="Componant_A",
nodes=[ | ModuleNode( | 2 | 2023-11-18 13:47:55+00:00 | 2k |
Gr-1m/AWD-Frame-ByGr1m | modules/Attack.py | [
{
"identifier": "FRAME_DIR",
"path": "Configs/frame_config.py",
"snippet": "FRAME_DIR = _os.path.dirname(_os.path.dirname(__file__))"
},
{
"identifier": "FlagRegular",
"path": "Configs/config.py",
"snippet": "API_URL = 'http://kaming/awduse/submit.php'"
},
{
"identifier": "printX... | from Configs.frame_config import FRAME_DIR
from Configs.config import FlagRegular
from func.CmdColors import printX
from modules.ReplaceStr import *
from urllib.parse import urlparse as URL
import requests, pymysql, paramiko, socket
import hashlib, base64
import os as _os
import re | 1,329 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
@project : customGr1m
@file : Attack.py
@Author : Gr%1m
@Date : 14/11/2023 10:56 am
"""
# from pwn import *
# About Flag
Flags = set()
FlagPath = '/flag'
FlagLen = 41
# Payload INFO
Payloads = {
f"http://POST@{HostReplaceStr}:80/awdtest/testback.p... | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
@project : customGr1m
@file : Attack.py
@Author : Gr%1m
@Date : 14/11/2023 10:56 am
"""
# from pwn import *
# About Flag
Flags = set()
FlagPath = '/flag'
FlagLen = 41
# Payload INFO
Payloads = {
f"http://POST@{HostReplaceStr}:80/awdtest/testback.p... | flag = re.search(FlagRegular, text).group() | 1 | 2023-11-17 09:12:03+00:00 | 2k |
Wolfsauge/async_summarize | async_helpers.py | [
{
"identifier": "get_length_of_chunk_in_tokens",
"path": "sync_helpers.py",
"snippet": "def get_length_of_chunk_in_tokens(my_chunk: str, buck_slip: dict) -> int:\n my_result = buck_slip[\"tokenizer\"](my_chunk)\n input_ids = my_result.input_ids\n length_of_chunk_in_tokens = len(input_ids)\n\n ... | import sys
import asyncio
import math
from tqdm.asyncio import tqdm # type: ignore
from icecream import ic # type: ignore
from sync_helpers import (
get_length_of_chunk_in_tokens,
get_text_splitter,
grouped,
find_chunk_pair_with_minimal_size,
find_longest_element_index,
calc_custom_chunking_pa... | 1,590 |
async def get_completion(buck_slip: dict, task: str, **kwargs) -> str:
template = buck_slip["jinja2_env"].from_string(buck_slip["prompt_templates"][task])
if task == "summarize":
chunk = kwargs["chunk"]
if isinstance(chunk, str):
my_prompt = template.render(prompt=chunk)
... |
async def get_completion(buck_slip: dict, task: str, **kwargs) -> str:
template = buck_slip["jinja2_env"].from_string(buck_slip["prompt_templates"][task])
if task == "summarize":
chunk = kwargs["chunk"]
if isinstance(chunk, str):
my_prompt = template.render(prompt=chunk)
... | buck_slip["text_splitter"] = get_text_splitter( | 1 | 2023-11-16 01:51:17+00:00 | 2k |
balazsborsos/dae_postprocessing | main.py | [
{
"identifier": "ConfigurationParser",
"path": "utils/parser.py",
"snippet": "class ConfigurationParser:\n def __init__(self):\n self.parser = argparse.ArgumentParser(description='Script for training or evaluation with configuration.')\n\n # Argument to specify mode (train or evaluation... | from utils.parser import ConfigurationParser, parse_yaml_config
from train import train_model | 690 |
if __name__ == "__main__":
config_parser = ConfigurationParser()
args = config_parser.parse_args()
|
if __name__ == "__main__":
config_parser = ConfigurationParser()
args = config_parser.parse_args()
| config = parse_yaml_config(args.config) | 1 | 2023-11-18 13:57:25+00:00 | 2k |
htyao89/Textual-based_Class-aware_prompt_tuning | clip/clip.py | [
{
"identifier": "build_model",
"path": "clip/model.py",
"snippet": "def build_model(state_dict: dict):\n vit = \"visual.proj\" in state_dict\n\n if vit:\n vision_width = state_dict[\"visual.conv1.weight\"].shape[0]\n vision_layers = len([k for k in state_dict.keys() if k.startswith(\... | import hashlib
import os
import urllib
import warnings
import torch
from typing import Any, Union, List
from pkg_resources import packaging
from PIL import Image
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
from tqdm import tqdm
from .model import build_model
from .simple_tokenize... | 1,515 |
try:
BICUBIC = InterpolationMode.BICUBIC
except ImportError:
BICUBIC = Image.BICUBIC
if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"):
warnings.warn("PyTorch version 1.7.1 or higher is recommended")
__all__ = ["available_models", "load", "tokenize"]
|
try:
BICUBIC = InterpolationMode.BICUBIC
except ImportError:
BICUBIC = Image.BICUBIC
if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"):
warnings.warn("PyTorch version 1.7.1 or higher is recommended")
__all__ = ["available_models", "load", "tokenize"] | _tokenizer = _Tokenizer() | 0 | 2023-11-14 03:50:33+00:00 | 2k |
Veridise/vanguard-aleo | vanguard/aleo/detectors/infoleak.py | [
{
"identifier": "get_ifg_edges",
"path": "vanguard/aleo/common.py",
"snippet": "def get_ifg_edges(prog, func, hash=False, call=False, inline=False):\n \"\"\"Get information flow graph edges.\n Args:\n - prog: \n - func\n - hash (default: False): whether to treat a hash function call... | import networkx as nx
from ..common import get_ifg_edges, trim_inst | 1,134 |
def detector_infoleak(prog, func):
"""Detect for information leak
Args:
- prog:
- func:
Rets: (result, info)
"""
|
def detector_infoleak(prog, func):
"""Detect for information leak
Args:
- prog:
- func:
Rets: (result, info)
"""
| edges = get_ifg_edges(prog, func, hash=False, call=True, inline=False) | 0 | 2023-11-10 02:57:03+00:00 | 2k |
winrey/x-following | check_following.py | [
{
"identifier": "client",
"path": "client.py",
"snippet": "class MyUser(TypedDict):\nclass TimelineUserEntitiesDescription(TypedDict):\nclass TimelineUserEntitiesURL(TypedDict):\nclass TimelineUserEntities(TypedDict):\nclass TimelineUserLegacy(TypedDict):\nclass TimelineUser(TypedDict):\nclass Following... | import json
from typing import List
from client import client, FollowingUser
from common_cli import select_account, trials
from back_white_list import filter_not_in_whitelist, filter_not_in_blacklist | 1,039 |
FOLLOWING_CACHE_PATH = 'cache/followings.json'
def load_followings():
try:
with open(FOLLOWING_CACHE_PATH, 'r') as f:
return json.load(f)
except FileNotFoundError:
return False
def get_all_followings(force_update=False):
followings = load_followings()
if followings an... |
FOLLOWING_CACHE_PATH = 'cache/followings.json'
def load_followings():
try:
with open(FOLLOWING_CACHE_PATH, 'r') as f:
return json.load(f)
except FileNotFoundError:
return False
def get_all_followings(force_update=False):
followings = load_followings()
if followings an... | trials(subjects) | 2 | 2023-11-11 18:54:25+00:00 | 2k |
Shritesh99/strawberry-django-social-auth | gql_social_auth/mixins.py | [
{
"identifier": "social_auth",
"path": "gql_social_auth/decorators.py",
"snippet": "def social_auth(f):\n \"\"\"\n Decorator for Getting social User. Use this decorator if you want to customize the SocialAuthMixin.\n :param f: Input: SocialAuthInput(provider, accessToken)\n :return: function... | from strawberry.types import Info
from gqlauth.user.resolvers import BaseMixin
from .decorators import social_auth
from .types import SocialAuthInput
from .types import SocialType | 673 |
class SocialAuthMixin(BaseMixin):
"""Social Auth takes OAuth Provider and OAuth Access Token
Allow user to perform social auth for the given OAuth provider and OAuth Access token
:returns
user: Entire User Object (Get your social data using user.social_user)
errors: Any error occurred in ... |
class SocialAuthMixin(BaseMixin):
"""Social Auth takes OAuth Provider and OAuth Access Token
Allow user to perform social auth for the given OAuth provider and OAuth Access token
:returns
user: Entire User Object (Get your social data using user.social_user)
errors: Any error occurred in ... | @social_auth | 0 | 2023-11-12 23:27:04+00:00 | 2k |
Scholar01/ComfyUI-Keyframe | keyframe/samples.py | [
{
"identifier": "is_injected_model",
"path": "keyframe/util.py",
"snippet": "def is_injected_model(model):\n return hasattr(model, KEYFRAME_INJECTED_ATTR)"
},
{
"identifier": "get_injected_model",
"path": "keyframe/util.py",
"snippet": "def get_injected_model(model):\n return getat... | import torch
import comfy.samplers
from tqdm.auto import trange
from comfy.k_diffusion import sampling as k_diffusion_sampling
from comfy.k_diffusion.sampling import to_d, default_noise_sampler
from .util import is_injected_model, get_injected_model, generate_sigmas, generate_noise, get_ancestral_step | 665 |
CUSTOM_SAMPLERS = [
'k_euler', 'k_euler_a', 'k_lcm'
]
def inject_samples():
comfy.samplers.SAMPLER_NAMES.extend(CUSTOM_SAMPLERS)
k_diffusion_sampling.sample_k_euler = sample_k_euler
k_diffusion_sampling.sample_k_euler_a = sample_k_euler_a
k_diffusion_sampling.sample_k_lcm = sample_k_lcm
prin... |
CUSTOM_SAMPLERS = [
'k_euler', 'k_euler_a', 'k_lcm'
]
def inject_samples():
comfy.samplers.SAMPLER_NAMES.extend(CUSTOM_SAMPLERS)
k_diffusion_sampling.sample_k_euler = sample_k_euler
k_diffusion_sampling.sample_k_euler_a = sample_k_euler_a
k_diffusion_sampling.sample_k_lcm = sample_k_lcm
prin... | sigmas = generate_sigmas(model_wrap.inner_model, x, sigmas, scheduler, steps, part_group, sigmas.device) | 2 | 2023-11-10 13:15:08+00:00 | 2k |
Hamidrezaostadabbas/FOSS4G_Asia_2023 | 03_Exercise_2/exercise_2/layout_generator/layout_generator.py | [
{
"identifier": "LayoutGeneratorDialog",
"path": "03_Exercise_2/exercise_2/layout_generator/layout_generator_dialog.py",
"snippet": "class LayoutGeneratorDialog(QtWidgets.QDialog, FORM_CLASS):\n def __init__(self, parent=None):\n \"\"\"Constructor.\"\"\"\n super(LayoutGeneratorDialog, s... | from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction
from .resources import *
from .layout_generator_dialog import LayoutGeneratorDialog
from .core_functions import (
import_vector_layer, display_vector_layer, zoom_to_layer, ... | 1,113 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
LayoutGenerator
A QGIS plugin
auto layout generator
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
... | # -*- coding: utf-8 -*-
"""
/***************************************************************************
LayoutGenerator
A QGIS plugin
auto layout generator
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
... | self.layout_generator_dialog = LayoutGeneratorDialog() | 0 | 2023-11-17 09:40:49+00:00 | 2k |
micheltlutz/Winged-Python | winged/HTML/table.py | [
{
"identifier": "String",
"path": "winged/HTML/string.py",
"snippet": "class String(GenericElement):\n text = \"\"\n\n def __init__(self, str):\n super().__init__()\n self.text = str\n\n def get_string(self):\n return self.text\n\n def generate(self):\n print(self... | from winged.HTML.string import String
from winged.core.generic_element import GenericElement
from winged.core.tag import Tag
from winged.HTML.thead import THead
from winged.HTML.tbody import TBody
from winged.HTML.tr import Tr
from winged.HTML.th import Th
from winged.HTML.td import Td | 1,315 |
"""
The Table class is a specific implementation of the HTML 'table' tag in the Winged-Python library.
It provides helper methods to generate table structures.
Table creation involves creating headers (th), rows (tr), and data cells (td).
# Example Usage:
```python
table = Table()
table.add_table_headers(["Name", "... |
"""
The Table class is a specific implementation of the HTML 'table' tag in the Winged-Python library.
It provides helper methods to generate table structures.
Table creation involves creating headers (th), rows (tr), and data cells (td).
# Example Usage:
```python
table = Table()
table.add_table_headers(["Name", "... | self.thead = THead() | 3 | 2023-11-18 17:40:48+00:00 | 2k |
davidhozic/TkClassWizard | tkclasswiz/object_frame/frame_string.py | [
{
"identifier": "extendable",
"path": "tkclasswiz/extensions.py",
"snippet": "@doc_category(\"Extensions\")\r\ndef extendable(obj: Union[T, list]) -> T:\r\n \"\"\"\r\n Decorator that makes the obj extendable.\r\n\r\n It wraps the ``obj``, which is a class or a function, into an extension object... | from typing import Any
from ..storage import *
from .frame_base import *
from ..extensions import extendable
from ..doc import doc_category
import tkinter as tk
| 1,400 |
TEXT_MAX_UNDO = 20
__all__ = (
"NewObjectFrameString",
)
|
TEXT_MAX_UNDO = 20
__all__ = (
"NewObjectFrameString",
)
| @extendable
| 0 | 2023-11-14 09:26:01+00:00 | 2k |
har777/snek-evm | test.py | [
{
"identifier": "EVM",
"path": "vm.py",
"snippet": "class EVM:\n def __init__(self):\n self.address_to_contract = {}\n\n def create_contract(self, bytecode, address):\n contract = Contract(bytecode=bytecode, address=address)\n self.address_to_contract[address] = contract\n ... | import unittest
from vm import EVM, TransactionMetadata, get_create_contract_address, get_create2_contract_address | 1,417 |
class UtilTestCase(unittest.TestCase):
def test_get_create_contract_address(self):
sender_address = "0x6ac7ea33f8831ea9dcc53393aaa88b25a785dbf0"
self.assertEqual(get_create_contract_address(sender_address=sender_address, sender_nonce=0),
"0xcd234a471b72ba2f1ccf0a70fcaba6... |
class UtilTestCase(unittest.TestCase):
def test_get_create_contract_address(self):
sender_address = "0x6ac7ea33f8831ea9dcc53393aaa88b25a785dbf0"
self.assertEqual(get_create_contract_address(sender_address=sender_address, sender_nonce=0),
"0xcd234a471b72ba2f1ccf0a70fcaba6... | self.evm = EVM() | 0 | 2023-11-10 14:13:05+00:00 | 2k |
AvaterClasher/eli | tests/middlewares/test_mindsdb.py | [
{
"identifier": "CredentialsError",
"path": "eli/exceptions/auth.py",
"snippet": "class CredentialsError(Exception): ..."
},
{
"identifier": "NetworkError",
"path": "eli/exceptions/connection.py",
"snippet": "class NetworkError(Exception): ..."
},
{
"identifier": "MINDSDB_HOST",
... | import pytest
from pandas import DataFrame
from unittest.mock import patch, MagicMock
from eli.exceptions.auth import CredentialsError
from eli.exceptions.connection import NetworkError
from requests.exceptions import HTTPError, ConnectionError
from eli.constants.service import MINDSDB_HOST
from eli.middlewares.mindsdb... | 726 |
@patch('mindsdb_sdk.connect')
def test_authenticate(mock_connect):
email = 'test@test.com'
password = 'testpassword'
mock_server = MagicMock()
mock_connect.return_value = mock_server
mindsdb = MindsDB(email, password)
mindsdb.authenticate()
mock_connect.assert_called_once_with(MINDSD... |
@patch('mindsdb_sdk.connect')
def test_authenticate(mock_connect):
email = 'test@test.com'
password = 'testpassword'
mock_server = MagicMock()
mock_connect.return_value = mock_server
mindsdb = MindsDB(email, password)
mindsdb.authenticate()
mock_connect.assert_called_once_with(MINDSD... | with pytest.raises(NetworkError): | 1 | 2023-11-16 13:31:55+00:00 | 2k |
xduck7/AI_Spam_checker | start.py | [
{
"identifier": "do_prediction",
"path": "predict.py",
"snippet": "def do_prediction(message):\n\n #подгрузка модели\n loaded_model = load_model('./Model/your_model.h5')\n loaded_label_encoder = joblib.load('./Model/label_encoder.pkl')\n loaded_vectorizer = joblib.load('./Model/vectorizer.pk... | import tkinter as tk
from predict import do_prediction
from rqst import add_report
from rqst import first_start | 899 |
root= tk.Tk()
root.title("SPAM CHECKER")
root.geometry("500x600")
root.resizable(width=True, height=True)
def get_input():
inputValue=textBox.get("1.0","end-1c")
print(inputValue)
textBox.delete('1.0', 'end')
return inputValue
def union():
msg = get_input()
result = do_prediction(msg)
if... |
root= tk.Tk()
root.title("SPAM CHECKER")
root.geometry("500x600")
root.resizable(width=True, height=True)
def get_input():
inputValue=textBox.get("1.0","end-1c")
print(inputValue)
textBox.delete('1.0', 'end')
return inputValue
def union():
msg = get_input()
result = do_prediction(msg)
if... | first_start() | 2 | 2023-11-18 17:11:44+00:00 | 2k |
TheJacksonLaboratory/geneweaver-boolean-algebra | tests/unit/test_boolean_algebra_tool.py | [
{
"identifier": "BOOLEAN_GENESET_GENES_0",
"path": "tests/unit/const.py",
"snippet": "BOOLEAN_GENESET_GENES_0 = {\n GeneValue(symbol=\"A\", value=1),\n GeneValue(symbol=\"B\", value=1),\n GeneValue(symbol=\"C\", value=1),\n GeneValue(symbol=\"D\", value=1),\n}"
},
{
"identifier": "BO... | from pathlib import Path
from geneweaver.tools.boolean_algebra.tool import (
BooleanAlgebra,
BooleanAlgebraInput,
BooleanAlgebraOutput,
BooleanAlgebraType,
WorkflowType,
)
from tests.unit.const import (
BOOLEAN_GENESET_GENES_0,
BOOLEAN_GENESET_GENES_1,
BOOLEAN_GENESET_GENES_2,
DIFF_B... | 850 | """Test the boolean algebra tool class."""
@pytest.mark.parametrize(
("input_value", "expected"),
[
# Union
(
BooleanAlgebraInput(
type=BooleanAlgebraType.UNION,
| """Test the boolean algebra tool class."""
@pytest.mark.parametrize(
("input_value", "expected"),
[
# Union
(
BooleanAlgebraInput(
type=BooleanAlgebraType.UNION, | input_genesets=[BOOLEAN_GENESET_GENES_0, BOOLEAN_GENESET_GENES_1], | 1 | 2023-11-15 17:53:26+00:00 | 2k |
jpcadena/fastapi-boilerplate | app/core/lifecycle.py | [
{
"identifier": "RedisConnectionManager",
"path": "app/api/deps.py",
"snippet": "class RedisConnectionManager:\n \"\"\"\n Redis connection manager class\n \"\"\"\n\n def __init__(self, auth_settings: AuthSettings):\n self.url: str = f\"{auth_settings.REDIS_DATABASE_URI}\"\n sel... | import logging
from contextlib import asynccontextmanager
from typing import Any, AsyncGenerator
from fastapi import FastAPI
from app.api.deps import RedisConnectionManager
from app.config.config import get_auth_settings, get_init_settings, get_settings
from app.crud.user import get_user_repository
from app.db.init_db ... | 1,182 | """
A module for lifecycle in the app-core package.
"""
logger: logging.Logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(application: FastAPI) -> AsyncGenerator[Any, None]:
"""
The lifespan of the application
:param application: The FastAPI application
:type application:... | """
A module for lifecycle in the app-core package.
"""
logger: logging.Logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(application: FastAPI) -> AsyncGenerator[Any, None]:
"""
The lifespan of the application
:param application: The FastAPI application
:type application:... | application.state.settings = get_settings() | 3 | 2023-11-17 00:32:32+00:00 | 2k |
juliusmarkwei/auth-system | backend/accounts/views.py | [
{
"identifier": "UserSerializer",
"path": "backend/accounts/serializers.py",
"snippet": "class UserSerializer(serializers.ModelSerializer):\n date_joined = serializers.ReadOnlyField()\n password = serializers.CharField(write_only=True)\n class Meta(object):\n model = User\n fields... | from rest_framework.views import APIView
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from .serializers import UserSerializer
from .models import User, EmailConfirmationToken
from .utils import send_confirmation_email | 1,123 |
class UserAPIView(APIView):
permission_classes = [AllowAny,]
def post(self, request):
user = request.data
serializer = UserSerializer(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED... |
class UserAPIView(APIView):
permission_classes = [AllowAny,]
def post(self, request):
user = request.data
serializer = UserSerializer(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED... | send_confirmation_email(email=user.email, token_id=token.pk, user_id=user.pk) | 3 | 2023-11-17 17:55:59+00:00 | 2k |
vitant-lang/CBAM-ASPP | nets/deeplabv3_plus.py | [
{
"identifier": "xception",
"path": "nets/xception.py",
"snippet": "def xception(pretrained=True, downsample_factor=16):\n model = Xception(downsample_factor=downsample_factor)\n if pretrained:\n model.load_state_dict(load_url('https://github.com/bubbliiiing/deeplabv3-plus-pytorch/releases/... | import torch
import torch.nn as nn
import torch.nn.functional as F
from .xception import xception
from .mobilenetv2 import mobilenetv2
from .attention import se_block,CBAM,eca_block
from functools import partial | 795 |
atteionb=[se_block,CBAM,eca_block]
class MobileNetV2(nn.Module):
def __init__(self, downsample_factor=8, pretrained=True):
super(MobileNetV2, self).__init__()
|
atteionb=[se_block,CBAM,eca_block]
class MobileNetV2(nn.Module):
def __init__(self, downsample_factor=8, pretrained=True):
super(MobileNetV2, self).__init__()
| model = mobilenetv2(pretrained) | 1 | 2023-11-17 13:25:28+00:00 | 2k |
JiNanPiWang/apple_health_export_gpx_add_heartrate | src/strava_gpx_uploader.py | [
{
"identifier": "RateLimitException",
"path": "utils/exceptions.py",
"snippet": "class RateLimitException(Exception):\n def __init__(self, message=\"API rate limit exceeded\"):\n self.message = message\n super().__init__(self.message)"
},
{
"identifier": "NoInternetException",
... | import json
import os
import time
from stravalib.util.limiter import RateLimiter, XRateLimitRule
from stravalib.client import Client, exc
from utils.exceptions import RateLimitException, NoInternetException | 830 |
def get_strava_client(access_token):
token = access_token
rate_limiter = RateLimiter()
rate_limiter.rules.append(XRateLimitRule(
{'short': {'usageFieldIndex': 0, 'usage': 0,
# 60s * 15 = 15 min
'limit': 100, 'time': (60 * 15),
'lastExceeded... |
def get_strava_client(access_token):
token = access_token
rate_limiter = RateLimiter()
rate_limiter.rules.append(XRateLimitRule(
{'short': {'usageFieldIndex': 0, 'usage': 0,
# 60s * 15 = 15 min
'limit': 100, 'time': (60 * 15),
'lastExceeded... | raise NoInternetException("No Internet connection: {}".format(err)) | 1 | 2023-11-14 01:50:02+00:00 | 2k |
rgrizzell/CircuitPython_LILYGO_T-Deck | examples/lilygo_tdeck_custom_keyboard.py | [
{
"identifier": "Keyboard",
"path": "lilygo_tdeck.py",
"snippet": "class Keyboard:\n \"\"\"Controls the keyboard peripheral. This class can be extended to support additional\n functionality if the keyboard is utilizing custom firmware.\n\n :param i2c: Object representing the I2C interface used ... | import time
import board
from lilygo_tdeck import Keyboard, TDeck | 1,310 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
# SPDX-FileCopyrightText: Copyright (c) 2023 Robert Grizzell
#
# SPDX-License-Identifier: Unlicense
class MyCustomKeyboard(Keyboard):
def __init__(self, backlight: bool = True):
super().__init__(board.I2C())
self.backl... | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
# SPDX-FileCopyrightText: Copyright (c) 2023 Robert Grizzell
#
# SPDX-License-Identifier: Unlicense
class MyCustomKeyboard(Keyboard):
def __init__(self, backlight: bool = True):
super().__init__(board.I2C())
self.backl... | t = TDeck(keyboard=k) | 1 | 2023-11-11 15:13:00+00:00 | 2k |
dataaug/open-interpreter-free | tests/test_interpreter.py | [
{
"identifier": "count_messages_tokens",
"path": "interpreter/utils/count_tokens.py",
"snippet": "def count_messages_tokens(messages=[], model=None):\n \"\"\"\n Count the number of tokens in a list of messages\n \"\"\"\n\n tokens_used = 0\n\n for message in messages:\n if isinstanc... | import os
import re
import time
import interpreter
from random import randint
from interpreter.utils.count_tokens import count_messages_tokens, count_tokens | 1,581 | Round to 2 decimal places.
""".strip()
messages = interpreter.chat(order_of_operations_message)
assert str(round(test_result, 2)) in messages[-1]["message"]
def test_delayed_exec():
interpreter.chat(
"""Can you write a single block of code and execute it that prints something, then delay... |
# this function will run before each test
# we're clearing out the messages Array so we can start fresh and reduce token usage
def setup_function():
interpreter.reset()
interpreter.temperature = 0
interpreter.auto_run = True
interpreter.model = "gpt-4"
interpreter.debug_mode = False
# this func... | system_token_test = count_messages_tokens( | 0 | 2023-11-16 03:10:42+00:00 | 2k |
TheJacksonLaboratory/geneweaver-client | tests/unit/utils/cli/prompt/pydantic/test_prompt_for_missing_fields.py | [
{
"identifier": "MOCK_EXISTING_COMBINATIONS",
"path": "tests/unit/utils/cli/prompt/pydantic/conftest.py",
"snippet": "MOCK_EXISTING_COMBINATIONS = [\n dict(e)\n for e in chain.from_iterable(\n combinations(MOCK_EXISTING_FIELDS, r)\n for r in range(len(MOCK_EXISTING_FIELDS) + 1)\n ... | from unittest.mock import Mock
from geneweaver.client.utils.cli.prompt.pydantic import prompt_for_missing_fields
from tests.unit.utils.cli.prompt.pydantic.conftest import (
MOCK_EXISTING_COMBINATIONS,
MOCK_MODEL_FIELD_COMBINATIONS,
MOCK_MODEL_FIELDS,
MockModel,
)
import pytest | 656 | """Test the prompt_for_missing_fields function."""
# We can't use every combination of fields because the number of combinations
# grows much too large to be practical.
# Instead, we use the first 25 and last 25 combinations.
@pytest.mark.parametrize(
"existing", MOCK_EXISTING_COMBINATIONS[:25] + MOCK_EXISTING_... | """Test the prompt_for_missing_fields function."""
# We can't use every combination of fields because the number of combinations
# grows much too large to be practical.
# Instead, we use the first 25 and last 25 combinations.
@pytest.mark.parametrize(
"existing", MOCK_EXISTING_COMBINATIONS[:25] + MOCK_EXISTING_... | set(MOCK_MODEL_FIELDS) - set(existing.keys()) - exclude | 2 | 2023-11-10 19:28:53+00:00 | 2k |
hmmbug/pythaidate | pythaidate/lsyear.py | [
{
"identifier": "DAYS_IN_800_YEARS",
"path": "pythaidate/constants.py",
"snippet": "DAYS_IN_800_YEARS = 292207"
},
{
"identifier": "TIME_UNITS_IN_1_DAY",
"path": "pythaidate/constants.py",
"snippet": "TIME_UNITS_IN_1_DAY = 800"
},
{
"identifier": "EPOCH_OFFSET",
"path": "pyth... | from .constants import (
DAYS_IN_800_YEARS,
TIME_UNITS_IN_1_DAY,
EPOCH_OFFSET,
UCCAPON_CONSTANT,
APOGEE_ROTATION_DAYS,
CAL_TYPE_DAY_COUNTS,
) | 1,012 |
class LSYear:
"""
A lightweight class representing a lunisolar year on new year's day.
"""
def __init__(self, year: int):
self.offset = False # adjusted later
self.year = year
# this year
self.horakhun = (year * DAYS_IN_800_YEARS + EPOCH_OFFSET) // TIME_UNITS_IN_1_DA... |
class LSYear:
"""
A lightweight class representing a lunisolar year on new year's day.
"""
def __init__(self, year: int):
self.offset = False # adjusted later
self.year = year
# this year
self.horakhun = (year * DAYS_IN_800_YEARS + EPOCH_OFFSET) // TIME_UNITS_IN_1_DA... | self.caldays = CAL_TYPE_DAY_COUNTS[self.cal_type] | 5 | 2023-11-18 21:14:01+00:00 | 2k |
finalparanoia/Bert-VITS2-Preprocess | main.py | [
{
"identifier": "create",
"path": "utils/create.py",
"snippet": "def create(dataset_name: str):\n raw_files = ls(f\"{raw_dir}/*.wav\")\n current_dataset_path = f\"{dataset_dir}/{dataset_name}\"\n i = 0\n\n if exist(current_dataset_path):\n mv(current_dataset_path, current_dataset_path... | from utils.create import create
from utils.tag import tag
from utils.resample import resample
from utils.clean import clean
from utils.model_conf import gen_config | 935 |
if __name__ == "__main__":
pass
dataset_name = input("请为数据集命名:")
create(dataset_name)
resample(dataset_name)
tag(dataset_name)
clean(dataset_name)
|
if __name__ == "__main__":
pass
dataset_name = input("请为数据集命名:")
create(dataset_name)
resample(dataset_name)
tag(dataset_name)
clean(dataset_name) | gen_config(dataset_name) | 4 | 2023-11-12 09:42:20+00:00 | 2k |
itzshukla/STRANGER-SPAM | TheXSpam/extra.py | [
{
"identifier": "SUDO_USERS",
"path": "config.py",
"snippet": "SUDO_USERS = list(map(lambda x: int(x), getenv(\"SUDO_USERS\", \"6163010926\").split(\" \")))"
},
{
"identifier": "ALIVE_PIC",
"path": "config.py",
"snippet": "ALIVE_PIC = getenv(\"ALIVE_PIC\", \"https://telegra.ph/file/aa4bf... | import heroku3
from os import getenv
from config import SUDO_USERS, ALIVE_PIC, OWNER_ID, HEROKU_APP_NAME, HEROKU_API_KEY
from pyrogram import Client, filters
from pyrogram.types import Message
| 724 | # © @shiva_ansh_op
FIRST_TEXT = f"""★ 𝗦𝘁𝗿𝗮𝗻𝗴𝗲𝗿-𝙎𝙥𝙖𝙢 𝙃𝙚𝙡𝙥 𝙈𝙚𝙣𝙪 ★
**» ʙᴏᴛ ᴄᴏᴍᴍᴀɴᴅꜱ:** [ᴄʟɪᴄᴋ ʜᴇʀᴇ](https://t.me/mastiwithfriendsx/5)
**» ʀᴀɪᴅ ᴄᴏᴍᴍᴀɴᴅꜱ:** [ᴄʟɪᴄᴋ ʜᴇʀᴇ](https://t.me/mastiwithfriendsx/6)
**» ꜱᴘᴀᴍ ᴄᴏᴍᴍᴀɴᴅꜱ:** [ᴄʟɪᴄᴋ ʜᴇʀᴇ](https://t.me/mastiwithfriendsx/7)
**» ᴅᴍ ᴄᴏᴍᴍᴀɴᴅꜱ:... | # © @shiva_ansh_op
FIRST_TEXT = f"""★ 𝗦𝘁𝗿𝗮𝗻𝗴𝗲𝗿-𝙎𝙥𝙖𝙢 𝙃𝙚𝙡𝙥 𝙈𝙚𝙣𝙪 ★
**» ʙᴏᴛ ᴄᴏᴍᴍᴀɴᴅꜱ:** [ᴄʟɪᴄᴋ ʜᴇʀᴇ](https://t.me/mastiwithfriendsx/5)
**» ʀᴀɪᴅ ᴄᴏᴍᴍᴀɴᴅꜱ:** [ᴄʟɪᴄᴋ ʜᴇʀᴇ](https://t.me/mastiwithfriendsx/6)
**» ꜱᴘᴀᴍ ᴄᴏᴍᴍᴀɴᴅꜱ:** [ᴄʟɪᴄᴋ ʜᴇʀᴇ](https://t.me/mastiwithfriendsx/7)
**» ᴅᴍ ᴄᴏᴍᴍᴀɴᴅꜱ:... | elif HEROKU_APP_NAME is None:
| 3 | 2023-11-14 05:14:00+00:00 | 2k |
fg320/DEASC | deasc/wf_model.py | [
{
"identifier": "floris_input_handler",
"path": "deasc/utils_floris.py",
"snippet": "def floris_input_handler(input_file, path):\n \"\"\"Convert input file into a FLORIS interface object.\"\"\"\n # No input file\n if input_file == None:\n err_msg = \"Input file required\"\n raise ... | import warnings
import numpy as np
from .utils_floris import (
floris_input_handler,
floris_properties,
floris_current_yaw,
floris_reinitialise_layout,
floris_farm_eval
) | 1,390 | # Copyright 2023 Filippo Gori
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
... | # Copyright 2023 Filippo Gori
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
... | self.D, self.H_hub, self.n_turbs = floris_properties(self) | 1 | 2023-11-10 18:13:27+00:00 | 2k |
CPES-Power-and-Energy-Systems/interoperable-recommender-tso | energy_app/src/energy_app_client/Controller.py | [
{
"identifier": "Endpoint",
"path": "energy_app/src/energy_app_client/Endpoint.py",
"snippet": "class Endpoint:"
},
{
"identifier": "RequestController",
"path": "energy_app/src/energy_app_client/RequestController.py",
"snippet": "class RequestController:\n \"\"\"\n Manages api call... | from time import time
from loguru import logger
from http import HTTPStatus
from .Endpoint import Endpoint, post_actions
from .RequestController import RequestController
from .exception import LoginException, PostActionsException | 965 |
class Controller(RequestController):
def __init__(self):
RequestController.__init__(self)
self.access_token = ""
def __check_if_token_exists(self):
if self.access_token is None:
e_msg = "Access token is not yet available. Login first."
logger.error(e_msg)
... |
class Controller(RequestController):
def __init__(self):
RequestController.__init__(self)
self.access_token = ""
def __check_if_token_exists(self):
if self.access_token is None:
e_msg = "Access token is not yet available. Login first."
logger.error(e_msg)
... | endpoint_cls: Endpoint, | 0 | 2023-11-17 09:23:38+00:00 | 2k |
PlaxtonFlarion/NexaFlow | nexaflow/hook.py | [
{
"identifier": "toolbox",
"path": "nexaflow/toolbox.py",
"snippet": "def video_capture(video_path: str):\ndef video_jump(video_cap: cv2.VideoCapture, frame_id: int):\ndef compare_ssim(pic1: np.ndarray, pic2: np.ndarray) -> float:\ndef multi_compare_ssim(\n pic1_list: typing.List, pic2_list: typing.L... | import os
import cv2
import typing
from loguru import logger
from nexaflow import toolbox
from nexaflow.video import VideoFrame | 1,228 |
class BaseHook(object):
def __init__(self, *_, **__):
# logger.debug(f"start initialing: {self.__class__.__name__} ...")
logger.info(f"加载视频帧处理单元: Frame Processor {self.__class__.__name__} ...")
self.result = dict()
def do(self, frame: VideoFrame, *_, **__) -> typing.Optional[VideoFra... |
class BaseHook(object):
def __init__(self, *_, **__):
# logger.debug(f"start initialing: {self.__class__.__name__} ...")
logger.info(f"加载视频帧处理单元: Frame Processor {self.__class__.__name__} ...")
self.result = dict()
def do(self, frame: VideoFrame, *_, **__) -> typing.Optional[VideoFra... | frame.data = toolbox.turn_grey(frame.data) | 0 | 2023-11-13 05:27:34+00:00 | 2k |
OpenBMB/XAgent | tests/test_run.py | [
{
"identifier": "parse_args",
"path": "run.py",
"snippet": "def parse_args() -> argparse.Namespace:\n \"\"\"\n Parse the command line arguments and return them as an argparse.Namespace object.\n\n Returns:\n argparse.Namespace: An object containing command line arguments and their values... | import pytest
import sys
from run import parse_args, execute_command_line_process, start_command_line
from unittest.mock import patch | 1,008 |
@pytest.fixture
def mock_argv(monkeypatch):
"""
A pytest fixture to mock the command line arguments.
It sets the sys.argv to mimic command line input for testing.
"""
test_args = ["--task", "example_task", "--upload-files", "file1", "file2", "--model", "model1"]
monkeypatch.setattr(sys, 'argv',... |
@pytest.fixture
def mock_argv(monkeypatch):
"""
A pytest fixture to mock the command line arguments.
It sets the sys.argv to mimic command line input for testing.
"""
test_args = ["--task", "example_task", "--upload-files", "file1", "file2", "--model", "model1"]
monkeypatch.setattr(sys, 'argv',... | args = parse_args() | 0 | 2023-10-16 03:44:57+00:00 | 2k |
pytorch-labs/gpt-fast | GPTQ.py | [
{
"identifier": "setup_cache_padded_seq_input_pos_max_seq_length_for_prefill",
"path": "eval.py",
"snippet": "def setup_cache_padded_seq_input_pos_max_seq_length_for_prefill(\n model: LLaMA,\n prompt: torch.Tensor,\n max_new_tokens: int,\n max_seq_length: Optional[int] = None,\n):\n \"\"\... | import os
import sys
import torch
import main as lm_evaluation_harness_main
import torch.fx as fx
import torch.nn as nn
import torch.nn.functional as F
import lm_eval
from torch.utils._pytree import tree_flatten, tree_unflatten
from eval import setup_cache_padded_seq_input_pos_max_seq_length_for_prefill
from genera... | 1,471 |
aten = torch.ops.aten
try:
class InputRecorder(lm_eval.base.BaseLM):
"""
This is a fake evaluation wrapper that just records the inputs
so that they can be used in calibration.
If pad_calibration_inputs is enabled, the input recorder will take
each input and pad/truncate ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
lm_evaluation_harness_path = "/".join(
os.getcwd().split("/")[:-1] + ["lm-evaluation-harness"]
)
sys.path.insert(0, l... | ) = setup_cache_padded_seq_input_pos_max_seq_length_for_prefill( | 0 | 2023-10-17 05:30:32+00:00 | 2k |
deepseek-ai/DeepSeek-Coder | Evaluation/MBPP/human_eval/evaluate_functional_correctness.py | [
{
"identifier": "HUMAN_EVAL",
"path": "Evaluation/MBPP/human_eval/data.py",
"snippet": "HUMAN_EVAL = os.path.join(ROOT, \"..\", \"data\", \"HumanEval.jsonl.gz\")"
},
{
"identifier": "evaluate_functional_correctness",
"path": "Evaluation/MBPP/human_eval/evaluation.py",
"snippet": "def eva... | import fire
import sys
from .data import HUMAN_EVAL
from .evaluation import evaluate_functional_correctness | 1,125 |
def entry_point(
sample_file: str,
k: str = "1,10,100",
n_workers: int = 4,
timeout: float = 3.0,
problem_file: str = "",
is_mbpp: bool = False,
):
"""
Evaluates the functional correctness of generated samples, and writes
results to f"{sample_file}_results.jsonl.gz"
"""
k ... |
def entry_point(
sample_file: str,
k: str = "1,10,100",
n_workers: int = 4,
timeout: float = 3.0,
problem_file: str = "",
is_mbpp: bool = False,
):
"""
Evaluates the functional correctness of generated samples, and writes
results to f"{sample_file}_results.jsonl.gz"
"""
k ... | results = evaluate_functional_correctness(sample_file, k, n_workers, timeout, problem_file, is_mbpp) | 1 | 2023-10-20 06:38:01+00:00 | 2k |
PKU-YuanGroup/Video-LLaVA | llava/model/llava_arch.py | [
{
"identifier": "build_image_tower",
"path": "llava/model/multimodal_encoder/builder.py",
"snippet": "def build_image_tower(image_tower_cfg, **kwargs):\n image_tower = getattr(image_tower_cfg, 'mm_image_tower', getattr(image_tower_cfg, 'image_tower', None))\n is_absolute_path_exists = os.path.exis... | from abc import ABC, abstractmethod
from .multimodal_encoder.builder import build_image_tower, build_video_tower
from .multimodal_projector.builder import build_vision_projector
from llava.constants import IGNORE_INDEX, X_TOKEN_INDEX, DEFAULT_X_PATCH_TOKEN, DEFAULT_X_START_TOKEN, DEFAULT_X_END_TOKEN
import torch
import... | 1,164 | # Copyright 2023 Haotian Liu
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | # Copyright 2023 Haotian Liu
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | self.mm_projector = build_vision_projector(config) | 2 | 2023-10-23 05:43:54+00:00 | 2k |
deepseek-ai/DreamCraft3D | extern/ldm_zero123/models/diffusion/ddim.py | [
{
"identifier": "norm_thresholding",
"path": "extern/ldm_zero123/models/diffusion/sampling_util.py",
"snippet": "def norm_thresholding(x0, value):\n s = append_dims(x0.pow(2).flatten(1).mean(1).sqrt().clamp(min=value), x0.ndim)\n return x0 * (value / s)"
},
{
"identifier": "renorm_threshol... | from functools import partial
from tqdm import tqdm
from extern.ldm_zero123.models.diffusion.sampling_util import (
norm_thresholding,
renorm_thresholding,
spatial_norm_thresholding,
)
from extern.ldm_zero123.modules.diffusionmodules.util import (
extract_into_tensor,
make_ddim_sampling_parameters,
... | 1,515 | """SAMPLING ONLY."""
class DDIMSampler(object):
def __init__(self, model, schedule="linear", **kwargs):
super().__init__()
self.model = model
self.ddpm_num_timesteps = model.num_timesteps
self.schedule = schedule
def to(self, device):
"""Same as to in torch module
... | """SAMPLING ONLY."""
class DDIMSampler(object):
def __init__(self, model, schedule="linear", **kwargs):
super().__init__()
self.model = model
self.ddpm_num_timesteps = model.num_timesteps
self.schedule = schedule
def to(self, device):
"""Same as to in torch module
... | self.ddim_timesteps = make_ddim_timesteps( | 5 | 2023-10-23 07:40:20+00:00 | 2k |
YORG-AI/Open-Assistant | package/src/yorgassistant/core/nodes/github/github_search.py | [
{
"identifier": "BaseNode",
"path": "package/src/yorgassistant/core/nodes/base_node.py",
"snippet": "class BaseNode(ABC):\n config: NodeConfig\n func_mapping: dict[str, Callable]\n\n def __init__(self):\n # initialize func_mapping\n self.func_mapping = {}\n avail_funcs = [\... | from ..base_node import BaseNode, NodeConfig
from .github_node import GithubNode
from .github_model import (
SearchCodeInput,
SearchCommitsInput,
SearchIssuesAndPRsInput,
SearchLabelsInput,
SearchRepositoriesInput,
SearchTopicsInput,
SearchUsersInput,
) | 889 |
github_search_node_config = {
"name": "github_search",
"description": "A node for searching various entities on GitHub.",
"functions": {
"search_code": "Search code.",
"search_commits": "Search commits.",
"search_issues_and_prs": "Search issues and pull requests.",
"search_l... |
github_search_node_config = {
"name": "github_search",
"description": "A node for searching various entities on GitHub.",
"functions": {
"search_code": "Search code.",
"search_commits": "Search commits.",
"search_issues_and_prs": "Search issues and pull requests.",
"search_l... | class GithubSearchNode(GithubNode): | 2 | 2023-10-24 15:15:48+00:00 | 2k |
zju3dv/4K4D | scripts/realtime4dv/charger.py | [
{
"identifier": "to_numpy",
"path": "easyvolcap/utils/data_utils.py",
"snippet": "def to_numpy(batch, non_blocking=False, ignore_list: bool = False) -> Union[List, Dict, np.ndarray]: # almost always exporting, should block\n if isinstance(batch, (tuple, list)) and not ignore_list:\n batch = [... | from os.path import join
from easyvolcap.utils.console_utils import *
from easyvolcap.utils.data_utils import to_numpy
from easyvolcap.utils.net_utils import save_npz
from easyvolcap.scripts.main import test # will do everything a normal user would do
from easyvolcap.engine import cfg
from easyvolcap.engine... | 690 | # This function will try to invoke evc programmatically
@catch_throw
def main():
# fmt: off
sys.path.append('.')
sep_ind = sys.argv.index('--')
our_args = sys.argv[1:sep_ind]
evv_args = sys.argv[sep_ind + 1:]
sys.argv = [sys.argv[0]] + ['-t','test'] + evv_args
parser = argparse.ArgumentP... | # This function will try to invoke evc programmatically
@catch_throw
def main():
# fmt: off
sys.path.append('.')
sep_ind = sys.argv.index('--')
our_args = sys.argv[1:sep_ind]
evv_args = sys.argv[sep_ind + 1:]
sys.argv = [sys.argv[0]] + ['-t','test'] + evv_args
parser = argparse.ArgumentP... | assert args.save_pt or args.save_npz | 1 | 2023-10-17 04:48:46+00:00 | 2k |
pchunduri6/rag-demystified | complex_qa.py | [
{
"identifier": "generate_subquestions",
"path": "subquestion_generator.py",
"snippet": "def generate_subquestions(\n question,\n file_names: List[str] = None,\n system_prompt=DEFAULT_SUBQUESTION_GENERATOR_PROMPT,\n user_task=DEFAULT_USER_TASK,\n llm_model=\"gpt-4-0613\",\n):\n \"\"\"G... | import os
import requests
import warnings
import evadb
from dotenv import load_dotenv
from pathlib import Path
from subquestion_generator import generate_subquestions
from openai_utils import llm_call | 1,593 |
warnings.filterwarnings("ignore")
if not load_dotenv():
print(
"Could not load .env file or it is empty. Please check if it exists and is readable."
)
exit(1)
def generate_vector_stores(cursor, docs):
"""Generate a vector store for the docs using evadb.
"""
for doc in docs:
... |
warnings.filterwarnings("ignore")
if not load_dotenv():
print(
"Could not load .env file or it is empty. Please check if it exists and is readable."
)
exit(1)
def generate_vector_stores(cursor, docs):
"""Generate a vector store for the docs using evadb.
"""
for doc in docs:
... | response, cost = llm_call(model=llm_model, user_prompt=user_prompt) | 1 | 2023-10-18 16:32:51+00:00 | 2k |
predibase/lorax | server/lorax_server/utils/sources/hub.py | [
{
"identifier": "BaseModelSource",
"path": "server/lorax_server/utils/sources/source.py",
"snippet": "class BaseModelSource:\n def remote_weight_files(self, extension: str = None):\n raise NotImplementedError\n\n def weight_files(self, extension: str = None):\n raise NotImplementedEr... | import time
import os
from datetime import timedelta
from loguru import logger
from pathlib import Path
from typing import Optional, List
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE
from huggingface_hub.utils import (
LocalEntryNotFoundError,
En... | 1,180 |
WEIGHTS_CACHE_OVERRIDE = os.getenv("WEIGHTS_CACHE_OVERRIDE", None)
def get_hub_model_local_dir(model_id: str) -> Path:
object_id = model_id.replace("/", "--")
repo_cache = Path(HUGGINGFACE_HUB_CACHE) / f"models--{object_id}"
return repo_cache
def weight_hub_files(
model_id: str, revision: Option... |
WEIGHTS_CACHE_OVERRIDE = os.getenv("WEIGHTS_CACHE_OVERRIDE", None)
def get_hub_model_local_dir(model_id: str) -> Path:
object_id = model_id.replace("/", "--")
repo_cache = Path(HUGGINGFACE_HUB_CACHE) / f"models--{object_id}"
return repo_cache
def weight_hub_files(
model_id: str, revision: Option... | cache_file = try_to_load_from_cache( | 1 | 2023-10-20 18:19:49+00:00 | 2k |
codefuse-ai/Test-Agent | chat/server/monitor/clean_chat_data.py | [
{
"identifier": "NUM_SERVERS",
"path": "chat/server/monitor/basic_stats.py",
"snippet": "NUM_SERVERS = 14"
},
{
"identifier": "to_openai_format",
"path": "chat/server/monitor/clean_battle_data.py",
"snippet": "def to_openai_format(messages):\n roles = [\"user\", \"assistant\"]\n re... | import argparse
import datetime
import json
import os
import time
from pytz import timezone
from tqdm import tqdm
from chat.server.monitor.basic_stats import NUM_SERVERS
from chat.server.monitor.clean_battle_data import (
to_openai_format,
replace_model_name,
)
from chat.utils import detect_language | 854 | """
Clean chatbot arena chat log.
Usage:
python3 clean_chat_data.py --mode conv_release
"""
NETWORK_ERROR_MSG = (
"NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.".lower()
)
def get_log_files(max_num_files=None):
dates = []
for month in [4, 5, 6, 7]:
for day in rang... | """
Clean chatbot arena chat log.
Usage:
python3 clean_chat_data.py --mode conv_release
"""
NETWORK_ERROR_MSG = (
"NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.".lower()
)
def get_log_files(max_num_files=None):
dates = []
for month in [4, 5, 6, 7]:
for day in rang... | conversation = to_openai_format(state["messages"][state["offset"] :]) | 1 | 2023-10-20 08:56:20+00:00 | 2k |
Subsets and Splits
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have consistent code formatting levels across multiple scales (2k, 4k, 8k, 12k) and reveals the structured formatting patterns within these repositories.
SQL Console for tianyang/repobench_python_v1.1
Compares cross-file and in-file code structure patterns across different complexity levels, revealing how file organization strategies vary with code size and potentially informing better code architecture decisions.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have complete performance data across all seven code complexity levels, revealing consistent benchmarking patterns across different code sizes.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that contain all 7 distinct quality levels (2k through 32k), revealing complete datasets that might be useful for comprehensive analysis.