crossfile_context_retrievalwref
dict
prompt
stringlengths
252
32.6k
right_context
stringlengths
0
81.2k
metadata
dict
crossfile_context_retrieval
dict
groundtruth
stringlengths
5
208
{ "list": [ { "filename": "AITemplate/ait/compile/controlnet.py", "retrieved_chunk": " addition_embed_type=addition_embed_type,\n num_class_embeds=num_class_embeds,\n projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,\n dtype=\"float16\",\n )\n ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # 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...
else: Y = ait_vae.decode(ait_input) mark_output(Y) target = detect_target( use_fp16_acc=use_fp16_acc, convert_conv_to_gemm=convert_conv_to_gemm ) dll_name = model_name + ".dll" if sys.platform == "win32" else model_name + ".so" total_usage = compile_model( Y, target, wor...
{ "context_start_lineno": 0, "file": "AITemplate/ait/compile/vae.py", "groundtruth_start_lineno": 117, "repository": "FizzleDorf-AIT-ad34668", "right_context_start_lineno": 118, "task_id": "project_cc_python/8892" }
{ "list": [ { "filename": "AITemplate/ait/compile/clip.py", "retrieved_chunk": " else:\n batch_size = IntVar(values=list(batch_size), name=\"batch_size\")\n input_ids_ait = Tensor(\n [batch_size, seqlen], name=\"input_ids\", dtype=\"int64\", is_input=True\n )\n position_ids_a...
encode(ait_input, sample)
{ "list": [ { "filename": "AITemplate/ait/compile/controlnet.py", "retrieved_chunk": " addition_embed_type=addition_embed_type,\n num_class_embeds=num_class_embeds,\n projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,\n dtype=\"float16\",\n )\n ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # 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...
mark_output(Y) target = detect_target( use_fp16_acc=use_fp16_acc, convert_conv_to_gemm=convert_conv_to_gemm ) dll_name = model_name + ".dll" if sys.platform == "win32" else model_name + ".so" total_usage = compile_model( Y, target, work_dir, model_name, constants=params_ait if const...
{ "context_start_lineno": 0, "file": "AITemplate/ait/compile/vae.py", "groundtruth_start_lineno": 119, "repository": "FizzleDorf-AIT-ad34668", "right_context_start_lineno": 120, "task_id": "project_cc_python/8893" }
{ "list": [ { "filename": "AITemplate/ait/compile/controlnet.py", "retrieved_chunk": " batch_size = batch_size[0] * 2 # double batch size for unet\n height_d = height[0] // down_factor\n width_d = width[0] // down_factor\n height_c = height[0]\n width_c = width[0]\n...
decode(ait_input)
{ "list": [ { "filename": "pain001/xml/create_root_element.py", "retrieved_chunk": " \"urn:iso:std:iso:20022:tech:xsd:\"\n + payment_initiation_message_type\n )\n # Create the root element.\n root = ET.Element(\"Document\")\n root.set(\"xmlns\", namespace)\n root.set(\"xml...
from pain001.xml.create_root_element import create_root_element import xml.etree.ElementTree as ET # Test if the root element is created correctly def test_create_root_element(): # Define the XML message type payment_initiation_message_type = "pain.001.001.03" # Create the root element root = creat...
root.set('xmlns:foo', 'http://example.com/foo') assert root.attrib['xmlns:xs'] == 'http://www.w3.org/2001/XMLSchema' assert root.attrib['xmlns:foo'] == 'http://example.com/foo'
{ "context_start_lineno": 0, "file": "tests/test_create_root_element.py", "groundtruth_start_lineno": 108, "repository": "sebastienrousseau-pain001-86a271f", "right_context_start_lineno": 109, "task_id": "project_cc_python/8923" }
{ "list": [ { "filename": "pain001/xml/create_root_element.py", "retrieved_chunk": " )\n root.set(\"xsi:schemaLocation\", schema_location)\n for elem in root.iter():\n elem.tag = elem.tag.split(\"}\", 1)[-1]\n return root", "score": 51.87445339909726 }, { "filena...
set('xmlns:xs', 'http://www.w3.org/2001/XMLSchema')
{ "list": [ { "filename": "src/agents/utils/juniordevprompt.py", "retrieved_chunk": " </div>\n );\n}\n``` )\nYou can only use tools and agents that are available to you. You can't invent new tools or agents.\nOnce a step is done and you have the result, you remove the step from the plan and contin...
import agents.utils.basicprompts as p system_init = """ Your name is debugGpt and your are an experienced web developper. You are here to help the user debug his app and fix the errors. You are a very good developer, and you know how to write clean, maintainable code. You are also able to come up with creative solut...
tools_n_agents = p.tools_n_agents_init + tools_list + agents_list tech = p.tech_stack + p.tech_rules realquick = """You are a planner AI. Your goal is to debug a web application, but you need to do everything through JuniorDevGpt. To use it, say: juniorDevGpt(command) Answer with the command only and nothing else.""...
{ "context_start_lineno": 0, "file": "src/agents/utils/seniordevprompt.py", "groundtruth_start_lineno": 118, "repository": "mecene-studio-debugGpt-20e9b61", "right_context_start_lineno": 119, "task_id": "project_cc_python/8941" }
{ "list": [ { "filename": "src/agents/utils/juniordevprompt.py", "retrieved_chunk": "def getJuniorDevPromptMessages():\n plannerPrompt = (\n system_init\n + tools_n_agents\n + good_n_bad_examples\n + remember\n + reevaluateAtEachStep\n + remember_only_use\n...
using_steps + reevaluateAtEachStep
{ "list": [ { "filename": "AITemplate/ait/load.py", "retrieved_chunk": " self,\n state_dict: dict,\n ) -> dict:\n \"\"\"\n removes:\n first_stage_model.\n from keys if present before conversion\n \"\"\"\n return convert_ldm_vae_checkpoint(stat...
from typing import Literal, Union import torch from safetensors.torch import load_file from .load import AITLoader from .module import Model from .inference import clip_inference, unet_inference, vae_inference, controlnet_inference class AIT: def __init__(self, path: str = None) -> None: self.modules = ...
self.modules["clip"] = self.loader.apply_clip(self.modules["clip"], clip) elif module_type == "controlnet": self.modules["controlnet"] = self.loader.load(aitemplate_path) controlnet = self.loader.compvis_controlnet(state_dict) self.modules["controlnet"] = self.lo...
{ "context_start_lineno": 0, "file": "AITemplate/ait/ait.py", "groundtruth_start_lineno": 72, "repository": "FizzleDorf-AIT-ad34668", "right_context_start_lineno": 73, "task_id": "project_cc_python/8883" }
{ "list": [ { "filename": "AITemplate/ait/load.py", "retrieved_chunk": " self,\n state_dict: dict,\n ) -> dict:\n \"\"\"\n removes:\n control_model.\n from keys if present before conversion\n \"\"\"\n return convert_ldm_unet_checkpoint(state_d...
compvis_clip(state_dict)
{ "list": [ { "filename": "src/agents/utils/juniordevprompt.py", "retrieved_chunk": " </div>\n );\n}\n``` )\nYou can only use tools and agents that are available to you. You can't invent new tools or agents.\nOnce a step is done and you have the result, you remove the step from the plan and contin...
import agents.utils.basicprompts as p system_init = """ Your name is debugGpt and your are an experienced web developper. You are here to help the user debug his app and fix the errors. You are a very good developer, and you know how to write clean, maintainable code. You are also able to come up with creative solut...
realquick = """You are a planner AI. Your goal is to debug a web application, but you need to do everything through JuniorDevGpt. To use it, say: juniorDevGpt(command) Answer with the command only and nothing else.""" def getSeniorDevPromptMessages(): promptMessage = [ {"role": "system", "content": ini...
{ "context_start_lineno": 0, "file": "src/agents/utils/seniordevprompt.py", "groundtruth_start_lineno": 120, "repository": "mecene-studio-debugGpt-20e9b61", "right_context_start_lineno": 121, "task_id": "project_cc_python/8943" }
{ "list": [ { "filename": "src/agents/utils/juniordevprompt.py", "retrieved_chunk": "def getJuniorDevPromptMessages():\n plannerPrompt = (\n system_init\n + tools_n_agents\n + good_n_bad_examples\n + remember\n + reevaluateAtEachStep\n + remember_only_use\n...
tech_stack + p.tech_rules
{ "list": [ { "filename": "src/agents/utils/juniordevprompt.py", "retrieved_chunk": " </div>\n );\n}\n``` )\nYou can only use tools and agents that are available to you. You can't invent new tools or agents.\nOnce a step is done and you have the result, you remove the step from the plan and contin...
import agents.utils.basicprompts as p system_init = """ Your name is debugGpt and your are an experienced web developper. You are here to help the user debug his app and fix the errors. You are a very good developer, and you know how to write clean, maintainable code. You are also able to come up with creative solut...
tools_n_agents = p.tools_n_agents_init + tools_list + agents_list tech = p.tech_stack + p.tech_rules realquick = """You are a planner AI. Your goal is to debug a web application, but you need to do everything through JuniorDevGpt. To use it, say: juniorDevGpt(command) Answer with the command only and nothing else.""...
{ "context_start_lineno": 0, "file": "src/agents/utils/seniordevprompt.py", "groundtruth_start_lineno": 118, "repository": "mecene-studio-debugGpt-20e9b61", "right_context_start_lineno": 119, "task_id": "project_cc_python/8940" }
{ "list": [ { "filename": "src/agents/utils/juniordevprompt.py", "retrieved_chunk": "def getJuniorDevPromptMessages():\n plannerPrompt = (\n system_init\n + tools_n_agents\n + good_n_bad_examples\n + remember\n + reevaluateAtEachStep\n + remember_only_use\n...
prompting_utils + p.using_steps + reevaluateAtEachStep
{ "list": [ { "filename": "speechai/tts/gtts.py", "retrieved_chunk": "from gtts import gTTS\nfrom gtts.tokenizer.pre_processors import abbreviations, end_of_line\nfrom speechai.tts.abstract_tts import AbstractTTS\nclass GTTS(AbstractTTS):\n __language: str\n def __init__(self, language_code=\"en...
from unittest.mock import Mock import pytest from gtts.tokenizer.pre_processors import abbreviations, end_of_line from speechai.tts.gtts import GTTS @pytest.fixture(name="mock_gtts") def fixture_mock_gtts(mocker): return mocker.patch("speechai.tts.gtts.gTTS", autospec=True) def test_gtts_initialization(): ...
mock_gtts.assert_called_once_with(text, lang=gtts.get_language(), pre_processor_funcs=[abbreviations, end_of_line]) mock_tts_instance.save.assert_called_once_with(save_to) def test_gtts_set_language(): gtts = GTTS() language_code = "es" gtts.set_language(language_code) assert gtts.get_languag...
{ "context_start_lineno": 0, "file": "tests/tts/test_gtts.py", "groundtruth_start_lineno": 26, "repository": "nicolasebastianelli-speech-ai-323473b", "right_context_start_lineno": 27, "task_id": "project_cc_python/8993" }
{ "list": [ { "filename": "speechai/tts/gtts.py", "retrieved_chunk": " return save_to\n def get_language(self):\n return self.__language\n def set_language(self, language_code: str):\n self.__language = language_code", "score": 22.905230511838628 }, { "fi...
text_to_speech(text, save_to) == save_to
{ "list": [ { "filename": "src/gptbot/classes/trackingmore.py", "retrieved_chunk": " operator: str = \"TrackingMore ([https://www.trackingmore.com](https://www.trackingmore.com))\"\n def __init__(self, api_key: str, logger: Optional[Logger] = None):\n self.api_key: str = api_key\n ...
import wolframalpha import requests from .logging import Logger from typing import Dict, List, Tuple, Generator, Optional class WolframAlpha: api_key: str logger: Logger client: wolframalpha.Client api_code: str = "wolfram" calculation_api: str = "alpha" operator: str = "Wolfram ([https://w...
if not response.success: yield "Could not process your query." if response.didyoumeans: yield "Did you mean: " + response.didyoumeans["didyoumean"][0]["#text"] return if response.error: self.logger.log("Error in query to WolframAlpha: ...
{ "context_start_lineno": 0, "file": "src/gptbot/classes/wolframalpha.py", "groundtruth_start_lineno": 25, "repository": "kumitterer-matrix-gptbot-d2c6682", "right_context_start_lineno": 26, "task_id": "project_cc_python/8929" }
{ "list": [ { "filename": "src/gptbot/classes/trackingmore.py", "retrieved_chunk": " response = self.client.track_shipment(query)\n return response, 1", "score": 145.24077690297094 }, { "filename": "src/gptbot/classes/openai.py", "retrieved_chunk": " self...
Result = self.client.query(query)
{ "list": [ { "filename": "finetune_fp16.py", "retrieved_chunk": " r=LORA_R,\n lora_alpha=LORA_ALPHA,\n target_modules=TARGET_MODULES,\n lora_dropout=LORA_DROPOUT,\n bias=\"none\",\n task_type=\"CAUSAL_LM\",\n)\nmodel = get_peft_model(model, config)\ntokenizer.pad_token_id = 0 # unk...
from peft import ( prepare_model_for_int8_training, LoraConfig, PeftModel, get_peft_model, get_peft_model_state_dict, set_peft_model_state_dict, ) from transformers import LlamaForCausalLM, LlamaTokenizer, TrainerCallback, GenerationConfig import os import sys import torch import torch.nn as nn ...
else: raise Exception('not support') # check tokenizer data = load_dataset('json', data_files=DATA_PATH) import random;start = random.randint(1, 100) examples = Dataset.from_dict(data['train'][start:start+5]).map(PROMPT.preprocess_train) for example in examples: logger.info(f'>>> using prompt {args.prompt_type...
{ "context_start_lineno": 0, "file": "finetune_chat.py", "groundtruth_start_lineno": 116, "repository": "Facico-Chinese-Vicuna-1c4cbfc", "right_context_start_lineno": 117, "task_id": "project_cc_python/8972" }
{ "list": [ { "filename": "finetune_fp16.py", "retrieved_chunk": "data = load_dataset(\"json\", data_files=DATA_PATH)\nnow_max_steps = max((len(data[\"train\"]) - VAL_SET_SIZE) // BATCH_SIZE * EPOCHS, EPOCHS)\nif args.resume_from_checkpoint:\n if args.lora_remote_checkpoint is not None:\n sn...
chat_prompt(train_tokenizer,CUTOFF_LEN)
{ "list": [ { "filename": "finetune_4bit.py", "retrieved_chunk": " print(f'>>> tokenizer example: { example[\"input_ids\"][:250] }...{ example[\"input_ids\"][-10:]}')\nnow_max_steps = max((len(data[\"train\"]) - VAL_SET_SIZE) // BATCH_SIZE * EPOCHS, EPOCHS)\nif args.resume_from_checkpoint:\n if ...
from peft import ( prepare_model_for_int8_training, LoraConfig, PeftModel, get_peft_model, get_peft_model_state_dict, set_peft_model_state_dict, ) from transformers import LlamaForCausalLM, LlamaTokenizer, TrainerCallback, GenerationConfig import os import sys import torch import torch.nn as nn ...
# 1. load dataset logger.info(f'>>> processing data from {DATA_PATH}') logger.info(f'>>> using {args}') train_tokenizer = LlamaTokenizer.from_pretrained(args.model_path, add_eos_token=True) assert train_tokenizer.eos_token_id == 2, "Tokenizer eos is wrong!!!" # unk. we want this to be different from the eos token tra...
{ "context_start_lineno": 0, "file": "finetune_chat.py", "groundtruth_start_lineno": 101, "repository": "Facico-Chinese-Vicuna-1c4cbfc", "right_context_start_lineno": 102, "task_id": "project_cc_python/8970" }
{ "list": [ { "filename": "tools/merge_lora.py", "retrieved_chunk": "assert n_heads == params[model_size][\"n_heads\"]\ndim = base_model.config.hidden_size\nassert dim == params[model_size][\"dim\"]\ndims_per_head = dim // n_heads\nbase = 10000.0\ninv_freq = 1.0 / (base ** (torch.arange(0, dims_per_he...
set_file_logger(__name__,OUTPUT_DIR)
{ "list": [ { "filename": "tools/quant_generate.py", "retrieved_chunk": " del layers[name]\n quant.make_quant_linear(model, layers, wbits, groupsize)\n del layers\n print('Loading model ...')\n model.load_state_dict(torch.load(checkpoint), strict=False)\n quant.make_quant_att...
import argparse import time import numpy as np import torch import torch.nn as nn import quant from gptq import GPTQ from datautils import get_loaders def find_layers(module, layers=[nn.Conv2d, nn.Linear], name=''): if type(module) in layers: return {name: module} res = {} for name1, child in modu...
qlayers = find_layers(model, [quant.QuantLinear]) print('Packing ...') for name in qlayers: print(name) quantizers[name], scale, zero, g_idx, _, _ = quantizers[name] qlayers[name].pack(layers[name], scale, zero, g_idx) print('Done.') return model def load_quant(model, chec...
{ "context_start_lineno": 0, "file": "tools/quant_llama.py", "groundtruth_start_lineno": 234, "repository": "Facico-Chinese-Vicuna-1c4cbfc", "right_context_start_lineno": 235, "task_id": "project_cc_python/8974" }
{ "list": [ { "filename": "tools/quant_generate.py", "retrieved_chunk": " if eval and fused_mlp:\n quant.autotune_warmup_fused(model)\n model.seqlen = 2048\n print('Done.')\n return model\ndef generate_prompt(instruction, input=None):\n if input:\n return f\"\"\"Be...
make_quant_linear(model, quantizers, wbits, groupsize)
{ "list": [ { "filename": "finetune_fp16.py", "retrieved_chunk": " r=LORA_R,\n lora_alpha=LORA_ALPHA,\n target_modules=TARGET_MODULES,\n lora_dropout=LORA_DROPOUT,\n bias=\"none\",\n task_type=\"CAUSAL_LM\",\n)\nmodel = get_peft_model(model, config)\ntokenizer.pad_token_id = 0 # unk...
from peft import ( prepare_model_for_int8_training, LoraConfig, PeftModel, get_peft_model, get_peft_model_state_dict, set_peft_model_state_dict, ) from transformers import LlamaForCausalLM, LlamaTokenizer, TrainerCallback, GenerationConfig import os import sys import torch import torch.nn as nn ...
elif args.prompt_type == 'chat': PROMPT = prompt.chat_prompt(train_tokenizer,CUTOFF_LEN) else: raise Exception('not support') # check tokenizer data = load_dataset('json', data_files=DATA_PATH) import random;start = random.randint(1, 100) examples = Dataset.from_dict(data['train'][start:start+5]).map(PROMPT.pr...
{ "context_start_lineno": 0, "file": "finetune_chat.py", "groundtruth_start_lineno": 114, "repository": "Facico-Chinese-Vicuna-1c4cbfc", "right_context_start_lineno": 115, "task_id": "project_cc_python/8971" }
{ "list": [ { "filename": "finetune_fp16.py", "retrieved_chunk": "data = load_dataset(\"json\", data_files=DATA_PATH)\nnow_max_steps = max((len(data[\"train\"]) - VAL_SET_SIZE) // BATCH_SIZE * EPOCHS, EPOCHS)\nif args.resume_from_checkpoint:\n if args.lora_remote_checkpoint is not None:\n sn...
instruct_prompt(train_tokenizer, CUTOFF_LEN)
{ "list": [ { "filename": "calibration/camera.py", "retrieved_chunk": " assert K[2, 0] == 0.0\n assert K[2, 1] == 0.0\n assert K[2, 2] == 1.0\n self.K = K\n self.K.register_hook(zero_K_gradient)\n assert lensnet is None or isinstance(lensnet, LensNet)\n ...
import torch from ..camera import Camera from ..networks import LensNet def cli(): RT = torch.eye(3, 4) RT[0, 3] = 5.0 cam = Camera(torch.eye(3), lensnet=LensNet(), RT=RT) # import pdb # pdb.set_trace() pt = torch.tensor([[1.0, 4.0, 5.0]], dtype=torch.float32) proj = cam.project_points(pt)...
print(f"unproj: {unproj}") ray = cam.get_rays_view(torch.tensor([[0.2, 0.8]])) print(f"ray: {ray}")
{ "context_start_lineno": 0, "file": "calibration/scripts/project.py", "groundtruth_start_lineno": 14, "repository": "wxian3-NeuroLens-380d68c", "right_context_start_lineno": 15, "task_id": "project_cc_python/9025" }
{ "list": [ { "filename": "calibration/camera.py", "retrieved_chunk": " else:\n assert RT.ndim == 2\n assert RT.shape[0] == 3\n assert RT.shape[1] == 4\n self.RT = RT\n @property\n def RT(self):\n rot_mat = rotation_6d_to_matrix(self.R[No...
unproject_points(torch.tensor([[proj[0, 0], proj[0, 1], 5.0]]))
{ "list": [ { "filename": "badger_os/examples/news.py", "retrieved_chunk": " gc.collect()\n else:\n text += char\ndef measure_qr_code(size, code):\n w, h = code.get_size()\n module_size = int(size / w)\n return module_size * w, module_size\ndef draw_qr_code(ox...
import badger2040 import qrcode import time import os import badger_os # Check that the qrcodes directory exists, if not, make it try: os.mkdir("/qrcodes") except OSError: pass # Check that there is a qrcode.txt, if not preload try: text = open("/qrcodes/qrcode.txt", "r") except OSError: text = open("...
top = 40 for line in detail_text: display.text(line, left, top, badger2040.WIDTH, 1) top += 10 if TOTAL_CODES > 1: for i in range(TOTAL_CODES): x = 286 y = int((128 / 2) - (TOTAL_CODES * 10 / 2) + (i * 10)) display.set_pen(0) display...
{ "context_start_lineno": 0, "file": "badger_os/examples/qrgen.py", "groundtruth_start_lineno": 103, "repository": "pimoroni-badger2040-24d6eb6", "right_context_start_lineno": 104, "task_id": "project_cc_python/9047" }
{ "list": [ { "filename": "badger_os/examples/news.py", "retrieved_chunk": " display.rectangle(ox, oy, size, size)\n display.set_pen(0)\n for x in range(size):\n for y in range(size):\n if code.get_module(x, y):\n display.rectangle(ox + x * module_size, oy + y...
WIDTH, 2)
{ "list": [ { "filename": "calibration/camera.py", "retrieved_chunk": " assert K[2, 0] == 0.0\n assert K[2, 1] == 0.0\n assert K[2, 2] == 1.0\n self.K = K\n self.K.register_hook(zero_K_gradient)\n assert lensnet is None or isinstance(lensnet, LensNet)\n ...
import torch from ..camera import Camera from ..networks import LensNet def cli(): RT = torch.eye(3, 4) RT[0, 3] = 5.0 cam = Camera(torch.eye(3), lensnet=LensNet(), RT=RT) # import pdb # pdb.set_trace() pt = torch.tensor([[1.0, 4.0, 5.0]], dtype=torch.float32) proj = cam.project_points(pt)...
print(f"ray: {ray}")
{ "context_start_lineno": 0, "file": "calibration/scripts/project.py", "groundtruth_start_lineno": 16, "repository": "wxian3-NeuroLens-380d68c", "right_context_start_lineno": 17, "task_id": "project_cc_python/9026" }
{ "list": [ { "filename": "calibration/camera.py", "retrieved_chunk": " else:\n assert RT.ndim == 2\n assert RT.shape[0] == 3\n assert RT.shape[1] == 4\n self.RT = RT\n @property\n def RT(self):\n rot_mat = rotation_6d_to_matrix(self.R[No...
get_rays_view(torch.tensor([[0.2, 0.8]]))
{ "list": [ { "filename": "badger_os/examples/image.py", "retrieved_chunk": " display.keepalive()\n if display.pressed(badger2040.BUTTON_UP):\n if state[\"current_image\"] > 0:\n state[\"current_image\"] -= 1\n changed = True\n if display.pressed(badger2040.BUTTON...
import badger2040 import qrcode import time import os import badger_os # Check that the qrcodes directory exists, if not, make it try: os.mkdir("/qrcodes") except OSError: pass # Check that there is a qrcode.txt, if not preload try: text = open("/qrcodes/qrcode.txt", "r") except OSError: text = open("...
display.set_pen(15) display.clear() badger_os.warning(display, "To add QR codes, connect Badger 2040 W to a PC, load up Thonny, and add files to /qrcodes directory.") time.sleep(4) changed = True if changed: draw_qr_file(state["current_qr"]) badger_os.state_...
{ "context_start_lineno": 0, "file": "badger_os/examples/qrgen.py", "groundtruth_start_lineno": 141, "repository": "pimoroni-badger2040-24d6eb6", "right_context_start_lineno": 142, "task_id": "project_cc_python/9051" }
{ "list": [ { "filename": "badger_os/examples/image.py", "retrieved_chunk": " state[\"show_info\"] = not state[\"show_info\"]\n changed = True\n if changed:\n show_image(state[\"current_image\"])\n badger_os.state_save(\"image\", state)\n changed = False\n # Ha...
BUTTON_B) or display.pressed(badger2040.BUTTON_C):
{ "list": [ { "filename": "badger_os/examples/badge.py", "retrieved_chunk": " display.line(WIDTH - IMAGE_WIDTH, HEIGHT - 1, WIDTH - 1, HEIGHT - 1)\n display.line(WIDTH - 1, 0, WIDTH - 1, HEIGHT - 1)\n # Uncomment this if a white background is wanted behind the company\n # display.set_pen(1...
import badger2040 import qrcode import time import os import badger_os # Check that the qrcodes directory exists, if not, make it try: os.mkdir("/qrcodes") except OSError: pass # Check that there is a qrcode.txt, if not preload try: text = open("/qrcodes/qrcode.txt", "r") except OSError: text = open("...
draw_qr_code(left, top, 128, code) left = 128 + 5 display.text(title_text, left, 20, badger2040.WIDTH, 2) top = 40 for line in detail_text: display.text(line, left, top, badger2040.WIDTH, 1) top += 10 if TOTAL_CODES > 1: for i in range(TOTAL_CODES): x = 2...
{ "context_start_lineno": 0, "file": "badger_os/examples/qrgen.py", "groundtruth_start_lineno": 98, "repository": "pimoroni-badger2040-24d6eb6", "right_context_start_lineno": 99, "task_id": "project_cc_python/9046" }
{ "list": [ { "filename": "badger_os/examples/badge.py", "retrieved_chunk": " display.set_pen(15)\n display.rectangle(1, COMPANY_HEIGHT + 1, TEXT_WIDTH, NAME_HEIGHT)\n # Draw the name, scaling it based on the available width\n display.set_pen(0)\n display.set_font(\"sans\")\n name_si...
HEIGHT / 2) - (size / 2))
{ "list": [ { "filename": "badger_os/examples/image.py", "retrieved_chunk": " display.keepalive()\n if display.pressed(badger2040.BUTTON_UP):\n if state[\"current_image\"] > 0:\n state[\"current_image\"] -= 1\n changed = True\n if display.pressed(badger2040.BUTTON...
import badger2040 import qrcode import time import os import badger_os # Check that the qrcodes directory exists, if not, make it try: os.mkdir("/qrcodes") except OSError: pass # Check that there is a qrcode.txt, if not preload try: text = open("/qrcodes/qrcode.txt", "r") except OSError: text = open("...
time.sleep(4) changed = True if changed: draw_qr_file(state["current_qr"]) badger_os.state_save("qrcodes", state) changed = False # Halt the Badger to save power, it will wake up if any of the front buttons are pressed display.halt()
{ "context_start_lineno": 0, "file": "badger_os/examples/qrgen.py", "groundtruth_start_lineno": 144, "repository": "pimoroni-badger2040-24d6eb6", "right_context_start_lineno": 145, "task_id": "project_cc_python/9053" }
{ "list": [ { "filename": "badger_os/examples/image.py", "retrieved_chunk": " state[\"show_info\"] = not state[\"show_info\"]\n changed = True\n if changed:\n show_image(state[\"current_image\"])\n badger_os.state_save(\"image\", state)\n changed = False\n # Ha...
warning(display, "To add QR codes, connect Badger 2040 W to a PC, load up Thonny, and add files to /qrcodes directory.")
{ "list": [ { "filename": "badger_os/examples/qrgen.py", "retrieved_chunk": " y = int((128 / 2) - (TOTAL_CODES * 10 / 2) + (i * 10))\n display.set_pen(0)\n display.rectangle(x, y, 8, 8)\n if state[\"current_qr\"] != i:\n display.set_pen(15)\n ...
import os import badger2040 from badger2040 import HEIGHT, WIDTH import badger_os import jpegdec TOTAL_IMAGES = 0 # Turn the act LED on as soon as possible display = badger2040.Badger2040() display.led(128) display.set_update_speed(badger2040.UPDATE_NORMAL) jpeg = jpegdec.JPEG(display.display) # Load images try:...
changed = True while True: # Sometimes a button press or hold will keep the system # powered *through* HALT, so latch the power back on. display.keepalive() if display.pressed(badger2040.BUTTON_UP): if state["current_image"] > 0: state["current_image"] -= 1 changed =...
{ "context_start_lineno": 0, "file": "badger_os/examples/image.py", "groundtruth_start_lineno": 63, "repository": "pimoroni-badger2040-24d6eb6", "right_context_start_lineno": 64, "task_id": "project_cc_python/9065" }
{ "list": [ { "filename": "badger_os/examples/qrgen.py", "retrieved_chunk": " # Sometimes a button press or hold will keep the system\n # powered *through* HALT, so latch the power back on.\n display.keepalive()\n if TOTAL_CODES > 1:\n if display.pressed(badger2040.BUTTON_UP):\n ...
state_load("image", state)
{ "list": [ { "filename": "badger_os/examples/weather.py", "retrieved_chunk": "URL = \"http://api.open-meteo.com/v1/forecast?latitude=\" + str(LAT) + \"&longitude=\" + str(LNG) + \"&current_weather=true&timezone=\" + TIMEZONE\n# Display Setup\ndisplay = badger2040.Badger2040()\ndisplay.led(128)\ndispl...
import badger2040 from badger2040 import WIDTH import machine from urllib import urequest import gc import qrcode import badger_os # URLS to use (Entertainment, Science and Technology) URL = ["http://feeds.bbci.co.uk/news/entertainment_and_arts/rss.xml", "http://feeds.bbci.co.uk/news/science_and_environment/rss...
# Display Setup display = badger2040.Badger2040() display.led(128) display.set_update_speed(2) # Setup buttons button_a = machine.Pin(badger2040.BUTTON_A, machine.Pin.IN, machine.Pin.PULL_DOWN) button_b = machine.Pin(badger2040.BUTTON_B, machine.Pin.IN, machine.Pin.PULL_DOWN) button_c = machine.Pin(badger2040.BUTTON...
{ "context_start_lineno": 0, "file": "badger_os/examples/news.py", "groundtruth_start_lineno": 20, "repository": "pimoroni-badger2040-24d6eb6", "right_context_start_lineno": 21, "task_id": "project_cc_python/9055" }
{ "list": [ { "filename": "badger_os/examples/weather.py", "retrieved_chunk": " print(f\"Requesting URL: {URL}\")\n r = urequests.get(URL)\n # open the json data\n j = r.json()\n print(\"Data obtained!\")\n print(j)\n # parse relevant data from JSON\n current = j[\"current_weat...
state_load("news", state)
{ "list": [ { "filename": "badger_os/launcher.py", "retrieved_chunk": " y = int((128 / 2) - (MAX_PAGE * 10 / 2) + (i * 10))\n display.set_pen(0)\n display.rectangle(x, y, 8, 8)\n if state[\"page\"] != i:\n display.set_pen(15)\n display.rectangle(x + 1,...
import badger2040 import qrcode import time import os import badger_os # Check that the qrcodes directory exists, if not, make it try: os.mkdir("/qrcodes") except OSError: pass # Check that there is a qrcode.txt, if not preload try: text = open("/qrcodes/qrcode.txt", "r") except OSError: text = open("...
changed = True while True: # Sometimes a button press or hold will keep the system # powered *through* HALT, so latch the power back on. display.keepalive() if TOTAL_CODES > 1: if display.pressed(badger2040.BUTTON_UP): if state["current_qr"] > 0: state["current_qr"...
{ "context_start_lineno": 0, "file": "badger_os/examples/qrgen.py", "groundtruth_start_lineno": 122, "repository": "pimoroni-badger2040-24d6eb6", "right_context_start_lineno": 123, "task_id": "project_cc_python/9048" }
{ "list": [ { "filename": "badger_os/launcher.py", "retrieved_chunk": " display.text(\"badgerOS\", 4, 4, WIDTH, 1.0)\n display.update()\ndef wait_for_user_to_release_buttons():\n while display.pressed_any():\n time.sleep(0.01)\ndef launch_example(index):\n wait_for_user_to_release_b...
state_load("qrcodes", state)
{ "list": [ { "filename": "data_model/reflection_data_persistentor.py", "retrieved_chunk": " traceback_str = traceback.format_exc()\n error_message = f\"ERROR: {str(e)}\"\n print(traceback_str + error_message)\n return\n #print(\"json_data:\", json.du...
#!/usr/bin/python # -*- coding: utf-8 -*- import pandas as pd import json from prompt_template import PromptTemplate from question import get_response from plan import Plan import os import traceback import json_utils from check_recover_json import check_json_str, recover_json_str class Planner: def __init__(self...
if "Strategies" not in self.strategy_history_json: self.strategy_history_json["Strategies"] = [] self.strategy_history_json["Strategies"].append(new_strategy) for entry in self.reply_json["Plan"]: self.plan.add_data(entry["DocumentID"], entry["Purpose"], entry["Perspect...
{ "context_start_lineno": 0, "file": "planner.py", "groundtruth_start_lineno": 96, "repository": "tmori-generative-agents-81cabfd", "right_context_start_lineno": 97, "task_id": "project_cc_python/8952" }
{ "list": [ { "filename": "check_recover_json.py", "retrieved_chunk": " except json.JSONDecodeError as e:\n traceback_str = traceback.format_exc()\n error_message = f\"ERROR: {str(e)}\"\n print(traceback_str + error_message)\n return (False, error_message)\ndef recover_j...
set_strategy(new_strategy)
{ "list": [ { "filename": "evaluator.py", "retrieved_chunk": " self.merged_data[\"DetailedStrategy\"] = self.plan.detailed_strategy\n self.merged_data[\"Plan\"] = []\n for entry in self.plan.get_json_data()[\"Plan\"]:\n tmp = copy.deepcopy(entry)\n new_entry ...
#!/usr/bin/python # -*- coding: utf-8 -*- import pandas as pd import json from prompt_template import PromptTemplate from question import get_response from plan import Plan import os import traceback import json_utils from check_recover_json import check_json_str, recover_json_str class Planner: def __init__(self...
def save_to_json(self, file_path): with open(file_path, 'w') as file: json.dump(self.reply_json, file, indent=4, ensure_ascii=False) def save_strategy_history(self): with open(self.strategy_history_path, 'w') as file: json.dump(self.strategy_history_json, file, indent=...
{ "context_start_lineno": 0, "file": "planner.py", "groundtruth_start_lineno": 102, "repository": "tmori-generative-agents-81cabfd", "right_context_start_lineno": 103, "task_id": "project_cc_python/8953" }
{ "list": [ { "filename": "evaluator.py", "retrieved_chunk": " if entry[\"ResultID\"] >= 0:\n data = self.memory_stream.get_data(entry[\"ResultID\"])\n #print(data)\n new_entry[\"ResultID\"] = { \"Reply\": data[\"Reply\"], \"Point...
add_data(entry["DocumentID"], entry["Purpose"], entry["Perspectives"])
{ "list": [ { "filename": "data_model/reflection_data_model.py", "retrieved_chunk": " #unreliable info\n return\n data = {\n \"KnownInfo\": known_info,\n \"DocumentIDs\": document_ids,\n \"Point\": point\n }\n if all(data.get(...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import json import traceback from data_model_accessor import DataModelAccessor from document_data_model import DocumentDataModel class DocumentDataPersistentor: def __init__(self, accessor: DataModelAccessor): self.accessor = accessor def save_docu...
if model.is_empty() == False: self.models.append(model) if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: <dir> <filepath>") sys.exit(1) dir = sys.argv[1] filepath = sys.argv[2] accessor = DataModelAccessor(dir) persistentor = DocumentData...
{ "context_start_lineno": 0, "file": "data_model/document_data_persistentor.py", "groundtruth_start_lineno": 38, "repository": "tmori-generative-agents-81cabfd", "right_context_start_lineno": 39, "task_id": "project_cc_python/8954" }
{ "list": [ { "filename": "data_model/reflection_data_model.py", "retrieved_chunk": " #print(\"known_info:\", known_info)\n if len(known_info) == 0:\n #print(\"skip1\")\n return\n if document_ids is None or len(document_ids) == 0:\n #unreliable inf...
create_from_plans(entry, json_data)
{ "list": [ { "filename": "plan.py", "retrieved_chunk": " self.detailed_strategy = detailed_strategy\n def add_data(self, document_id, purpose, perspectives):\n data = [[self.current_id, document_id, purpose, perspectives, \"\", \"None\"]]\n new_data = pd.DataFrame(data, column...
#!/usr/bin/python # -*- coding: utf-8 -*- from plan import Plan from prompt_template import PromptTemplate from db_manager import get_qa from question import TextQa import sys class TacticalPlanning: def __init__(self, plan: Plan, db_dir: str): self.plan = plan self.db_dir = db_dir def genera...
return query if __name__ == "__main__": if len(sys.argv) != 1 and len(sys.argv) != 2: print("USAGE: " + sys.argv[0] + " [text]") sys.exit(1) query_mode = "db_query" if len(sys.argv) == 2: query_mode = "text_query" from query import Query from memory_stream import M...
{ "context_start_lineno": 0, "file": "tactical_plannig.py", "groundtruth_start_lineno": 39, "repository": "tmori-generative-agents-81cabfd", "right_context_start_lineno": 40, "task_id": "project_cc_python/8948" }
{ "list": [ { "filename": "plan.py", "retrieved_chunk": " self.data.loc[self.data[\"PlanID\"] == plan_id, \"ResultID\"] = memory_id\n def save_to_json(self, file_path):\n json_data = dict()\n json_data[\"DetailedStrategy\"] = self.detailed_strategy\n json_data[\"Plan\"] ...
get_prompt(document_id=document_id, purpose=purpose, perspectives=perspectives)
{ "list": [ { "filename": "badger_os/examples/fonts.py", "retrieved_chunk": "# ------------------------------\n# Program setup\n# ------------------------------\n# Global variables\nstate = {\"selected_font\": 0}\nbadger_os.state_load(\"fonts\", state)\n# Create a new Badger and set it to updat...
import badger2040 import gc import badger_os # **** Put the name of your text file here ***** text_file = "/books/289-0-wind-in-the-willows-abridged.txt" # File must be on the MicroPython device gc.collect() # Global Constants WIDTH = badger2040.WIDTH HEIGHT = badger2040.HEIGHT ARROW_THICKNESS = 3 ARROW_WIDTH = 18...
text_spacing = int(34 * state["text_size"]) # Create a new Badger and set it to update FAST display = badger2040.Badger2040() display.led(128) display.set_update_speed(badger2040.UPDATE_FAST) # ------------------------------ # Render page # ------------------------------ def render_page(): row = 0 ...
{ "context_start_lineno": 0, "file": "badger_os/examples/ebook.py", "groundtruth_start_lineno": 72, "repository": "pimoroni-badger2040-24d6eb6", "right_context_start_lineno": 73, "task_id": "project_cc_python/9078" }
{ "list": [ { "filename": "badger_os/examples/fonts.py", "retrieved_chunk": "changed = True\n# ------------------------------\n# Main program loop\n# ------------------------------\nwhile True:\n # Sometimes a button press or hold will keep the system\n # powered *through* HALT, so latch t...
state_load("ebook", state)
{ "list": [ { "filename": "firmware/PIMORONI_BADGER2040/lib/badger2040.py", "retrieved_chunk": "}\nWAKEUP_MASK = 0\nenable = machine.Pin(ENABLE_3V3, machine.Pin.OUT)\nenable.on()\ndef is_wireless():\n return False\ndef woken_by_rtc():\n return False # Badger 2040 does not include an RTC\ndef wo...
import machine import micropython from picographics import PicoGraphics, DISPLAY_INKY_PACK import time import wakeup import pcf85063a BUTTON_DOWN = 11 BUTTON_A = 12 BUTTON_B = 13 BUTTON_C = 14 BUTTON_UP = 15 BUTTON_USER = None # User button not available on W BUTTON_MASK = 0b11111 << 11 SYSTEM_VERY_SLOW = 0 SYSTEM...
def woken_by_button(): return wakeup.get_gpio_state() & BUTTON_MASK > 0 def pressed_to_wake(button): return wakeup.get_gpio_state() & (1 << button) > 0 def reset_pressed_to_wake(): wakeup.reset_gpio_state() def pressed_to_wake_get_once(button): global WAKEUP_MASK result = (wakeup.get_gpio_s...
{ "context_start_lineno": 0, "file": "firmware/PIMORONI_BADGER2040W/lib/badger2040.py", "groundtruth_start_lineno": 68, "repository": "pimoroni-badger2040-24d6eb6", "right_context_start_lineno": 69, "task_id": "project_cc_python/9085" }
{ "list": [ { "filename": "firmware/PIMORONI_BADGER2040/lib/badger2040.py", "retrieved_chunk": "def pressed_to_wake(button):\n return wakeup.get_gpio_state() & (1 << button) > 0\ndef reset_pressed_to_wake():\n wakeup.reset_gpio_state()\ndef pressed_to_wake_get_once(button):\n global WAKEUP_MA...
get_gpio_state() & (1 << RTC_ALARM))
{ "list": [ { "filename": "modules/iflab/ui/dream.py", "retrieved_chunk": "from .pipeline import PipelineUI, catch_handler_errors\nclass Txt2ImgUI(PipelineUI):\n def __init__(self, pipeline):\n super().__init__(pipeline)\n self.IMAGE_FOLDER = \"dream\"\n def _tune_ui(self):\n ...
import ipywidgets as widgets from .pipeline import PipelineUI, catch_handler_errors class SuperResolutionUI(PipelineUI): def __init__(self, pipeline): super().__init__(pipeline) self.IMAGE_FOLDER = "super_resolution" def _tune_ui(self): self.SERIES_BUTTON_LABEL = "Batch Stage III" ...
self.generate_series_button.description = self.SERIES_BUTTON_LABEL self.info_button.tooltip = "Upload source image and provide a prompt to generate an upscaled version" def on_display_info(self, button): pass def get_title(self): return "Super Resolution" def on_before_ge...
{ "context_start_lineno": 0, "file": "modules/iflab/ui/super_resolution.py", "groundtruth_start_lineno": 15, "repository": "GChristensen-deepfloyd_if_lab-4644b93", "right_context_start_lineno": 16, "task_id": "project_cc_python/9122" }
{ "list": [ { "filename": "modules/iflab/ui/dream.py", "retrieved_chunk": " #webbrowser.open(\"https://github.com/deep-floyd/IF#i-dream\")\n def get_title(self):\n return \"Dream\"", "score": 65.06204262634324 }, { "filename": "modules/iflab/ui/pipeline.py", ...
generate_button.description = "Stage III"
{ "list": [ { "filename": "modules/iflab/ui/pipeline.py", "retrieved_chunk": " \"pass_prompt_to_stage_III\": self.sIII_pass_prompt_check.value\n }\n return parameters\n def persist_ui_state(self):\n if self.settings.get(\"remember_ui_state\", False):\n key...
import importlib import ipywidgets as widgets from IPython.core.display_functions import clear_output from IPython.display import display from ipywidgets import HTML, VBox, Layout from ..const import VERSION from ..settings import settings from ..pipelines.inpainting import InpaintingPipeline from ..pipelines.super_r...
self.tabs.selected_index = 2 def get(self): return self.root_box def show(self): self._apply_style() display(self.root_box) @staticmethod def load(): stages_module = importlib.import_module('.'.join(__name__.split('.')[:-2]) + ".pipelines.stages") if_s...
{ "context_start_lineno": 0, "file": "modules/iflab/ui/main.py", "groundtruth_start_lineno": 105, "repository": "GChristensen-deepfloyd_if_lab-4644b93", "right_context_start_lineno": 106, "task_id": "project_cc_python/9114" }
{ "list": [ { "filename": "modules/iflab/ui/pipeline.py", "retrieved_chunk": " parameters = self.load_ui_state(self.pipeline.__class__.__name__)\n if parameters:\n self.set_ui_parameters(parameters)\n def get_result_pnginfo(self, seed, stage):\n parameter...
set_support_image(image, parameters)
{ "list": [ { "filename": "modules/iflab/pipelines/utils.py", "retrieved_chunk": "import torch\ndef get_total_gb_vram():\n if torch.cuda.is_available():\n return round(torch.cuda.get_device_properties(0).total_memory / 1024 ** 3)\n else:\n return 0\ndef get_default_settings():\n ...
import torch import os from pathlib import Path from .const import SEQ_LOAD_OFF, SEQ_LOAD_MERGE, SEQ_LOAD_SEPARATE from .settings import settings def get_total_gb_vram(): if torch.cuda.is_available(): return round(torch.cuda.get_device_properties(0).total_memory / 1024 ** 3) else: return 8 ...
elif total_gb_vram >= 12: settings.set("sequential_load", SEQ_LOAD_MERGE) else: settings.set("sequential_load", SEQ_LOAD_SEPARATE) settings.set("stageI_model", "IF-I-L-v1.0") settings.set("stageII_model", "IF-II-L-v1.0") settings.save() retu...
{ "context_start_lineno": 0, "file": "modules/iflab/init.py", "groundtruth_start_lineno": 23, "repository": "GChristensen-deepfloyd_if_lab-4644b93", "right_context_start_lineno": 24, "task_id": "project_cc_python/9104" }
{ "list": [ { "filename": "modules/iflab/pipelines/utils.py", "retrieved_chunk": " result = {\"alternate_load\": False}\n elif total_gb_vram >= 12:\n result = {\n \"alternate_load\": True\n }\n else:\n result = {\n \"stageI_model\": \"IF-I-L-v1.0...
set("sequential_load", SEQ_LOAD_OFF)
{ "list": [ { "filename": "modules/iflab/ui/pipeline.py", "retrieved_chunk": " self.info_button = widgets.Button(description='ℹ️', tooltip='', layout=Layout(width='40px'),\n style={\"button_color\": \"#212121\"})\n self.info_button.on_click(self.o...
import ipywidgets as widgets from .pipeline import PipelineUI, catch_handler_errors class SuperResolutionUI(PipelineUI): def __init__(self, pipeline): super().__init__(pipeline) self.IMAGE_FOLDER = "super_resolution" def _tune_ui(self): self.SERIES_BUTTON_LABEL = "Batch Stage III" ...
def on_display_info(self, button): pass def get_title(self): return "Super Resolution" def on_before_generation(self): self.upscaling = True self.upscaling_stage = "III" super().on_before_generation() def process_stageI_result(self, result): if self.u...
{ "context_start_lineno": 0, "file": "modules/iflab/ui/super_resolution.py", "groundtruth_start_lineno": 17, "repository": "GChristensen-deepfloyd_if_lab-4644b93", "right_context_start_lineno": 18, "task_id": "project_cc_python/9124" }
{ "list": [ { "filename": "modules/iflab/ui/pipeline.py", "retrieved_chunk": " self.upscale_results_label.layout.display = \"none\"\n def save_result(self, image, time, seed, stage):\n file_name = self._get_file_name(time, seed, stage)\n file_dir = os.path.dirname(file_name)\n ...
info_button.tooltip = "Upload source image and provide a prompt to generate an upscaled version"
{ "list": [ { "filename": "modules/iflab/ui/super_resolution.py", "retrieved_chunk": " self.clear_results_button.layout.display = \"none\"\n self.generate_button.description = \"Stage III\"\n self.generate_series_button.description = self.SERIES_BUTTON_LABEL\n self.info_but...
from .pipeline import PipelineUI class Img2ImgUI(PipelineUI): def __init__(self, pipeline): super().__init__(pipeline) self.IMAGE_FOLDER = "style_transfer" def _tune_ui(self): self.info_button.tooltip = "Upload source image and provide a style prompt to produce image of a different st...
super().generate_series(**kwargs) else: print("Please provide a style prompt")
{ "context_start_lineno": 0, "file": "modules/iflab/ui/style_transfer.py", "groundtruth_start_lineno": 19, "repository": "GChristensen-deepfloyd_if_lab-4644b93", "right_context_start_lineno": 20, "task_id": "project_cc_python/9117" }
{ "list": [ { "filename": "modules/iflab/ui/super_resolution.py", "retrieved_chunk": " self.upscaling_stage = \"III\"\n super().on_before_generation()\n def process_stageI_result(self, result):\n if self.upscaling_progress_event:\n self.upscaling_progress_event.set()...
pipeline.style_prompt:
{ "list": [ { "filename": "modules/iflab/ui/super_resolution.py", "retrieved_chunk": " self.clear_results_button.layout.display = \"none\"\n self.generate_button.description = \"Stage III\"\n self.generate_series_button.description = self.SERIES_BUTTON_LABEL\n self.info_but...
from .pipeline import PipelineUI class Img2ImgUI(PipelineUI): def __init__(self, pipeline): super().__init__(pipeline) self.IMAGE_FOLDER = "style_transfer" def _tune_ui(self): self.info_button.tooltip = "Upload source image and provide a style prompt to produce image of a different st...
else: print("Please provide a style prompt")
{ "context_start_lineno": 0, "file": "modules/iflab/ui/style_transfer.py", "groundtruth_start_lineno": 20, "repository": "GChristensen-deepfloyd_if_lab-4644b93", "right_context_start_lineno": 21, "task_id": "project_cc_python/9118" }
{ "list": [ { "filename": "modules/iflab/ui/super_resolution.py", "retrieved_chunk": " self.upscaling_stage = \"III\"\n super().on_before_generation()\n def process_stageI_result(self, result):\n if self.upscaling_progress_event:\n self.upscaling_progress_event.set()...
generate_series(**kwargs)
{ "list": [ { "filename": "modules/iflab/ui/pipeline.py", "retrieved_chunk": " def clear_results(self, button):\n self.resultsI = {}\n self.result_box.children = []\n self.result_box.layout.display = \"none\"\n self.result_button_box.layout.display = \"none\"\n se...
import ipywidgets as widgets from .pipeline import PipelineUI, catch_handler_errors class SuperResolutionUI(PipelineUI): def __init__(self, pipeline): super().__init__(pipeline) self.IMAGE_FOLDER = "super_resolution" def _tune_ui(self): self.SERIES_BUTTON_LABEL = "Batch Stage III" ...
self.info_button.tooltip = "Upload source image and provide a prompt to generate an upscaled version" def on_display_info(self, button): pass def get_title(self): return "Super Resolution" def on_before_generation(self): self.upscaling = True self.upscaling_stage ...
{ "context_start_lineno": 0, "file": "modules/iflab/ui/super_resolution.py", "groundtruth_start_lineno": 16, "repository": "GChristensen-deepfloyd_if_lab-4644b93", "right_context_start_lineno": 17, "task_id": "project_cc_python/9123" }
{ "list": [ { "filename": "modules/iflab/ui/dream.py", "retrieved_chunk": " #webbrowser.open(\"https://github.com/deep-floyd/IF#i-dream\")\n def get_title(self):\n return \"Dream\"", "score": 59.79800373775135 }, { "filename": "modules/iflab/ui/pipeline.py", ...
generate_series_button.description = self.SERIES_BUTTON_LABEL
{ "list": [ { "filename": "modules/iflab/ui/pnginfo.py", "retrieved_chunk": "import weakref\nimport ipywidgets as widgets\nfrom ipywidgets import HBox, Layout\nfrom .pipeline import PipelineUI, catch_handler_errors\nclass PNGInfoUI(PipelineUI):\n def __init__(self, uis, tabs):\n super().__in...
import importlib import ipywidgets as widgets from IPython.core.display_functions import clear_output from IPython.display import display from ipywidgets import HTML, VBox, Layout from ..const import VERSION from ..settings import settings from ..pipelines.inpainting import InpaintingPipeline from ..pipelines.super_r...
for i in range(len(self.tabs.children)): self.tabs.set_title(i, self.uis[i].get_title()) self.title_label = widgets.Label(f"DeepFloyd IF Lab v{VERSION}", layout=Layout(display="flex", justify_content="flex-end")) if settings.get("remember_...
{ "context_start_lineno": 0, "file": "modules/iflab/ui/main.py", "groundtruth_start_lineno": 64, "repository": "GChristensen-deepfloyd_if_lab-4644b93", "right_context_start_lineno": 65, "task_id": "project_cc_python/9108" }
{ "list": [ { "filename": "modules/iflab/ui/pnginfo.py", "retrieved_chunk": " self.upload_support_img_button.layout.display = \"none\"\n self.send_to_label = widgets.Label(\"Send to:\")\n self.dream_button = widgets.Button(description='Dream')\n self.dream_button.on_click(s...
get() for ui in self.uis]
{ "list": [ { "filename": "modules/iflab/ui/pipeline.py", "retrieved_chunk": " resultI = self.resultsI[seed]\n result = self.pipeline.upscale(resultI=resultI, progress=self.update_progress)\n self.stageII_time = round(result.duration)\n self.upscale_resultsI...
import ipywidgets as widgets from .pipeline import PipelineUI, catch_handler_errors class SuperResolutionUI(PipelineUI): def __init__(self, pipeline): super().__init__(pipeline) self.IMAGE_FOLDER = "super_resolution" def _tune_ui(self): self.SERIES_BUTTON_LABEL = "Batch Stage III" ...
def set_support_image(self, image, parameters): self.support_img_view.value = self._image_to_bytes(image) self.support_img_view.layout.display = "inline-block" self.prompt_text.value = parameters.get("prompt", "") self.negative_prompt_text.value = parameters.get("negative_prompt", ...
{ "context_start_lineno": 0, "file": "modules/iflab/ui/super_resolution.py", "groundtruth_start_lineno": 37, "repository": "GChristensen-deepfloyd_if_lab-4644b93", "right_context_start_lineno": 38, "task_id": "project_cc_python/9128" }
{ "list": [ { "filename": "modules/iflab/ui/pipeline.py", "retrieved_chunk": " self.stageIII_iter_time = result.duration / self.pipeline.iterationsIII\n self.process_upscale_result(seed, result, \"III\", stage_max, image_index, total_images)\n def process_upscale_result(self, ...
status_message(f"Stages II-III: {duration}s")
{ "list": [ { "filename": "modules/iflab/ui/pipeline.py", "retrieved_chunk": " if generate_seed:\n seed = self.pipeline.generate_seed()\n result = self.pipeline.generate(seed, progress=self.update_progress)\n self.process_stageI_result(re...
import ipywidgets as widgets from .pipeline import PipelineUI, catch_handler_errors class SuperResolutionUI(PipelineUI): def __init__(self, pipeline): super().__init__(pipeline) self.IMAGE_FOLDER = "super_resolution" def _tune_ui(self): self.SERIES_BUTTON_LABEL = "Batch Stage III" ...
duration = round(result.duration) self.status_message(f"Stages II-III: {duration}s") def set_support_image(self, image, parameters): self.support_img_view.value = self._image_to_bytes(image) self.support_img_view.layout.display = "inline-block" self.prompt_text.value = par...
{ "context_start_lineno": 0, "file": "modules/iflab/ui/super_resolution.py", "groundtruth_start_lineno": 34, "repository": "GChristensen-deepfloyd_if_lab-4644b93", "right_context_start_lineno": 35, "task_id": "project_cc_python/9127" }
{ "list": [ { "filename": "modules/iflab/ui/pipeline.py", "retrieved_chunk": " def clear_results(self, button):\n self.resultsI = {}\n self.result_box.children = []\n self.result_box.layout.display = \"none\"\n self.result_button_box.layout.display = \"none\"\n se...
process_upscale_result(result.seed, result, "III")
{ "list": [ { "filename": "talkbot/neos_connector.py", "retrieved_chunk": " while not read_socket.closed and server.is_serving():\n await _ws_broadcast(get_expression())\n try:\n message = await read_socket.recv_json()\n if...
"""Message types.""" import time from typing import Any, Literal, TypedDict, TypeGuard from .constants import ComponentState class UserMessage(TypedDict): """A message from the user.""" role: Literal["user"] content: str class AssistantMessage(TypedDict): """A message from the assistant.""" ...
def is_busy(busy_time: float, timeout: float) -> bool: """Check if a component is busy.""" return time.time() - busy_time < timeout
{ "context_start_lineno": 0, "file": "talkbot/utilities/message.py", "groundtruth_start_lineno": 80, "repository": "esnya-lm-talkbot-f072b85", "right_context_start_lineno": 81, "task_id": "project_cc_python/9178" }
{ "list": [ { "filename": "talkbot/neos_connector.py", "retrieved_chunk": " logger.debug(\n \"Status Updated: %s, %s\",\n component_status,\n component_status_update_time,\n )\n ex...
BUSY else 0
{ "list": [ { "filename": "src/tools/base.py", "retrieved_chunk": " description: str = Field(..., description=\"The description of the tool\")\n func: Callable[[str], str] = Field(..., description=\"The function to execute\")\n args: Dict[str, str] = Field(default={})\n user_permission_req...
import os from dotenv import load_dotenv from agent import Agent from tools.base import AgentTool from ui.cui import CommandlineUserInterface from langchain.utilities import GoogleSearchAPIWrapper from langchain.llms import OpenAI from langchain.chat_models import ChatOpenAI # Set API Keys load_dotenv() OPENAI_API_KE...
### 4.Run agent ### agent.run()
{ "context_start_lineno": 0, "file": "src/main.py", "groundtruth_start_lineno": 57, "repository": "dory111111-Pengenuity-297d9ee", "right_context_start_lineno": 58, "task_id": "project_cc_python/9142" }
{ "list": [ { "filename": "src/tools/base.py", "retrieved_chunk": " result = self.func(**kwargs)\n except (Exception, KeyboardInterrupt) as e:\n raise AgentToolError(str(e))\n return result\n def get_tool_info(self, include_args=True) -> str:\n \"\"\"Get t...
prodedural_memory.memorize_tools([search_tool])
{ "list": [ { "filename": "talkbot/utilities/audio.py", "retrieved_chunk": " \"\"\"Open a stream.\"\"\"\n stream = get_pa().open(*args, **kwargs)\n yield stream\n stream.stop_stream()\ndef _on_sigint(*_):\n \"\"\"Handle SIGINT.\"\"\"\n if hasattr(\"_pa_local\", \"pa\"):\n _pa_...
"""Talkbot main entry point.""" import asyncio import signal from typing import Any, Callable, Coroutine from .audio_to_message import audio_to_message from .bridge import bridge from .chat_engine import chat_engine from .console import console from .message_stream import message_stream from .message_to_speak import ...
parser.dispatch()
{ "context_start_lineno": 0, "file": "talkbot/__main__.py", "groundtruth_start_lineno": 68, "repository": "esnya-lm-talkbot-f072b85", "right_context_start_lineno": 69, "task_id": "project_cc_python/9173" }
{ "list": [ { "filename": "talkbot/utilities/audio.py", "retrieved_chunk": " \"\"\"Open a stream.\"\"\"\n stream = get_pa().open(*args, **kwargs)\n yield stream\n stream.stop_stream()\ndef _on_sigint(*_):\n \"\"\"Handle SIGINT.\"\"\"\n if hasattr(\"_pa_local\", \"pa\"):\n _pa_...
set_async_default_command(run)
{ "list": [ { "filename": "talkbot/utilities/asyncargh.py", "retrieved_chunk": " setattr(wrapper, \"__wrapped__\", async_func)\n cmd_name, _ = _extract_command_meta_from_func(async_func)\n setattr(wrapper, ATTR_NAME, cmd_name)\n setattr(wrapper, \"__doc__\", async_func.__doc__)\n return...
"""Talkbot main entry point.""" import asyncio import signal from typing import Any, Callable, Coroutine from .audio_to_message import audio_to_message from .bridge import bridge from .chat_engine import chat_engine from .console import console from .message_stream import message_stream from .message_to_speak import ...
{ "context_start_lineno": 0, "file": "talkbot/__main__.py", "groundtruth_start_lineno": 69, "repository": "esnya-lm-talkbot-f072b85", "right_context_start_lineno": 70, "task_id": "project_cc_python/9174" }
{ "list": [ { "filename": "talkbot/utilities/audio.py", "retrieved_chunk": " \"\"\"Open a stream.\"\"\"\n stream = get_pa().open(*args, **kwargs)\n yield stream\n stream.stop_stream()\ndef _on_sigint(*_):\n \"\"\"Handle SIGINT.\"\"\"\n if hasattr(\"_pa_local\", \"pa\"):\n _pa_...
dispatch()
{ "list": [ { "filename": "src/cassio/vector/vector_table.py", "retrieved_chunk": " metadata: Dict[str, Any] = {},\n ttl_seconds: Optional[int] = None,\n **kwargs: Any,\n ) -> None:\n self.table.put(\n row_id=document_id,\n body_blob=document,\n ...
""" handling of key-value storage on a Cassandra table. One row per partition, serializes a multiple partition key into a string """ from warnings import warn from typing import Any, Dict, List, Optional from cassandra.cluster import Session # type: ignore from cassio.table.tables import ElasticCassandraTable cla...
return None def get(self, key_dict) -> Optional[str]: entry = self.table.get(**key_dict) if entry is None: return None else: return entry["body_blob"] def delete(self, key_dict) -> None: """Will not complain if the row does not exist.""" ...
{ "context_start_lineno": 0, "file": "src/cassio/keyvalue/k_v_cache.py", "groundtruth_start_lineno": 56, "repository": "CassioML-cassio-7953897", "right_context_start_lineno": 57, "task_id": "project_cc_python/9100" }
{ "list": [ { "filename": "src/cassio/vector/vector_table.py", "retrieved_chunk": " **kwargs,\n )\n def put_async(\n self,\n document: str,\n embedding_vector: List[float],\n document_id: Any,\n metadata: Dict[str, Any],\n ttl_seconds: int...
put(body_blob=cache_value, ttl_seconds=ttl_seconds, **key_dict)
{ "list": [ { "filename": "talkbot/utilities/socket.py", "retrieved_chunk": " _local.context = zmq.asyncio.Context()\n atexit.register(_local.context.term)\n return _local.context\ndef _on_sigint(*_):\n \"\"\"Handle SIGINT.\"\"\"\n if hasattr(_local, \"context\"):\n _loca...
"""Talkbot main entry point.""" import asyncio import signal from typing import Any, Callable, Coroutine from .audio_to_message import audio_to_message from .bridge import bridge from .chat_engine import chat_engine from .console import console from .message_stream import message_stream from .message_to_speak import ...
parser.add_async_commands([run]) parser.add_async_commands([console]) parser.add_async_commands([train]) parser.add_async_commands([prune]) parser.add_async_commands([run_bridge]) parser.set_async_default_command(run) parser.dispatch()
{ "context_start_lineno": 0, "file": "talkbot/__main__.py", "groundtruth_start_lineno": 62, "repository": "esnya-lm-talkbot-f072b85", "right_context_start_lineno": 63, "task_id": "project_cc_python/9172" }
{ "list": [ { "filename": "talkbot/utilities/socket.py", "retrieved_chunk": " \"\"\"Return a socket that sends messages to the message stream.\"\"\"\n context = get_context()\n with context.socket(zmq.PUB) as socket:\n socket.connect(config.get(\"message_stream.write\", \"\"))\n ...
add_async_commands(COMPONENTS)
{ "list": [ { "filename": "eval/post_refinement.py", "retrieved_chunk": " path.points.requires_grad = True\n points_vars.append(path.points)\n # Optimize\n points_optim = torch.optim.Adam(points_vars, lr=0.5, betas=(0.9, 0.999))\n # Adam iterations.\n ...
import argparse, os, sys, subprocess, copy, random, time, shutil, math from PIL import Image import yaml import numpy as np import torch import torch.nn as nn from tqdm import tqdm from torch.utils.data import DataLoader import torch.nn.functional as F import torchvision from einops import repeat, rearrange, reduce, p...
imgs = [] with tqdm(range(num_iter), leave=False, desc='Refine', disable=not prog_bar) as iters: for i in iters: optim.zero_grad() cp_norm_list = connect_cp_for_tensor_list(cp_tensor_list, norm=True, sidelength=w) img_render = renderer(cp_norm_list, kernel=4) ...
{ "context_start_lineno": 0, "file": "eval/refine_svg.py", "groundtruth_start_lineno": 149, "repository": "thuliu-yt16-dualvector-e5ae56e", "right_context_start_lineno": 150, "task_id": "project_cc_python/9170" }
{ "list": [ { "filename": "eval/post_refinement.py", "retrieved_chunk": " canvas_width, canvas_height, shapes, shape_groups)\n try:\n img = render(canvas_width, # width\n canvas_height, # height\n ...
OccRender(sidelength=w).cuda()
{ "list": [ { "filename": "eval/post_refinement.py", "retrieved_chunk": " path.points.requires_grad = True\n points_vars.append(path.points)\n # Optimize\n points_optim = torch.optim.Adam(points_vars, lr=0.5, betas=(0.9, 0.999))\n # Adam iterations.\n ...
import argparse, os, sys, subprocess, copy, random, time, shutil, math from PIL import Image import yaml import numpy as np import torch import torch.nn as nn from tqdm import tqdm from torch.utils.data import DataLoader import torch.nn.functional as F import torchvision from einops import repeat, rearrange, reduce, p...
list_of_loss = loss_fn(img_render, target, cp_norm_list) loss = list_of_loss['loss'] loss.backward() optim.step() for k, v in list_of_loss.items(): list_of_loss[k] = f'{v.item():.6f}' iters.set_postfix({ **list_o...
{ "context_start_lineno": 0, "file": "eval/refine_svg.py", "groundtruth_start_lineno": 159, "repository": "thuliu-yt16-dualvector-e5ae56e", "right_context_start_lineno": 160, "task_id": "project_cc_python/9171" }
{ "list": [ { "filename": "eval/post_refinement.py", "retrieved_chunk": " canvas_width, canvas_height, shapes, shape_groups)\n try:\n img = render(canvas_width, # width\n canvas_height, # height\n ...
tensor_to_image(img_render))
{ "list": [ { "filename": "eval/eval_generation_multiref.py", "retrieved_chunk": " continue\n system.write_paths_to_svg(curves_np_raw[i], raw_path)\n utils.tensor_to_image(img_rec[i, 0], img_path)\n curve_np = curves_np[i]\n d_string_list = [models.gutils.path_d_...
import argparse import os import sys sys.path.append(os.getcwd()) import time import numpy as np import random from PIL import Image import imageio import yaml, shutil import torch import torch.nn as nn from tqdm import tqdm from torch.utils.data import DataLoader from torch.optim.lr_scheduler import MultiStepLR impor...
continue
{ "context_start_lineno": 0, "file": "eval/sample_font.py", "groundtruth_start_lineno": 139, "repository": "thuliu-yt16-dualvector-e5ae56e", "right_context_start_lineno": 140, "task_id": "project_cc_python/9168" }
{ "list": [ { "filename": "eval/eval_generation_multiref.py", "retrieved_chunk": " continue\n system.write_paths_to_svg(curves_np_raw[i], raw_path)\n utils.tensor_to_image(img_rec[i, 0], img_path)\n curve_np = curves_np[i]\n d_string_list = [models.gutils.path_d_...
write_path_to_svg(cps_list, path_prefix + '_init.svg')
{ "list": [ { "filename": "models/base.py", "retrieved_chunk": " path_tensor = path_tensor.detach().cpu().numpy()\n n_paths, n_curves, n_cp = path_tensor.shape\n n_cp = n_cp // 2\n sl = 256\n canvas = svgwrite.Drawing(filename=filename, debug=True)\n canva...
import argparse, os, sys, subprocess, copy, random, time, shutil, math from PIL import Image import yaml import numpy as np import torch import torch.nn as nn from tqdm import tqdm from torch.utils.data import DataLoader import torch.nn.functional as F import torchvision from einops import repeat, rearrange, reduce, p...
path_d = ' '.join(path_d) path = canvas.path( d=path_d, fill='#000000', ) canvas.add(path) canvas.save() return canvas def simplify_path(path): new_segs = [] last_end = None accumulated_length = 0 for seg in path: if last_end is None: ...
{ "context_start_lineno": 0, "file": "eval/refine_svg.py", "groundtruth_start_lineno": 79, "repository": "thuliu-yt16-dualvector-e5ae56e", "right_context_start_lineno": 80, "task_id": "project_cc_python/9169" }
{ "list": [ { "filename": "models/base.py", "retrieved_chunk": " d=path_d, \n fill=self._colors[i%len(self._colors)],\n fill_opacity='0.3',\n )\n canvas.add(path)\n canvas.save()\n return canvas", "score": 94.407254...
gutils.path_d_from_control_points(curve_tensor, xy_flip=False))
{ "list": [ { "filename": "worker/app/worker/models/gpt_neox_7b.py", "retrieved_chunk": " ##############################\n ### INFERENCE #############\n ##############################\n def prepare_for_inference(self):\n super().prepare_for_inference()\n async def generate_str...
from typing import List from .vllm_causal import VllmCausalModel class BigCode15B(VllmCausalModel): architecture_name = "bigcode_15b" def __init__(self, config): super().__init__(config) ############################## ### INFERENCE ############# ############################## de...
async for text in stream: yield text
{ "context_start_lineno": 0, "file": "worker/app/worker/models/bigcode_15b.py", "groundtruth_start_lineno": 20, "repository": "havenhq-haven-fa692f2", "right_context_start_lineno": 21, "task_id": "project_cc_python/9014" }
{ "list": [ { "filename": "worker/app/worker/models/gpt_neox_7b.py", "retrieved_chunk": " ##############################\n ### INFERENCE #############\n ##############################\n def prepare_for_inference(self):\n super().prepare_for_inference()\n async def generate_str...
generate_stream(prompt, stop_tokens=stop_tokens, max_tokens=max_tokens, top_p=top_p, top_k=top_k, temperature=temperature)
{ "list": [ { "filename": "eval/eval_reconstruction.py", "retrieved_chunk": " n = curves.shape[0]\n curves_np_raw = curves.detach().cpu().numpy()\n curves_np = (curves_np_raw + 1) * sidelength / 2\n targets = img_rec\n for i in range(n):\n font_name = batch['font_name'][i]\n ...
import argparse import os import sys sys.path.append(os.getcwd()) import time import numpy as np import random from PIL import Image import imageio import yaml, shutil import torch import torch.nn as nn from tqdm import tqdm from torch.utils.data import DataLoader from torch.optim.lr_scheduler import MultiStepLR impor...
curve_np = curves_np[i] d_string_list = [models.gutils.path_d_from_control_points(cp, xy_flip=True) for cp in curve_np] path, d_string = refine_svg.merge_d_string(d_string_list) cps_list = refine_svg.convert_path_to_control_points(path, pruned=True) if len(cps_list) == 0: ...
{ "context_start_lineno": 0, "file": "eval/sample_font.py", "groundtruth_start_lineno": 129, "repository": "thuliu-yt16-dualvector-e5ae56e", "right_context_start_lineno": 130, "task_id": "project_cc_python/9164" }
{ "list": [ { "filename": "eval/eval_reconstruction.py", "retrieved_chunk": " raw_path = os.path.join(save_dir, f'{char_name:02d}_raw.svg')\n img_path = os.path.join(save_dir, f'{char_name:02d}_rec.png')\n if os.path.exists(svg_path) and os.path.exists(raw_path) and os.path.exists...
tensor_to_image(img_rec[i, 0], path_prefix + '_rec.png')
{ "list": [ { "filename": "worker/app/worker/models/gpt_neox_7b.py", "retrieved_chunk": " ##############################\n ### INFERENCE #############\n ##############################\n def prepare_for_inference(self):\n super().prepare_for_inference()\n async def generate_str...
from typing import List from .vllm_causal import VllmCausalModel class GPTNeoX3B(VllmCausalModel): architecture_name = "gpt_neox_3b" def __init__(self, config): super().__init__(config) ############################## ### INFERENCE ############# ############################## def...
async for text in stream: yield text
{ "context_start_lineno": 0, "file": "worker/app/worker/models/gpt_neox_3b.py", "groundtruth_start_lineno": 20, "repository": "havenhq-haven-fa692f2", "right_context_start_lineno": 21, "task_id": "project_cc_python/9018" }
{ "list": [ { "filename": "worker/app/worker/models/gpt_neox_7b.py", "retrieved_chunk": " ##############################\n ### INFERENCE #############\n ##############################\n def prepare_for_inference(self):\n super().prepare_for_inference()\n async def generate_str...
generate_stream(prompt, max_tokens=max_tokens, top_p=top_p, top_k=top_k, temperature=temperature)
{ "list": [ { "filename": "src/superbig/base.py", "retrieved_chunk": " def inject(self, injection_point: InjectionPoint, text: str):\n injected_prompt = self.prepared_prompt\n for key, section in self.prepared_prompt.items():\n if type(section) != str:\n cont...
from typing import Tuple from ..searcher import CosineSimilaritySearcher from ..source import SourceBuilder from ..base import Bucket, Collecter, Chunker, InjectionPoint, Injector, Page, PreparedPrompt, Source, Embedder, Chunk, Window from ..prepared_prompt import AlpacaPreparedPrompt, GenericPreparedPrompt from ..meta...
print("Injecting...") prompt = prepared_prompt.rebuild() return prompt
{ "context_start_lineno": 0, "file": "src/superbig/injector/generic.py", "groundtruth_start_lineno": 181, "repository": "kaiokendev-superbig-be5500b", "right_context_start_lineno": 182, "task_id": "project_cc_python/9204" }
{ "list": [ { "filename": "src/superbig/base.py", "retrieved_chunk": " ...\nclass Collecter():\n def __init__(self):\n pass\n def add(self, texts: list[Bucket]):\n pass\n def get(self, search_strings: list[str], n_results: int, bucket_key: str = '') -> dict[InjectionPoint...
view())
{ "list": [ { "filename": "src/superbig/source/source_builder.py", "retrieved_chunk": " return inferred_source\n def get_hollow_injection_points(self, prepared_prompt: PreparedPrompt) -> list[str]:\n extractor = URLExtract()\n hollow_injection_points = []\n urls = extrac...
from typing import Tuple from ..searcher import CosineSimilaritySearcher from ..source import SourceBuilder from ..base import Bucket, Collecter, Chunker, InjectionPoint, Injector, Page, PreparedPrompt, Source, Embedder, Chunk, Window from ..prepared_prompt import AlpacaPreparedPrompt, GenericPreparedPrompt from ..meta...
print('Inferring injections...') injection_points += self.add_and_infer_hollow_injection_points(hollow_injection_points) print('Loading and caching injections...') self.load_and_cache(injection_points) return prepared_prompt def choose_best_source(self, prepared_prompt:...
{ "context_start_lineno": 0, "file": "src/superbig/injector/generic.py", "groundtruth_start_lineno": 119, "repository": "kaiokendev-superbig-be5500b", "right_context_start_lineno": 120, "task_id": "project_cc_python/9201" }
{ "list": [ { "filename": "src/superbig/source/source_builder.py", "retrieved_chunk": " alphabet = string.ascii_lowercase + string.digits\n return ''.join(random.choices(alphabet, k=8))", "score": 29.700267666010628 }, { "filename": "src/superbig/base.py", "retr...
get_hollow_injection_points(prepared_prompt)
{ "list": [ { "filename": "src/superbig/source/source_builder.py", "retrieved_chunk": " return inferred_source\n def get_hollow_injection_points(self, prepared_prompt: PreparedPrompt) -> list[str]:\n extractor = URLExtract()\n hollow_injection_points = []\n urls = extrac...
from typing import Tuple from ..searcher import CosineSimilaritySearcher from ..source import SourceBuilder from ..base import Bucket, Collecter, Chunker, InjectionPoint, Injector, Page, PreparedPrompt, Source, Embedder, Chunk, Window from ..prepared_prompt import AlpacaPreparedPrompt, GenericPreparedPrompt from ..meta...
if source is not None: source_name = source.metadata.get('inferred_injection_point_name') inferred_from = source.metadata.get('inferred_from') self.inferred_source_mappings[inferred_from] = source injection_point = InjectionPoint(source_name) injectio...
{ "context_start_lineno": 0, "file": "src/superbig/injector/generic.py", "groundtruth_start_lineno": 53, "repository": "kaiokendev-superbig-be5500b", "right_context_start_lineno": 54, "task_id": "project_cc_python/9197" }
{ "list": [ { "filename": "src/superbig/source/source_builder.py", "retrieved_chunk": " alphabet = string.ascii_lowercase + string.digits\n return ''.join(random.choices(alphabet, k=8))", "score": 44.7226841130395 }, { "filename": "src/superbig/base.py", "retrie...
from_text(text, self.auto_infer_settings)
{ "list": [ { "filename": "src/superbig/metadata/builder.py", "retrieved_chunk": "from ..base import Source, Chunk\nclass MetadataChunk(Chunk):\n def add_meta(self, name: str, value: str):\n if self.meta is None:\n self.meta = {}\n self.meta[name] = value\nclass MetadataBui...
import random import string from ..base import PreparedPrompt, Source from ..source import TextSource, UrlSource from bs4 import BeautifulSoup from urlextract import URLExtract class SourceBuilder(): def __init__(self) -> None: pass def from_text(self, text: str, infer_settings: dict) -> Source | ...
inferred_source.metadata.add('descriptions', descriptions) inferred_source.metadata.add('description', string) inferred_source.metadata.add('inferred_from', string) inferred_source.name = injection_point_name elif TextSource in infer_settings and infer_settings[T...
{ "context_start_lineno": 0, "file": "src/superbig/source/source_builder.py", "groundtruth_start_lineno": 29, "repository": "kaiokendev-superbig-be5500b", "right_context_start_lineno": 30, "task_id": "project_cc_python/9212" }
{ "list": [ { "filename": "src/superbig/metadata/builder.py", "retrieved_chunk": " \"\"\"\n def enrich(self, chunk: Chunk) -> MetadataChunk:\n chunk = self.meta_id(chunk)\n return chunk\n def meta_related(self, chunk: Chunk) -> Chunk:\n \"\"\"\n Add metadata of rel...
metadata.add('inferred_injection_point_name', injection_point_name)
{ "list": [ { "filename": "src/superbig/base.py", "retrieved_chunk": " def inject(self, injection_point: InjectionPoint, text: str):\n injected_prompt = self.prepared_prompt\n for key, section in self.prepared_prompt.items():\n if type(section) != str:\n cont...
from typing import Tuple from ..searcher import CosineSimilaritySearcher from ..source import SourceBuilder from ..base import Bucket, Collecter, Chunker, InjectionPoint, Injector, Page, PreparedPrompt, Source, Embedder, Chunk, Window from ..prepared_prompt import AlpacaPreparedPrompt, GenericPreparedPrompt from ..meta...
return prepared_prompt def get_inferred_prompt(self, text: str) -> PreparedPrompt: if(text.find('### Instruction') != 1): return AlpacaPreparedPrompt() else: return GenericPreparedPrompt() def add_and_infer_hollow_injection_points(self, hollow_i...
{ "context_start_lineno": 0, "file": "src/superbig/injector/generic.py", "groundtruth_start_lineno": 29, "repository": "kaiokendev-superbig-be5500b", "right_context_start_lineno": 30, "task_id": "project_cc_python/9195" }
{ "list": [ { "filename": "src/superbig/base.py", "retrieved_chunk": " ...\nclass Collecter():\n def __init__(self):\n pass\n def add(self, texts: list[Bucket]):\n pass\n def get(self, search_strings: list[str], n_results: int, bucket_key: str = '') -> dict[InjectionPoint...
from_prompt(text)
{ "list": [ { "filename": "src/superbig/source/text_source.py", "retrieved_chunk": "import requests\nfrom ..base import Source\nclass TextSource(Source):\n def __init__(self, text=''):\n super().__init__()\n if len(text) > 1:\n self.set(text)\n def get(self) -> str:\n ...
import requests from ..base import Source from lxml.html.clean import Cleaner import unicodedata import hashlib class UrlSource(Source): def __init__(self, url=''): super().__init__() if len(url) > 1: self.set(url) def get(self) -> str: data = '' if...
else: print("Couldn't fetch resource") print(response) self.contents = data return super().get() def set(self, url: str): self.url = url super().set() def sanitize(self, dirty_html): cleaner = Cleaner(pag...
{ "context_start_lineno": 0, "file": "src/superbig/source/url_source.py", "groundtruth_start_lineno": 24, "repository": "kaiokendev-superbig-be5500b", "right_context_start_lineno": 25, "task_id": "project_cc_python/9208" }
{ "list": [ { "filename": "src/superbig/source/text_source.py", "retrieved_chunk": " self.contents = self.text\n return super().get()\n def set(self, text: str):\n self.text = text\n super().set()", "score": 39.097348799410334 }, { "filename": "src/su...
invalidate(hash)
{ "list": [ { "filename": "src/superbig/source/source_selector.py", "retrieved_chunk": "from ..base import Embedder, Source\nclass SourceSelector():\n def __init__(self, embedder: Embedder) -> None:\n self.embedder = embedder\n def find_best_source(self, sources: list[Source], input: str)...
from typing import Tuple from ..searcher import CosineSimilaritySearcher from ..source import SourceBuilder from ..base import Bucket, Collecter, Chunker, InjectionPoint, Injector, Page, PreparedPrompt, Source, Embedder, Chunk, Window from ..prepared_prompt import AlpacaPreparedPrompt, GenericPreparedPrompt from ..meta...
results = [list(self.sources.items())[result.result] for result in results] return results def parse_injection_levels(self, string: str) -> Tuple[bool, list[int]]: parts = string.split(':') is_expansion = False if "+" in parts[1]: is_expansion = Tru...
{ "context_start_lineno": 0, "file": "src/superbig/injector/generic.py", "groundtruth_start_lineno": 129, "repository": "kaiokendev-superbig-be5500b", "right_context_start_lineno": 130, "task_id": "project_cc_python/9202" }
{ "list": [ { "filename": "src/superbig/source/source_selector.py", "retrieved_chunk": "from ..base import Embedder, Source\nclass SourceSelector():\n def __init__(self, embedder: Embedder) -> None:\n self.embedder = embedder\n def find_best_source(self, sources: list[Source], input: str)...
search(search_string_embeddings, source_description_embeddings)
{ "list": [ { "filename": "src/superbig/source/text_source.py", "retrieved_chunk": "import requests\nfrom ..base import Source\nclass TextSource(Source):\n def __init__(self, text=''):\n super().__init__()\n if len(text) > 1:\n self.set(text)\n def get(self) -> str:\n ...
import requests from ..base import Source from lxml.html.clean import Cleaner import unicodedata import hashlib class UrlSource(Source): def __init__(self, url=''): super().__init__() if len(url) > 1: self.set(url) def get(self) -> str: data = '' if...
self.invalidate(hash) else: print("Couldn't fetch resource") print(response) self.contents = data return super().get() def set(self, url: str): self.url = url super().set() def sanitize(self, dirt...
{ "context_start_lineno": 0, "file": "src/superbig/source/url_source.py", "groundtruth_start_lineno": 23, "repository": "kaiokendev-superbig-be5500b", "right_context_start_lineno": 24, "task_id": "project_cc_python/9207" }
{ "list": [ { "filename": "src/superbig/source/text_source.py", "retrieved_chunk": " self.contents = self.text\n return super().get()\n def set(self, text: str):\n self.text = text\n super().set()", "score": 42.05377997321526 }, { "filename": "src/sup...
cache_key != hash:
{ "list": [ { "filename": "src/superbig/injector/generic.py", "retrieved_chunk": " return results\n def parse_injection_levels(self, string: str) -> Tuple[bool, list[int]]:\n parts = string.split(':')\n is_expansion = False\n if \"+\" in parts[1]:\n is_expansi...
import random import string from ..base import PreparedPrompt, Source from ..source import TextSource, UrlSource from bs4 import BeautifulSoup from urlextract import URLExtract class SourceBuilder(): def __init__(self) -> None: pass def from_text(self, text: str, infer_settings: dict) -> Source | ...
metas = soup.find_all('meta') descriptions = [meta.attrs['content'] for meta in metas if 'name' in meta.attrs and meta.attrs['name'] == 'description'] # Todo - page title, index page by title semantic search by page name # titles = [meta.attrs['content'] for meta in meta...
{ "context_start_lineno": 0, "file": "src/superbig/source/source_builder.py", "groundtruth_start_lineno": 20, "repository": "kaiokendev-superbig-be5500b", "right_context_start_lineno": 21, "task_id": "project_cc_python/9211" }
{ "list": [ { "filename": "src/superbig/injector/generic.py", "retrieved_chunk": " previous_relevant_context = search_strings\n search_results_page = Page(additional_information)\n is_expansion = False\n collected_chunks: list[Chunk] = []\n if isinstance(injection_le...
get(), features="html.parser")
{ "list": [ { "filename": "src/superbig/metadata/builder.py", "retrieved_chunk": " \"\"\"\n Add metadata of related chunks\n \"\"\"\n chunk.metadatas['id'] = chunk.id\n return chunk\n def meta_content_type(self, chunk: Chunk) -> Chunk:\n \"\"\"\n Add...
from typing import Tuple from ..searcher import CosineSimilaritySearcher from ..source import SourceBuilder from ..base import Bucket, Collecter, Chunker, InjectionPoint, Injector, Page, PreparedPrompt, Source, Embedder, Chunk, Window from ..prepared_prompt import AlpacaPreparedPrompt, GenericPreparedPrompt from ..meta...
ids.append(chunk.id) embeddings.append(chunk.embeddings) metadatas.append(chunk.metadatas) documents.append(chunk.text) bucket = Bucket(injection_point.real_name, chunks) bucket.ids = ids bucket.embeddings = embeddings bucket....
{ "context_start_lineno": 0, "file": "src/superbig/injector/generic.py", "groundtruth_start_lineno": 98, "repository": "kaiokendev-superbig-be5500b", "right_context_start_lineno": 99, "task_id": "project_cc_python/9198" }
{ "list": [ { "filename": "src/superbig/metadata/builder.py", "retrieved_chunk": " \"\"\"\n Add metadata of related chunks\n \"\"\"\n chunk.metadatas['id'] = chunk.id\n return chunk\n def meta_content_type(self, chunk: Chunk) -> Chunk:\n \"\"\"\n Add...
enrich(chunk)
{ "list": [ { "filename": "tests/digital_wiper/test_digital_wiper_voltage_out.py", "retrieved_chunk": " digital_wiper.voltage_in = 0\n for voltage in np.linspace(-5, 5, num=13, endpoint=True):\n digital_wiper.voltage_out = voltage\n s...
""" Example of MCP4231 usage """ from BDPotentiometer.mcp4xxx import MCP4231 # Create potentiometer with total resistance 10 kOhm my_pot = MCP4231(r_ab=10e3, device=0) # Label the two available channels with meaningful names my_pot.set_channel_label(0, "V_CTRL") my_pot.set_channel_label(1, "AMPL") # Set current lim...
# OR my_pot.set_r_wa("AMPL", 9e3) # You can also set pot's winder position to exact value my_pot.set_value("AMPL", 64) print(f"Winder position for AMPL channel is {my_pot.get_value('AMPL')}") print(f"Winder position for all channels: {my_pot.value}")
{ "context_start_lineno": 0, "file": "examples/mcp4231.py", "groundtruth_start_lineno": 33, "repository": "bond-anton-BDPotentiometer-872a7e2", "right_context_start_lineno": 34, "task_id": "project_cc_python/9187" }
{ "list": [ { "filename": "tests/digital_wiper/test_digital_wiper_voltage_out.py", "retrieved_chunk": " for voltage in [None, \"100.2\"]:\n with self.assertRaises(TypeError):\n digital_wiper.voltage_out = voltage\nif __name__ == \"__main__\":\n ...
set_r_wb("AMPL", 1e3)
{ "list": [ { "filename": "src/BDPotentiometer/potentiometer.py", "retrieved_chunk": " │ d │\n └───┘\n │\n ─┴─ GND\n R_lim is current limiting resistor, and R_load is resistive load.\n Parameters `r_lim` and `r_load` can be set using...
""" Example of MCP4231 usage """ from BDPotentiometer.mcp4xxx import MCP4231 # Create potentiometer with total resistance 10 kOhm my_pot = MCP4231(r_ab=10e3, device=0) # Label the two available channels with meaningful names my_pot.set_channel_label(0, "V_CTRL") my_pot.set_channel_label(1, "AMPL") # Set current lim...
print(f"Winder position for AMPL channel is {my_pot.get_value('AMPL')}") print(f"Winder position for all channels: {my_pot.value}")
{ "context_start_lineno": 0, "file": "examples/mcp4231.py", "groundtruth_start_lineno": 38, "repository": "bond-anton-BDPotentiometer-872a7e2", "right_context_start_lineno": 39, "task_id": "project_cc_python/9189" }
{ "list": [ { "filename": "src/BDPotentiometer/potentiometer.py", "retrieved_chunk": " using function `voltage_out_to_wiper_position`.\n \"\"\"\n # pylint: disable=too-many-instance-attributes\n def __init__(\n self,\n r_ab: float,\n r_w: float = 0,\n rheostat: ...
set_value("AMPL", 64)
{ "list": [ { "filename": "src/BDPotentiometer/digital_potentiometer.py", "retrieved_chunk": " raise ValueError(\n f\"A tuple or list of length {self.channels_num} is expected.\"\n )\n for channel, wiper in self.channels.items():\n wiper.r_lim = r...
""" Example of MCP4231 usage """ from BDPotentiometer.mcp4xxx import MCP4231 # Create potentiometer with total resistance 10 kOhm my_pot = MCP4231(r_ab=10e3, device=0) # Label the two available channels with meaningful names my_pot.set_channel_label(0, "V_CTRL") my_pot.set_channel_label(1, "AMPL") # Set current lim...
my_pot.voltage_in = (5.0, 0.0) print(f"Input voltage: {my_pot.voltage_in}") # All Done! Now you can control the pot my_pot.set_voltage_out("V_CTRL", 3.3) my_pot.voltage_out = (3.7, 0) print(f"Output voltage: {my_pot.voltage_out}") # You can also control the resistance my_pot.set_r_wb("AMPL", 1e3) # OR my_pot.set_r_w...
{ "context_start_lineno": 0, "file": "examples/mcp4231.py", "groundtruth_start_lineno": 23, "repository": "bond-anton-BDPotentiometer-872a7e2", "right_context_start_lineno": 24, "task_id": "project_cc_python/9185" }
{ "list": [ { "filename": "tests/potentiometer/test_potentiometer_fixed_resistors.py", "retrieved_chunk": " with self.assertRaises(TypeError):\n self.pot.r_lim = r_lim\n def test_r_load(self) -> None:\n \"\"\"\n Test r_load property.\n For unlo...
set_voltage_in("V_CTRL", 5.0)
{ "list": [ { "filename": "src/BDPotentiometer/potentiometer.py", "retrieved_chunk": " │ d │\n └───┘\n │\n ─┴─ GND\n R_lim is current limiting resistor, and R_load is resistive load.\n Parameters `r_lim` and `r_load` can be set using...
""" Example of MCP4231 usage """ from BDPotentiometer.mcp4xxx import MCP4231 # Create potentiometer with total resistance 10 kOhm my_pot = MCP4231(r_ab=10e3, device=0) # Label the two available channels with meaningful names my_pot.set_channel_label(0, "V_CTRL") my_pot.set_channel_label(1, "AMPL") # Set current lim...
print(f"Winder position for all channels: {my_pot.value}")
{ "context_start_lineno": 0, "file": "examples/mcp4231.py", "groundtruth_start_lineno": 39, "repository": "bond-anton-BDPotentiometer-872a7e2", "right_context_start_lineno": 40, "task_id": "project_cc_python/9190" }
{ "list": [ { "filename": "src/BDPotentiometer/potentiometer.py", "retrieved_chunk": " using function `voltage_out_to_wiper_position`.\n \"\"\"\n # pylint: disable=too-many-instance-attributes\n def __init__(\n self,\n r_ab: float,\n r_w: float = 0,\n rheostat: ...
get_value('AMPL')}")
{ "list": [ { "filename": "src/BDPotentiometer/digital_potentiometer.py", "retrieved_chunk": " channel_number = self._get_channel_number_by_label_or_id(channel)\n if channel_number is None:\n raise ValueError(f\"Channel {channel} not found.\")\n self.channels[channel_nu...
""" Example of MCP4231 usage """ from BDPotentiometer.mcp4xxx import MCP4231 # Create potentiometer with total resistance 10 kOhm my_pot = MCP4231(r_ab=10e3, device=0) # Label the two available channels with meaningful names my_pot.set_channel_label(0, "V_CTRL") my_pot.set_channel_label(1, "AMPL") # Set current lim...
my_pot.r_load = (100e3, 1e3) print(f"Load resistors: {my_pot.r_load}") # Set input voltage my_pot.set_voltage_in("V_CTRL", 5.0) my_pot.voltage_in = (5.0, 0.0) print(f"Input voltage: {my_pot.voltage_in}") # All Done! Now you can control the pot my_pot.set_voltage_out("V_CTRL", 3.3) my_pot.voltage_out = (3.7, 0) print...
{ "context_start_lineno": 0, "file": "examples/mcp4231.py", "groundtruth_start_lineno": 18, "repository": "bond-anton-BDPotentiometer-872a7e2", "right_context_start_lineno": 19, "task_id": "project_cc_python/9184" }
{ "list": [ { "filename": "src/BDPotentiometer/digital_potentiometer.py", "retrieved_chunk": " channel_number = self._get_channel_number_by_label_or_id(channel)\n if channel_number is None:\n raise ValueError(f\"Channel {channel} not found.\")\n return self.channels[cha...
set_r_load("V_CTRL", 50e3)
{ "list": [ { "filename": "src/BDPotentiometer/digital_potentiometer.py", "retrieved_chunk": " \"\"\"\n Method to set the value for a given channel.\n :param channel: Channel number or label (int | str).\n :param value: Wiper position value requested (int).\n :return...
""" Example of MCP4231 usage """ from BDPotentiometer.mcp4xxx import MCP4231 # Create potentiometer with total resistance 10 kOhm my_pot = MCP4231(r_ab=10e3, device=0) # Label the two available channels with meaningful names my_pot.set_channel_label(0, "V_CTRL") my_pot.set_channel_label(1, "AMPL") # Set current lim...
{ "context_start_lineno": 0, "file": "examples/mcp4231.py", "groundtruth_start_lineno": 40, "repository": "bond-anton-BDPotentiometer-872a7e2", "right_context_start_lineno": 41, "task_id": "project_cc_python/9191" }
{ "list": [ { "filename": "src/BDPotentiometer/potentiometer.py", "retrieved_chunk": " using function `voltage_out_to_wiper_position`.\n \"\"\"\n # pylint: disable=too-many-instance-attributes\n def __init__(\n self,\n r_ab: float,\n r_w: float = 0,\n rheostat: ...
value}")
{ "list": [ { "filename": "symlogos/modal_rules.py", "retrieved_chunk": " def is_applicable(self) -> bool:\n return self.signed_formula.sign == \"T\" and isinstance(self.signed_formula.formula, Possibility)\nclass ModalDiamondFRule(TableauRule):\n def __init__(self, signed_formula: Signed...
from __future__ import annotations from typing import Optional from symlogos.first_order_rules import AlphaRule, BetaRule, DeltaRule, GammaRule from symlogos.modal_operators import Necessity, Possibility from symlogos.proposition import Proposition from symlogos.tableau_node import TableauNode from .signed_formula imp...
def _handle_modal_operators(self, signed_formula): formula = signed_formula.formula if isinstance(formula, Necessity): rule = ModalBoxTRule(signed_formula) if signed_formula.sign == "T" else ModalBoxFRule(signed_formula) else: # isinstance(formula, Possibility) rul...
{ "context_start_lineno": 0, "file": "symlogos/tableau_prover.py", "groundtruth_start_lineno": 76, "repository": "gnbonney-SymLogos-08a26af", "right_context_start_lineno": 77, "task_id": "project_cc_python/9231" }
{ "list": [ { "filename": "symlogos/modal_rules.py", "retrieved_chunk": " result = [new_signed_formula]\n print(f\"{self.__class__.__name__}: Result: {result}\")\n return result\n def is_applicable(self) -> bool:\n return self.signed_formula.sign == \"F\" and isinstance(...
apply(node)]
{ "list": [ { "filename": "src/BDPotentiometer/digital_wiper.py", "retrieved_chunk": " if isinstance(spi, SPI):\n self.__spi = spi\n super().__init__(\n potentiometer=potentiometer,\n max_value=max_value,\n parameters_locked=parameters_locked,\...
""" MCP4XXX series SPI device base class """ from typing import Union from gpiozero import SPI, SPIDevice from BDPotentiometer import SpiDigitalWiper, Potentiometer resistance_list: tuple[float, ...] = (5e3, 10e3, 50e3, 100e3) def _coerce_max_value(max_value: int) -> int: if max_value not in (128, 256): ...
_check_write_response(data) return value raise ConnectionError("SPI interface not set") def _read_value(self): if isinstance(self.spi, SPI): data = self.spi.transfer([_R_CMD | _CH[self.channel], 0]) _check_read_response(data) return data[...
{ "context_start_lineno": 0, "file": "src/BDPotentiometer/mcp4xxx/mcp4xxx.py", "groundtruth_start_lineno": 131, "repository": "bond-anton-BDPotentiometer-872a7e2", "right_context_start_lineno": 132, "task_id": "project_cc_python/9181" }
{ "list": [ { "filename": "src/BDPotentiometer/digital_wiper.py", "retrieved_chunk": " Get SPI interface\n :return: SPI interface (gpiozero.SPI)\n \"\"\"\n return self.__spi\n @spi.setter\n def spi(self, spi: Union[SPI, None]) -> None:\n if isinstance(spi, SPI)...
channel], value])
{ "list": [ { "filename": "tests/digital_wiper/test_digital_wiper_voltage_out.py", "retrieved_chunk": " digital_wiper.voltage_in = 0\n for voltage in np.linspace(-5, 5, num=13, endpoint=True):\n digital_wiper.voltage_out = voltage\n s...
""" Example of MCP4231 usage """ from BDPotentiometer.mcp4xxx import MCP4231 # Create potentiometer with total resistance 10 kOhm my_pot = MCP4231(r_ab=10e3, device=0) # Label the two available channels with meaningful names my_pot.set_channel_label(0, "V_CTRL") my_pot.set_channel_label(1, "AMPL") # Set current lim...
my_pot.voltage_out = (3.7, 0) print(f"Output voltage: {my_pot.voltage_out}") # You can also control the resistance my_pot.set_r_wb("AMPL", 1e3) # OR my_pot.set_r_wa("AMPL", 9e3) # You can also set pot's winder position to exact value my_pot.set_value("AMPL", 64) print(f"Winder position for AMPL channel is {my_pot.ge...
{ "context_start_lineno": 0, "file": "examples/mcp4231.py", "groundtruth_start_lineno": 28, "repository": "bond-anton-BDPotentiometer-872a7e2", "right_context_start_lineno": 29, "task_id": "project_cc_python/9186" }
{ "list": [ { "filename": "src/BDPotentiometer/digital_potentiometer.py", "retrieved_chunk": " def get_voltage_in(self, channel: Union[int, str] = 0) -> float:\n \"\"\"\n Get input voltage for a given channel number.\n :param channel: Channel number (int).\n :return: Inp...
set_voltage_out("V_CTRL", 3.3)
{ "list": [ { "filename": "pydantic_numpy/helper/validation.py", "retrieved_chunk": " dimensions: Optional[int], target_data_type: npt.DTypeLike, strict_data_typing: bool\n) -> Callable[[npt.NDArray], npt.NDArray]:\n \"\"\"\n Creates a validator that ensures the numpy array has the defined di...
import tempfile from pathlib import Path import numpy as np import pytest from hypothesis.extra.numpy import arrays from pydantic_numpy.model import NumpyModel from pydantic_numpy.model.np_model import model_agnostic_load from pydantic_numpy.typing import NpNDArray TEST_MODEL_OBJECT_ID = "test" OTHER_TEST_MODEL_OBJE...
model_b.dump(tmp_dir_path, OTHER_TEST_MODEL_OBJECT_ID) models = [model_a, model_b] assert model_a == model_agnostic_load(tmp_dir_path, TEST_MODEL_OBJECT_ID, models=models) assert model_b == model_agnostic_load(tmp_dir_path, OTHER_TEST_MODEL_OBJECT_ID, models=models)
{ "context_start_lineno": 0, "file": "tests/test_np_model.py", "groundtruth_start_lineno": 90, "repository": "caniko-pydantic-numpy-abcfd59", "right_context_start_lineno": 91, "task_id": "project_cc_python/9272" }
{ "list": [ { "filename": "pydantic_numpy/helper/validation.py", "retrieved_chunk": " during validation. Float to integer is rounded (np.round) followed by an astype with target data type.\n strict_data_typing: bool\n Default False; if True, the incoming array must its dtype match the...
dump(tmp_dir_path, TEST_MODEL_OBJECT_ID)
{ "list": [ { "filename": "src/BDPotentiometer/potentiometer.py", "retrieved_chunk": " │ d │\n └───┘\n │\n ─┴─ GND\n R_lim is current limiting resistor, and R_load is resistive load.\n Parameters `r_lim` and `r_load` can be set using...
""" Example of MCP4231 usage """ from BDPotentiometer.mcp4xxx import MCP4231 # Create potentiometer with total resistance 10 kOhm my_pot = MCP4231(r_ab=10e3, device=0) # Label the two available channels with meaningful names my_pot.set_channel_label(0, "V_CTRL") my_pot.set_channel_label(1, "AMPL") # Set current lim...
# You can also set pot's winder position to exact value my_pot.set_value("AMPL", 64) print(f"Winder position for AMPL channel is {my_pot.get_value('AMPL')}") print(f"Winder position for all channels: {my_pot.value}")
{ "context_start_lineno": 0, "file": "examples/mcp4231.py", "groundtruth_start_lineno": 35, "repository": "bond-anton-BDPotentiometer-872a7e2", "right_context_start_lineno": 36, "task_id": "project_cc_python/9188" }
{ "list": [ { "filename": "src/BDPotentiometer/potentiometer.py", "retrieved_chunk": " using function `voltage_out_to_wiper_position`.\n \"\"\"\n # pylint: disable=too-many-instance-attributes\n def __init__(\n self,\n r_ab: float,\n r_w: float = 0,\n rheostat: ...
set_r_wa("AMPL", 9e3)
{ "list": [ { "filename": "train_trades.py", "retrieved_chunk": " loss = utils.trades.trades_loss(model=model,\n x_natural=inputs,\n y=targets,\n optimizer=optimizer,\n step_size=adv_configs[...
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torch.optim as optim def squared_l2_norm(x): flattened = x.view(x.unsqueeze(0).shape[0], -1) return (flattened ** 2).sum(1) def l2_norm(x): return squared_l2_norm(x).sqrt() def trades_loss(mod...
model.eval() batch_size = len(x_natural) # generate adversarial example x_adv = x_natural.detach() + 0.001 * torch.randn(x_natural.shape).cuda().detach() if distance == 'l_inf': for _ in range(perturb_steps): x_adv.requires_grad_() with torch.enable_grad(): ...
{ "context_start_lineno": 0, "file": "utils/trades.py", "groundtruth_start_lineno": 26, "repository": "jfc43-stratified-adv-rej-bfdc043", "right_context_start_lineno": 27, "task_id": "project_cc_python/9268" }
{ "list": [ { "filename": "train_trades.py", "retrieved_chunk": " if scheduler is not None:\n scheduler.step()\n if (b+1) % print_freq == 0:\n logger.info(\"Progress: {:d}/{:d}, adv_loss: {:.2f}\".format(b+1,\n ...
KLDivLoss(size_average=False)
{ "list": [ { "filename": "slonogram/handling/handler.py", "retrieved_chunk": " fn: AnyHandlerFn[T],\n observer: bool,\n filter_: Optional[FilterFn[T]],\n middleware: Optional[MiddlewareFn[T]],\n ) -> None:\n self.filter_ = filter_\n self.middleware = middl...
from __future__ import annotations from typing import ( TYPE_CHECKING, Optional, TypeVar, TypeAlias, Callable, ) from ..types.filter import FilterFn from ..types.middleware import MiddlewareFn from ..types.event_flags import MessageFlags from ..types.handler_fn import AnyHandlerFn from ..handling...
self._set._sent_message_handlers.append(handler) if MessageFlags.EDITED in subtypes: self._set._edited_message_handlers.append(handler) return handler return inner def __call__( self, subtypes: MessageFlags, filter_: _OptFil...
{ "context_start_lineno": 0, "file": "slonogram/dispatching/_registrants.py", "groundtruth_start_lineno": 42, "repository": "slonogram-slonogram-9f86552", "right_context_start_lineno": 43, "task_id": "project_cc_python/9223" }
{ "list": [ { "filename": "slonogram/handling/handler.py", "retrieved_chunk": " def __repr__(self) -> str:\n obs_flag = \":observer\" if self.observer else \"\"\n return f\"<Handler{obs_flag} name={self._fn_name!r}>\"\n async def try_invoke(self, ctx: Context[T]) -> bool:\n ...
SENT in subtypes:
{ "list": [ { "filename": "attacks/pgd_attack.py", "retrieved_chunk": " loss.mean().backward()\n grad = delta.grad.data\n # normalize and add momentum.\n grad.data = torch.sign(grad.data)\n global_gradients.data = self.momentum*global_gradients.da...
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torch.optim as optim def squared_l2_norm(x): flattened = x.view(x.unsqueeze(0).shape[0], -1) return (flattened ** 2).sum(1) def l2_norm(x): return squared_l2_norm(x).sqrt() def trades_loss(mod...
for _ in range(perturb_steps): adv = x_natural + delta # optimize optimizer_delta.zero_grad() with torch.enable_grad(): loss = (-1) * criterion_kl(F.log_softmax(model(adv), dim=1), F.softmax(model(x_nat...
{ "context_start_lineno": 0, "file": "utils/trades.py", "groundtruth_start_lineno": 46, "repository": "jfc43-stratified-adv-rej-bfdc043", "right_context_start_lineno": 47, "task_id": "project_cc_python/9269" }
{ "list": [ { "filename": "attacks/pgd_attack.py", "retrieved_chunk": " delta.data[split:] = torch.clamp(delta.data[split:], min=-self.epsilon_0, max=self.epsilon_0)\n delta.data = torch.clamp(x.data + delta.data, min=self.clip_min, max=self.clip_max) - x.data\n de...
SGD([delta], lr=epsilon / perturb_steps * 2)
{ "list": [ { "filename": "utils/numpy.py", "retrieved_chunk": " \"\"\"\n Expands the tensor using view to allow broadcasting.\n :param array: input tensor\n :type array: numpy.ndarray\n :param array_as: reference tensor\n :type array_as: torch.Tensor or torch.autograd.Variable\n ...
import torch import numpy import scipy.ndimage import math from . import numpy as cnumpy import random SMALL_VALUE = 1e-8 def set_seed(seed): """Sets seed""" if torch.cuda.is_available(): torch.cuda.manual_seed(seed) torch.manual_seed(seed) numpy.random.seed(seed) random.seed(seed) t...
if is_cuda(a): order_index = order_index.cuda() return torch.index_select(a, dim, order_index) def expand_as(tensor, tensor_as): """ Expands the tensor using view to allow broadcasting. :param tensor: input tensor :type tensor: torch.Tensor or torch.autograd.Variable :param tenso...
{ "context_start_lineno": 0, "file": "utils/torch.py", "groundtruth_start_lineno": 445, "repository": "jfc43-stratified-adv-rej-bfdc043", "right_context_start_lineno": 446, "task_id": "project_cc_python/9271" }
{ "list": [ { "filename": "utils/numpy.py", "retrieved_chunk": " for i in range(len(array.shape), len(array_as.shape)):\n shape.append(1)\n return array.reshape(shape)\ndef concatenate(array1, array2, axis=0):\n \"\"\"\n Basically a wrapper for numpy.concatenate, with the exception\...
concatenate([init_dim * numpy.arange(n_tile) + i for i in range(init_dim)]))
{ "list": [ { "filename": "slonogram/handling/handler.py", "retrieved_chunk": " fn: AnyHandlerFn[T],\n observer: bool,\n filter_: Optional[FilterFn[T]],\n middleware: Optional[MiddlewareFn[T]],\n ) -> None:\n self.filter_ = filter_\n self.middleware = middl...
from __future__ import annotations from typing import ( TYPE_CHECKING, Optional, TypeVar, TypeAlias, Callable, ) from ..types.filter import FilterFn from ..types.middleware import MiddlewareFn from ..types.event_flags import MessageFlags from ..types.handler_fn import AnyHandlerFn from ..handling...
self._set._edited_message_handlers.append(handler) return handler return inner def __call__( self, subtypes: MessageFlags, filter_: _OptFilterFn[Message] = None, observer: bool = False, middleware: _OptMid[Message] = None, ) -> _Reg...
{ "context_start_lineno": 0, "file": "slonogram/dispatching/_registrants.py", "groundtruth_start_lineno": 44, "repository": "slonogram-slonogram-9f86552", "right_context_start_lineno": 45, "task_id": "project_cc_python/9224" }
{ "list": [ { "filename": "slonogram/handling/handler.py", "retrieved_chunk": " def __repr__(self) -> str:\n obs_flag = \":observer\" if self.observer else \"\"\n return f\"<Handler{obs_flag} name={self._fn_name!r}>\"\n async def try_invoke(self, ctx: Context[T]) -> bool:\n ...
EDITED in subtypes:
{ "list": [ { "filename": "utils/numpy.py", "retrieved_chunk": " array = array.reshape(-1, flattened_size)\n sorted = numpy.sort(array, axis=1)\n k = int(math.ceil(epsilon))\n thresholds = sorted[:, -k]\n mask = (array >= expand_as(thresholds, array)).astype(float)\n...
import torch import numpy import scipy.ndimage import math from . import numpy as cnumpy import random SMALL_VALUE = 1e-8 def set_seed(seed): """Sets seed""" if torch.cuda.is_available(): torch.cuda.manual_seed(seed) torch.manual_seed(seed) numpy.random.seed(seed) random.seed(seed) t...
tensor = torch.from_numpy(array) if cuda: tensor = tensor.cuda() elif ord == 2: size = tensor.size() flattened_size = numpy.prod(numpy.array(size[1:])) tensor = tensor.view(-1, flattened_size) clamped = torch.clamp(epsilon/torch.norm(tensor, 2, dim=1), m...
{ "context_start_lineno": 0, "file": "utils/torch.py", "groundtruth_start_lineno": 323, "repository": "jfc43-stratified-adv-rej-bfdc043", "right_context_start_lineno": 324, "task_id": "project_cc_python/9270" }
{ "list": [ { "filename": "utils/numpy.py", "retrieved_chunk": " if False: # Version 1\n # https://github.com/ftramer/MultiRobustness/blob/master/pgd_attack.py\n l1 = numpy.sum(numpy.abs(array), axis=1)\n epsilons = numpy.ones((array.shape[0]))*epsilon\n ...
project_ball(array, epsilon=epsilon, ord=ord)
{ "list": [ { "filename": "misc/code_generator/types.py", "retrieved_chunk": "class CodegenerationConfig:\n enums: EnumsConfig\n renames: Dict[AbsolutePath, RenameValue]\n @classmethod\n def read_from(cls, path: Path) -> \"CodegenerationConfig\":\n d = safe_load(open(path, \"r\"))\n...
from pathlib import Path from os import mkdir from sys import argv, exit from json import load from .schemas_generator import generate_schemas from .types import CodegenerationConfig, Spec, RETORT try: config_path = Path(argv[1]) schemas_path = Path(argv[2]) call_groups_directory = Path(argv[3]) except I...
if not call_groups_directory.exists(): print(f"> mkdir {call_groups_directory}") mkdir(call_groups_directory) if not (call_groups_directory / "__init__.py").exists(): print("> creating __init__.py file in the call groups directory") open(call_groups_directory / "__init__.py", "wb").close() schemas =...
{ "context_start_lineno": 0, "file": "misc/code_generator/__main__.py", "groundtruth_start_lineno": 23, "repository": "slonogram-slonogram-9f86552", "right_context_start_lineno": 24, "task_id": "project_cc_python/9218" }
{ "list": [ { "filename": "misc/code_generator/types.py", "retrieved_chunk": "class CodegenerationConfig:\n enums: EnumsConfig\n renames: Dict[AbsolutePath, RenameValue]\n @classmethod\n def read_from(cls, path: Path) -> \"CodegenerationConfig\":\n d = safe_load(open(path, \"r\"))\n...
load(raw_spec, Spec)
{ "list": [ { "filename": "slonogram/extra/aiohttp_session.py", "retrieved_chunk": "class Session(ApiSession):\n def __init__(self, token: str, base_url: str) -> None:\n self._token = token\n self._session = ClientSession(base_url=base_url)\n async def call_method(\n self, m...
import warnings from adaptix import Retort, name_mapping from typing import Optional, Self from .types.api_session import ApiSession from .schemas import Message, Update from .consts import DEFAULT_API_URL from .call_groups import chat, user, updates, queries class Bot: def __init__( self, toke...
self.user = user.UserCallGroup(retort, u_session) self.updates = updates.UpdatesCallGroup(retort, u_session) self.queries = queries.QueriesCallGroup(retort, u_session) self._session = u_session self._finalized = False async def __aenter__(self) -> Self: return self...
{ "context_start_lineno": 0, "file": "slonogram/bot.py", "groundtruth_start_lineno": 41, "repository": "slonogram-slonogram-9f86552", "right_context_start_lineno": 42, "task_id": "project_cc_python/9219" }
{ "list": [ { "filename": "slonogram/extra/aiohttp_session.py", "retrieved_chunk": " raw = await response.read()\n return loads(raw)\n async def finalize(self) -> None:\n await self._session.close()\n__all__ = [\"Session\"]", "score": 56.0472613833769 }, {...
ChatCallGroup(retort, u_session)
{ "list": [ { "filename": "misc/code_generator/types.py", "retrieved_chunk": "class CodegenerationConfig:\n enums: EnumsConfig\n renames: Dict[AbsolutePath, RenameValue]\n @classmethod\n def read_from(cls, path: Path) -> \"CodegenerationConfig\":\n d = safe_load(open(path, \"r\"))\n...
from pathlib import Path from os import mkdir from sys import argv, exit from json import load from .schemas_generator import generate_schemas from .types import CodegenerationConfig, Spec, RETORT try: config_path = Path(argv[1]) schemas_path = Path(argv[2]) call_groups_directory = Path(argv[3]) except I...
spec_root = Path(__file__).parent.parent / "telegram-bot-api-spec" raw_spec = load(open(spec_root / "api.min.json")) spec = RETORT.load(raw_spec, Spec) if not call_groups_directory.exists(): print(f"> mkdir {call_groups_directory}") mkdir(call_groups_directory) if not (call_groups_directory / "__init__.py")....
{ "context_start_lineno": 0, "file": "misc/code_generator/__main__.py", "groundtruth_start_lineno": 20, "repository": "slonogram-slonogram-9f86552", "right_context_start_lineno": 21, "task_id": "project_cc_python/9217" }
{ "list": [ { "filename": "misc/code_generator/types.py", "retrieved_chunk": "class CodegenerationConfig:\n enums: EnumsConfig\n renames: Dict[AbsolutePath, RenameValue]\n @classmethod\n def read_from(cls, path: Path) -> \"CodegenerationConfig\":\n d = safe_load(open(path, \"r\"))\n...
read_from(config_path)
{ "list": [ { "filename": "learning/util/rs2g_trainer.py", "retrieved_chunk": " if (self.config.training_config['task_type'] in ['sequence_classification','graph_classification','collision_prediction']):\n tqdm_bar = tqdm(range(self.config.training_config['epochs']))\n for...
#Copied from https://github.com/AICPS/roadscene2vec #Copyright (c) 2021 UC Irvine Advanced Integrated Cyber-Physical Systems Lab (AICPS) import sys, os sys.path.append(os.path.dirname(sys.path[0])) import torch import numpy as np from tqdm import tqdm from learning.util.trainer import Trainer from data.dataset import ...
if self.config.training_config['task_type'] == 'sequence_classification': batch_y = self.training_labels[indices] #batch_x = (batch, frames, channel, h, w) elif self.config.training_config['task_type'] == 'collision_prediction': bat...
{ "context_start_lineno": 0, "file": "learning/util/image_trainer.py", "groundtruth_start_lineno": 126, "repository": "AICPS-RS2G-b4e985f", "right_context_start_lineno": 127, "task_id": "project_cc_python/9289" }
{ "list": [ { "filename": "learning/util/rs2g_trainer.py", "retrieved_chunk": " for sequence in data_list: # iterate through scene-graph sequences in the batch\n data, label = sequence['sequence'], sequence['label'] #data= list of SceneGraph\n ...
toGPU(batch_x, torch.float32)
{ "list": [ { "filename": "learning/util/scenegraph_trainer.py", "retrieved_chunk": " sequence = next(iter(self.train_loader)).to(self.config.model_config[\"device\"])\n output, _ = self.model.forward(sequence.x, sequence.edge_index, sequence.edge_attr, se...
#Copied from https://github.com/AICPS/roadscene2vec #Copyright (c) 2021 UC Irvine Advanced Integrated Cyber-Physical Systems Lab (AICPS) import sys, os sys.path.append(os.path.dirname(sys.path[0])) import torch import numpy as np from tqdm import tqdm from learning.util.trainer import Trainer from data.dataset import ...
loss_train.backward() acc_loss_train += loss_train.detach().cpu().item() * len(indices) self.optimizer.step() del loss_train acc_loss_train /= len(self.training_data) tqdm_bar.set_description('Epoch: {:...
{ "context_start_lineno": 0, "file": "learning/util/image_trainer.py", "groundtruth_start_lineno": 134, "repository": "AICPS-RS2G-b4e985f", "right_context_start_lineno": 135, "task_id": "project_cc_python/9290" }
{ "list": [ { "filename": "learning/util/rs2g_trainer.py", "retrieved_chunk": " if self.config.training_config['task_type'] == 'sequence_classification':\n self.class_weights = torch.from_numpy(compute_class_weight('balanced', classes=np.unique(self.training_labels), y=self.t...
loss_func(output, batch_y)
{ "list": [ { "filename": "learning/util/trainer.py", "retrieved_chunk": "import random\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nfrom learning.model.cnn_lstm import CNN_LSTM_Classifier\nfrom learning.model.mrgcn import MRGCN\nfrom learning.model.rs2g import RS2...
#Copied from https://github.com/AICPS/roadscene2vec #Copyright (c) 2021 UC Irvine Advanced Integrated Cyber-Physical Systems Lab (AICPS) import sys, os sys.path.append(os.path.dirname(sys.path[0])) import torch import numpy as np from tqdm import tqdm from learning.util.trainer import Trainer from data.dataset import ...
self.training_data, self.testing_data = self.build_real_image_dataset() self.training_labels = np.array([i[1] for i in self.training_data]) self.testing_labels = np.array([i[1] for i in self.testing_data]) self.total_train_labels = np.concatenate([np.full(len(i[0]), i[1]...
{ "context_start_lineno": 0, "file": "learning/util/image_trainer.py", "groundtruth_start_lineno": 28, "repository": "AICPS-RS2G-b4e985f", "right_context_start_lineno": 29, "task_id": "project_cc_python/9285" }
{ "list": [ { "filename": "learning/util/scenegraph_trainer.py", "retrieved_chunk": " super(Scenegraph_Trainer, self).__init__(config, wandb_a)\n self.scene_graph_dataset = SceneGraphDataset()\n self.feature_list = list()\n for i in range(self.config.model_config['num_of_cl...
config.training_config['task_type'] in ['sequence_classification','collision_prediction']):
{ "list": [ { "filename": "scripts/6_train_rs2g_model.py", "retrieved_chunk": " #wandb setup \n wandb_arg = wandb.init(config=learning_config, \n project=learning_config.wandb_config['project'], \n entity=learning_config.wandb_config['entity'])\n ...
import os import sys sys.path.append(os.path.dirname(sys.path[0])) from learning.util.image_trainer import Image_Trainer from learning.util.scenegraph_trainer import Scenegraph_Trainer from learning.util.rs2g_trainer import RS2G_Trainer from util.config_parser import configuration import wandb #Usage: #python 7_transf...
trainer.eval_model(current_epoch=0) elif learning_config.training_config["dataset_type"] == "scenegraph": if learning_config.model_config['model'] in ['rs2g']: trainer = RS2G_Trainer(learning_config, wandb_arg) else: trainer = Scenegraph_Trainer(learning_con...
{ "context_start_lineno": 0, "file": "scripts/7_transfer_model.py", "groundtruth_start_lineno": 26, "repository": "AICPS-RS2G-b4e985f", "right_context_start_lineno": 27, "task_id": "project_cc_python/9311" }
{ "list": [ { "filename": "scripts/6_train_rs2g_model.py", "retrieved_chunk": " trainer.build_model()\n trainer.learn()\n trainer.evaluate()\n else:\n raise ValueError(\"Task unrecognized\")\n trainer.save_model()\nif __name__ == \"__main__\":\n learning_config = c...
load_model()
{ "list": [ { "filename": "scripts/6_train_rs2g_model.py", "retrieved_chunk": " #wandb setup \n wandb_arg = wandb.init(config=learning_config, \n project=learning_config.wandb_config['project'], \n entity=learning_config.wandb_config['entity'])\n ...
import os import sys sys.path.append(os.path.dirname(sys.path[0])) from learning.util.image_trainer import Image_Trainer from learning.util.scenegraph_trainer import Scenegraph_Trainer from learning.util.rs2g_trainer import RS2G_Trainer from util.config_parser import configuration import wandb #Usage: #python 7_transf...
elif learning_config.training_config["dataset_type"] == "scenegraph": if learning_config.model_config['model'] in ['rs2g']: trainer = RS2G_Trainer(learning_config, wandb_arg) else: trainer = Scenegraph_Trainer(learning_config, wandb_arg) trainer.build_transf...
{ "context_start_lineno": 0, "file": "scripts/7_transfer_model.py", "groundtruth_start_lineno": 27, "repository": "AICPS-RS2G-b4e985f", "right_context_start_lineno": 28, "task_id": "project_cc_python/9312" }
{ "list": [ { "filename": "scripts/6_train_rs2g_model.py", "retrieved_chunk": " trainer.build_model()\n trainer.learn()\n trainer.evaluate()\n else:\n raise ValueError(\"Task unrecognized\")\n trainer.save_model()\nif __name__ == \"__main__\":\n learning_config = c...
eval_model(current_epoch=0)
{ "list": [ { "filename": "scripts/3_train_model.py", "retrieved_chunk": " trainer = Image_Trainer(learning_config, wandb_arg)\n trainer.split_dataset()\n trainer.build_model()\n trainer.learn()\n elif learning_config.training_config[\"dataset_type\"] == \"scenegraph\":\...
import os import sys sys.path.append(os.path.dirname(sys.path[0])) from learning.util.image_trainer import Image_Trainer from learning.util.scenegraph_trainer import Scenegraph_Trainer from learning.util.rs2g_trainer import RS2G_Trainer from util.config_parser import configuration import wandb #Usage: #python 7_transf...
else: raise ValueError("Task unrecognized") trainer.save_model() if __name__ == "__main__": # the entry of dynkg pipeline training learning_config = configuration(sys.argv[1:]) train_Trainer(learning_config)
{ "context_start_lineno": 0, "file": "scripts/7_transfer_model.py", "groundtruth_start_lineno": 36, "repository": "AICPS-RS2G-b4e985f", "right_context_start_lineno": 37, "task_id": "project_cc_python/9317" }
{ "list": [ { "filename": "scripts/3_train_model.py", "retrieved_chunk": " raise ValueError(\"Task unrecognized\")\n trainer.save_model()\nif __name__ == \"__main__\":\n # the entry of dynkg pipeline training\n learning_config = configuration(sys.argv[1:])\n train_Trainer(learning_c...
evaluate_transfer_learning()
{ "list": [ { "filename": "llm_rs/convert/models/_base.py", "retrieved_chunk": " n_dims = len(data.shape)\n return name.endswith(\".weight\") and n_dims == 2\n def _rename_weights(self,name:str)->str:\n \"\"\"Rename weights that should be renamed\"\"\"\n return name\n ...
from ._base import BaseAdapter,GGJT_MAGIC from typing import Union,Tuple,Optional,BinaryIO,List,Iterable from transformers import LlamaConfig,LlamaForCausalLM,LlamaTokenizer,AutoConfig,AutoTokenizer,AutoModelForCausalLM import os import torch import struct from ...auto import KnownModels import re import numpy as np im...
logging.info(f"Processing vocabulary with size {self.config.vocab_size}") def sentencepiece_tokens() -> Iterable[Tuple[bytes, float]]: tokenizer = sentence_piece_tokenizer for i in range(tokenizer.vocab_size()): text: bytes if tokenizer.is_unknow...
{ "context_start_lineno": 0, "file": "llm_rs/convert/models/llama.py", "groundtruth_start_lineno": 109, "repository": "LLukas22-llm-rs-python-90e5e70", "right_context_start_lineno": 110, "task_id": "project_cc_python/9419" }
{ "list": [ { "filename": "llm_rs/convert/models/_base.py", "retrieved_chunk": " for name, weight in weights.items():\n if self._filter_weights(name,weight):\n logging.info(f\"Skipping layer '{name}'\")\n continue\n name = self._rename_weights...
tokenizer.sp_model
{ "list": [ { "filename": "scripts/7_transfer_model.py", "retrieved_chunk": " trainer = Image_Trainer(learning_config, wandb_arg)\n trainer.split_dataset()\n trainer.load_model()\n trainer.eval_model(current_epoch=0)\n elif learning_config.training_config[\"dataset_type\...
import os import sys sys.path.append(os.path.dirname(sys.path[0])) from learning.util.rs2g_trainer import RS2G_Trainer from util.config_parser import configuration import wandb #Usage: #python 3_train_model.py --yaml_path ../config/rs2g_graph_risk_config.yaml def train_Trainer(learning_config): ''' Training th...
else: raise ValueError("Task unrecognized") trainer.save_model() if __name__ == "__main__": learning_config = configuration(sys.argv[1:]) train_Trainer(learning_config)
{ "context_start_lineno": 0, "file": "scripts/6_train_rs2g_model.py", "groundtruth_start_lineno": 28, "repository": "AICPS-RS2G-b4e985f", "right_context_start_lineno": 29, "task_id": "project_cc_python/9333" }
{ "list": [ { "filename": "scripts/7_transfer_model.py", "retrieved_chunk": " trainer = Image_Trainer(learning_config, wandb_arg)\n trainer.split_dataset()\n trainer.load_model()\n trainer.eval_model(current_epoch=0)\n elif learning_config.training_config[\"dataset_type\...
evaluate()
{ "list": [ { "filename": "llm_rs/auto.py", "retrieved_chunk": " @staticmethod\n def quantize(\n model_file:Union[str,os.PathLike],\n target_path:Optional[Union[str,os.PathLike]]=None,\n quantization:QuantizationType=QuantizationType.Q4_0,\n container:ContainerType=Co...
from typing import Optional, Callable, List, Union, Generator from abc import ABC import os from .config import GenerationConfig, SessionConfig, ContainerType, QuantizationType from .results import GenerationResult #Theoretically this is incorrect as the 'model' doesnt actually exist, but it is a good enough approx...
""" Quantizes the model. """ ...
{ "context_start_lineno": 0, "file": "llm_rs/base_model.py", "groundtruth_start_lineno": 67, "repository": "LLukas22-llm-rs-python-90e5e70", "right_context_start_lineno": 68, "task_id": "project_cc_python/9403" }
{ "list": [ { "filename": "llm_rs/haystack/haystack.py", "retrieved_chunk": " prompt = kwargs.pop(\"prompt\",None)\n if not prompt:\n raise ValueError(\"`prompt` cannot be None\")\n generation_config = kwargs.pop(\"generation_config\", GenerationConfig())\n gener...
Q4_0,container:ContainerType=ContainerType.GGJT,callback:Optional[Callable[[str],None]]=None)->None:
{ "list": [ { "filename": "llm_rs/auto.py", "retrieved_chunk": " @staticmethod\n def quantize(\n model_file:Union[str,os.PathLike],\n target_path:Optional[Union[str,os.PathLike]]=None,\n quantization:QuantizationType=QuantizationType.Q4_0,\n container:ContainerType=Co...
from typing import Optional, Callable, List, Union, Generator from abc import ABC import os from .config import GenerationConfig, SessionConfig, ContainerType, QuantizationType from .results import GenerationResult #Theoretically this is incorrect as the 'model' doesnt actually exist, but it is a good enough approx...
""" Quantizes the model. """ ...
{ "context_start_lineno": 0, "file": "llm_rs/base_model.py", "groundtruth_start_lineno": 67, "repository": "LLukas22-llm-rs-python-90e5e70", "right_context_start_lineno": 68, "task_id": "project_cc_python/9404" }
{ "list": [ { "filename": "llm_rs/haystack/haystack.py", "retrieved_chunk": " prompt = kwargs.pop(\"prompt\",None)\n if not prompt:\n raise ValueError(\"`prompt` cannot be None\")\n generation_config = kwargs.pop(\"generation_config\", GenerationConfig())\n gener...
GGJT,callback:Optional[Callable[[str],None]]=None)->None:
{ "list": [ { "filename": "OJ/models/SubmissionModel.py", "retrieved_chunk": " contest_id = Column(Integer, ForeignKey('ContestInfo.id'))\n problem_id = Column(Integer, ForeignKey('ProblemInfo.id'))\n create_time = Column(DateTime, default=datetime.datetime.now)\n code_source = Column(Stri...
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, DateTime, Text, JSON from sqlalchemy.orm import relationship import datetime from OJ.db.database import Base, BaseModel from OJ.util.aes import AESTool class ProblemInfo(Base, BaseModel): __tablename__ = 'ProblemInfo' id = Column(Integer, ...
def user(self, filed=None): if not filed: return self._user else: return getattr(self._user, filed) class UserProblemStatus(Base, BaseModel): __tablename__ = 'UserProblemStatus' id = Column(Integer, primary_key=True, index=True, autoincrement=True) user_id = ...
{ "context_start_lineno": 0, "file": "OJ/models/ProblemModels.py", "groundtruth_start_lineno": 43, "repository": "DMSintalor-OJ-Be-f04ae6e", "right_context_start_lineno": 44, "task_id": "project_cc_python/9337" }
{ "list": [ { "filename": "OJ/models/SubmissionModel.py", "retrieved_chunk": " @property\n def user(self):\n return self._user\n @property\n def problem(self):\n return self._problem\n @property\n def contest(self):\n return self._contest\n @property", "...
encrypt_data(self.id)
{ "list": [ { "filename": "test/test_stats_mngr.py", "retrieved_chunk": " all_cf1_stats_lines.extend(stats_lines_cf1_t1_l4[1:])\n all_cf1_stats_lines.extend([empty_line])\n mngr = CfFileHistogramStatsMngr()\n expected_cf1_entries = {\n time1: {l0: expected_cf1_t1_l0_stats,\n ...
# Copyright (C) 2023 Speedb Ltd. 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 or...
assert utils.compare_times_strs(time1, time2) < 0 assert utils.compare_times_strs(time2, time1) > 0 def test_parse_time_str(): parse_time = utils.parse_time_str now = datetime.now() now_str = now.strftime("%Y/%m/%d-%H:%M:%S.%f") assert now == utils.parse_time_str(now_str) assert parse_...
{ "context_start_lineno": 0, "file": "test/test_utils.py", "groundtruth_start_lineno": 104, "repository": "speedb-io-log-parser-d600b0e", "right_context_start_lineno": 105, "task_id": "project_cc_python/9388" }
{ "list": [ { "filename": "test/test_stats_mngr.py", "retrieved_chunk": "** DB Stats **\nUptime(secs): 4.1 total, 4.1 interval\nCumulative writes: 0 writes, 0 keys, 0 commit groups, 0.0 writes per commit group, ingest: 0.00 GB, 0.00 MB/s\nCumulative WAL: 0 writes, 0 syncs, 0.00 writes per sync, writte...
compare_times_strs(time1, time1) == 0
{ "list": [ { "filename": "test/test_csv_outputter.py", "retrieved_chunk": " for entry in counter1_entry_lines:\n add_stats_entry_lines_to_mngr(entry, mngr)\n for entry in counter2_entry_lines:\n add_stats_entry_lines_to_mngr(entry, mngr)\n for entry in counter3_entry_lines:\n ...
# Copyright (C) 2023 Speedb Ltd. 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 or...
assert entry.have_all_lines_been_added() with pytest.raises(utils.ParsingAssertion): entry.add_line(log_line2, last_line=True) with pytest.raises(utils.ParsingAssertion): entry.add_line(log_line2, last_line=False) with pytest.raises(utils.ParsingAssertion): entry.all_lines_adde...
{ "context_start_lineno": 0, "file": "test/test_log_entry.py", "groundtruth_start_lineno": 44, "repository": "speedb-io-log-parser-d600b0e", "right_context_start_lineno": 45, "task_id": "project_cc_python/9360" }
{ "list": [ { "filename": "test/test_log_file.py", "retrieved_chunk": " metadata = LogFileMetadata(entries, start_entry_idx=0)\n assert metadata.get_product_name() == \"RocksDB\"\n assert metadata.get_version() == \"7.2.2\"\n assert metadata.get_git_hash() == \\\n \"35f6432643807...
get_warning_type() is None
{ "list": [ { "filename": "calc_utils.py", "retrieved_chunk": " # have the options common to all the cf-s (they are missing in the\n # cfs_specific_options)\n baseline_opts_for_diff_dict = \\\n copy.deepcopy(baseline_opts.get_options_dict())\n utils.delete_dict_keys(baseline_opts_fo...
import logging from dataclasses import dataclass import db_files from counters import CountersMngr from db_files import DbFilesMonitor from db_options import RAW_NULL_PTR, DatabaseOptions, \ sanitized_to_raw_ptr_value def get_cf_raw_cache_ptr_str(cf_name, db_options): assert isinstance(db_options, DatabaseOp...
if not cache_files_stats: return None assert isinstance(cache_files_stats, db_files.CfsFilesStats) stats.per_cache_id_info[cache_id] = \ CacheIdInfo(options=options, files_stats=cache_files_stats) cache_counters = collect_cache_counters(counters_mngr) if cache...
{ "context_start_lineno": 0, "file": "cache_utils.py", "groundtruth_start_lineno": 218, "repository": "speedb-io-log-parser-d600b0e", "right_context_start_lineno": 219, "task_id": "project_cc_python/9353" }
{ "list": [ { "filename": "display_utils.py", "retrieved_chunk": " disp[\"Caches\"][cache_id] = \\\n prepare_block_cache_info_for_display(cache_info)\n if cache_stats.global_cache_counters:\n disp[\"DB Counters\"] = \\\n prepare_block_counters_for_display...
calc_cf_files_stats(cache_cfs_names, files_monitor)
{ "list": [ { "filename": "test/test_log_file.py", "retrieved_chunk": " 2022/11/24-15:58:04.758398 32819 Compile date\n 2022/11/24-15:58:04.758402 32819 DB SUMMARY\n 2022/11/24-15:58:04.758403 32819 DB Session ID: V90YQ8JY6T5E5H2ES6LK\n 2022/11/24-15:58:04.759056 32819 CURRENT file: CURR...
# Copyright (C) 2023 Speedb Ltd. 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 or...
assert entry.get_lines_idxs_range() == (100, 101) assert not entry.get_code_pos() assert not entry.is_warn_msg() assert entry.get_warning_type() is None assert entry.have_all_lines_been_added() with pytest.raises(utils.ParsingAssertion): entry.add_line(log_line2, last_line=True) wi...
{ "context_start_lineno": 0, "file": "test/test_log_entry.py", "groundtruth_start_lineno": 40, "repository": "speedb-io-log-parser-d600b0e", "right_context_start_lineno": 41, "task_id": "project_cc_python/9356" }
{ "list": [ { "filename": "test/test_log_file.py", "retrieved_chunk": " metadata = LogFileMetadata(entries, start_entry_idx=0)\n assert metadata.get_product_name() == \"RocksDB\"\n assert metadata.get_version() == \"7.2.2\"\n assert metadata.get_git_hash() == \\\n \"35f6432643807...
get_start_line_idx() == 100
{ "list": [ { "filename": "test/test_csv_outputter.py", "retrieved_chunk": " for entry in counter1_entry_lines:\n add_stats_entry_lines_to_mngr(entry, mngr)\n for entry in counter2_entry_lines:\n add_stats_entry_lines_to_mngr(entry, mngr)\n for entry in counter3_entry_lines:\n ...
# Copyright (C) 2023 Speedb Ltd. 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 or...
with pytest.raises(utils.ParsingAssertion): entry.add_line(log_line2, last_line=True) with pytest.raises(utils.ParsingAssertion): entry.add_line(log_line2, last_line=False) with pytest.raises(utils.ParsingAssertion): entry.all_lines_added() def test_warn_single_line(): warn_m...
{ "context_start_lineno": 0, "file": "test/test_log_entry.py", "groundtruth_start_lineno": 45, "repository": "speedb-io-log-parser-d600b0e", "right_context_start_lineno": 46, "task_id": "project_cc_python/9361" }
{ "list": [ { "filename": "test/test_csv_outputter.py", "retrieved_chunk": " assert csv_outputter.get_counters_csv(mngr) == expected_csv\ndef test_get_human_readable_histograms_csv():\n counter1_entry_lines = [\n '''2022/11/24-15:50:09.512106 32851 [db_impl.cc:761] STATISTICS:\n co...
have_all_lines_been_added()
{ "list": [ { "filename": "test/test_counters.py", "retrieved_chunk": " {'time': '2022/11/24-15:50:09.512106', 'value': 0},\n {'time': '2022/11/24-15:50:10.512106', 'value': 10}]}\n add_stats_entry_lines_to_mngr(entry_lines[3], mngr)\n assert mngr....
# Copyright (C) 2023 Speedb Ltd. 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 or...
assert utils.convert_seconds_to_dd_hh_mm_ss(1) == "0d 00h 00m 01s" assert utils.convert_seconds_to_dd_hh_mm_ss(one_minute) == "0d 00h 01m 00s" assert utils.convert_seconds_to_dd_hh_mm_ss(one_hour) == "0d 01h 00m 00s" assert utils.convert_seconds_to_dd_hh_mm_ss(one_day) == "1d 00h 00m 00s" assert ut...
{ "context_start_lineno": 0, "file": "test/test_utils.py", "groundtruth_start_lineno": 138, "repository": "speedb-io-log-parser-d600b0e", "right_context_start_lineno": 139, "task_id": "project_cc_python/9392" }
{ "list": [ { "filename": "test/test_counters.py", "retrieved_chunk": " {'time': '2022/11/24-15:50:10.512106', 'value': 10},\n {'time': '2022/11/24-15:50:11.512106', 'value': 11}]}\n add_stats_entry_lines_to_mngr(entry_lines[4], mngr)\n assert mngr...
convert_seconds_to_dd_hh_mm_ss(0) == "0d 00h 00m 00s"
{ "list": [ { "filename": "test/test_csv_outputter.py", "retrieved_chunk": " for entry in counter1_entry_lines:\n add_stats_entry_lines_to_mngr(entry, mngr)\n for entry in counter2_entry_lines:\n add_stats_entry_lines_to_mngr(entry, mngr)\n for entry in counter3_entry_lines:\n ...
# Copyright (C) 2023 Speedb Ltd. 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 or...
with pytest.raises(utils.ParsingAssertion): entry.add_line(log_line2, last_line=False) with pytest.raises(utils.ParsingAssertion): entry.all_lines_added() def test_warn_single_line(): warn_msg = "2022/04/17-15:24:51.089890 7f4a9fdff700 [WARN] " \ "[/column_family.cc:932] St...
{ "context_start_lineno": 0, "file": "test/test_log_entry.py", "groundtruth_start_lineno": 48, "repository": "speedb-io-log-parser-d600b0e", "right_context_start_lineno": 49, "task_id": "project_cc_python/9363" }
{ "list": [ { "filename": "test/test_csv_outputter.py", "retrieved_chunk": " assert csv_outputter.get_counters_csv(mngr) == expected_csv\ndef test_get_human_readable_histograms_csv():\n counter1_entry_lines = [\n '''2022/11/24-15:50:09.512106 32851 [db_impl.cc:761] STATISTICS:\n co...
add_line(log_line2, last_line=True)
{ "list": [ { "filename": "laser_tag/graphics/components/Fps.py", "retrieved_chunk": " super().update()\n def render(self):\n self.surface = self.text.get_surface(\n \"FPS: \" + str(round(self.data, 2)), 40, (255, 255, 255)\n )\n super().render()", "scor...
import pygame from ..configuration import VARIABLES from . import display from .resize import resize class Text: """A class for generating text""" __instances = {} def __new__(cls, font: str, font_is_file: bool = False, size_multiplier: float = 1): id = (font, font_is_file, size_multiplier) ...
def get_size(self, generated_text: pygame.Surface) -> tuple[int, int]: return generated_text.get_width(), generated_text.get_height() def blit( self, generated_text: pygame.Surface, x, y, align_x, align_y ) -> tuple[int, int]: text_width, text_height = self.get_size(generated_text...
{ "context_start_lineno": 0, "file": "laser_tag/graphics/Text.py", "groundtruth_start_lineno": 40, "repository": "axelmunch-laser-tag-38f6fc0", "right_context_start_lineno": 41, "task_id": "project_cc_python/9277" }
{ "list": [ { "filename": "laser_tag/graphics/components/Fps.py", "retrieved_chunk": " super().update()\n def render(self):\n self.surface = self.text.get_surface(\n \"FPS: \" + str(round(self.data, 2)), 40, (255, 255, 255)\n )\n super().render()", "scor...
anti_aliased_text, color)