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": "train.py", "retrieved_chunk": " dist.print0()\n dist.print0('Training options:')\n dist.print0(json.dumps(c, indent=2))\n dist.print0()\n dist.print0(f'Output directory: {c.run_dir}')\n dist.print0(f'Dataset path: {c.dataset_kwargs.path}')...
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # This work is licensed under a Creative Commons # Attribution-NonCommercial-ShareAlike 4.0 International License. # You should have received a copy of the license along with this # work. If not, see http://creativecommons.org/licenses/by-nc-...
stats_jsonl = None batch_mul_dict = {512: 1, 256: 2, 128: 4, 64: 16, 32: 32, 16: 64} if train_on_latents: p_list = np.array([(1 - real_p), real_p]) patch_list = np.array([img_resolution // 2, img_resolution]) batch_mul_avg = np.sum(p_list * np.array([2, 1])) else: p_list...
{ "context_start_lineno": 0, "file": "training/training_loop.py", "groundtruth_start_lineno": 144, "repository": "Zhendong-Wang-Patch-Diffusion-929b0c0", "right_context_start_lineno": 145, "task_id": "project_cc_python/4562" }
{ "list": [ { "filename": "train.py", "retrieved_chunk": " dist.print0(f'Batch size: {c.batch_size}')\n dist.print0(f'Mixed-precision: {c.network_kwargs.use_fp16}')\n dist.print0()\n # Dry run?\n if opts.dry_run:\n dist.print0('Dry run; exiting.')\n re...
update_progress(cur_nimg // 1000, total_kimg)
{ "list": [ { "filename": "meta-vsc-descriptor-runtime/runtime/validation.py", "retrieved_chunk": "logger.setLevel(logging.INFO)\nclass DataValidationError(AssertionError):\n pass\ndef validate_total_descriptors(dataset: str, n_features: int, total_seconds: float):\n if n_features > total_second...
import numpy as np import pytest import validation # Run with python -m pytest tests/test_validation.py from runtime/ def test_dim_too_large(): features = np.random.randn(10, 513).astype("float32") with pytest.raises(validation.DataValidationError): validation.validate_descriptor_dim("test", features...
def test_length_validation(): video_ids = np.array(["Q200001", "Q200001", "Q200002", "Q200003"]) timestamps = np.array([[0, 10], [10, 20], [0, 10]]) features = np.random.randn(4, 16).astype("float32") submission = { "video_ids": video_ids, "timestamps": timestamps, "features":...
{ "context_start_lineno": 0, "file": "meta-vsc-descriptor-runtime/runtime/tests/test_validation.py", "groundtruth_start_lineno": 29, "repository": "line-Meta-AI-Video-Similarity-Challenge-3rd-Place-Solution-b8cf098", "right_context_start_lineno": 30, "task_id": "project_cc_python/4386" }
{ "list": [ { "filename": "meta-vsc-descriptor-runtime/runtime/validation.py", "retrieved_chunk": " query_features = np.load(args.query_features, allow_pickle=False)\n ref_features = np.load(args.ref_features, allow_pickle=False)\n query_meta = pd.read_csv(args.query_metadata)\n ref_meta =...
validate_total_descriptors("test", features.shape[0], total_seconds)
{ "list": [ { "filename": "meta-vsc-descriptor-runtime/runtime/validation.py", "retrieved_chunk": " validate_descriptor_dtype(\"reference\", ref_features[\"features\"])\n validate_descriptor_dim(\"query\", query_features[\"features\"], max_dim=512)\n validate_descriptor_dim(\"reference\", ref...
import numpy as np import pytest import validation # Run with python -m pytest tests/test_validation.py from runtime/ def test_dim_too_large(): features = np.random.randn(10, 513).astype("float32") with pytest.raises(validation.DataValidationError): validation.validate_descriptor_dim("test", features...
def test_total_descriptors(): features = np.random.randn(100, 64).astype("float32") total_seconds = 50 with pytest.raises(validation.DataValidationError): validation.validate_total_descriptors("test", features.shape[0], total_seconds) def test_length_validation(): video_ids = np.array(["Q20...
{ "context_start_lineno": 0, "file": "meta-vsc-descriptor-runtime/runtime/tests/test_validation.py", "groundtruth_start_lineno": 22, "repository": "line-Meta-AI-Video-Similarity-Challenge-3rd-Place-Solution-b8cf098", "right_context_start_lineno": 23, "task_id": "project_cc_python/4385" }
{ "list": [ { "filename": "meta-vsc-descriptor-runtime/runtime/validation.py", "retrieved_chunk": " validate_descriptor_dtype(\"reference\", ref_features[\"features\"])\n validate_descriptor_dim(\"query\", query_features[\"features\"], max_dim=512)\n validate_descriptor_dim(\"reference\", ref...
validate_sorted_ids("test", video_ids)
{ "list": [ { "filename": "meta-vsc-matching-runtime/submission_src/src/vsc/storage.py", "retrieved_chunk": " feats = []\n timestamps = []\n for feature in features:\n video_id = format_video_id(feature.video_id, dataset)\n video_ids.append(np.full(len(feature), video_id))\n ...
import numpy as np import pytest import validation # Run with python -m pytest tests/test_validation.py from runtime/ def test_dim_too_large(): features = np.random.randn(10, 513).astype("float32") with pytest.raises(validation.DataValidationError): validation.validate_descriptor_dim("test", features...
timestamps = np.array([[0, 10], [10, 20], [0, 10], [10, 20]]) features = np.random.randn(3, 16).astype("float32") submission = { "video_ids": video_ids, "timestamps": timestamps, "features": features, } with pytest.raises(validation.DataValidationError): validation....
{ "context_start_lineno": 0, "file": "meta-vsc-descriptor-runtime/runtime/tests/test_validation.py", "groundtruth_start_lineno": 42, "repository": "line-Meta-AI-Video-Similarity-Challenge-3rd-Place-Solution-b8cf098", "right_context_start_lineno": 43, "task_id": "project_cc_python/4387" }
{ "list": [ { "filename": "meta-vsc-matching-runtime/submission_src/src/vsc/storage.py", "retrieved_chunk": " np.savez(f, video_ids=video_ids, features=feats, timestamps=timestamps)\ndef same_value_ranges(values):\n start = 0\n value = values[start]\n for i, v in enumerate(values):\n ...
validate_lengths("test", submission)
{ "list": [ { "filename": "meta-vsc-matching-runtime/submission_src/src/vsc/index.py", "retrieved_chunk": " query_id = query_ids[i]\n query_idx = query_indices[i]\n query_metadata = query_metadatas[query_id]\n ref_id = self.video_clip_to_video_ids[j]\n ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import abc from typing import List import numpy as np import torch from src.vsc.index import VideoFeature from src.vsc.metrics import Candi...
matches.append(match) return matches def localize(self, candidate: CandidatePair) -> List[Match]: return self.localize_all([candidate]) def score(self, candidate: CandidatePair, match: Match, box, similarity) -> float: return 1.0 class VCSLLocalizationMaxSim(VCSLLoca...
{ "context_start_lineno": 0, "file": "meta-vsc-matching-runtime/submission_src/src/vsc/localization.py", "groundtruth_start_lineno": 86, "repository": "line-Meta-AI-Video-Similarity-Challenge-3rd-Place-Solution-b8cf098", "right_context_start_lineno": 87, "task_id": "project_cc_python/4379" }
{ "list": [ { "filename": "meta-vsc-matching-runtime/submission_src/src/vsc/index.py", "retrieved_chunk": " )\n pair_nns[query_id, ref_id].append(match)\n return [\n PairMatches(query_id, ref_id, matches)\n for ((query_id, ref_id), matches) in pair_nn...
_replace(score=score)
{ "list": [ { "filename": "training/dataset.py", "retrieved_chunk": " if fname not in self._all_fnames:\n return None\n with self._open_file(fname) as f:\n labels = json.load(f)['labels']\n if labels is None:\n return None\n labels = dict(la...
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # This work is licensed under a Creative Commons # Attribution-NonCommercial-ShareAlike 4.0 International License. # You should have received a copy of the license along with this # work. If not, see http://creativecommons.org/licenses/by-nc-...
if progressive: p_cumsum = p_list.cumsum() p_cumsum[-1] = 10. prog_mask = (cur_nimg // 1000 / total_kimg) <= p_cumsum patch_size = int(patch_list[prog_mask][0]) batch_mul_avg = batch_mul_dict[patch_size]...
{ "context_start_lineno": 0, "file": "training/training_loop.py", "groundtruth_start_lineno": 160, "repository": "Zhendong-Wang-Patch-Diffusion-929b0c0", "right_context_start_lineno": 161, "task_id": "project_cc_python/4563" }
{ "list": [ { "filename": "training/dataset.py", "retrieved_chunk": " return labels\n#----------------------------------------------------------------------------", "score": 50.603534135175444 }, { "filename": "dataset_tool.py", "retrieved_chunk": " if img.ndim ...
ddp_sync(ddp, (round_idx == num_accumulation_rounds - 1)):
{ "list": [ { "filename": "training/loss.py", "retrieved_chunk": " self.epsilon_t = epsilon_t\n def __call__(self, net, images, labels, augment_pipe=None):\n rnd_uniform = torch.rand([images.shape[0], 1, 1, 1], device=images.device)\n sigma = self.sigma(1 + rnd_uniform * (self....
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # This work is licensed under a Creative Commons # Attribution-NonCommercial-ShareAlike 4.0 International License. # You should have received a copy of the license along with this # work. If not, see http://creativecommons.org/licenses/by-nc-...
loss.sum().mul(loss_scaling / batch_gpu_total / batch_mul).backward() # loss.mean().mul(loss_scaling / batch_mul).backward() # Update weights. for g in optimizer.param_groups: g['lr'] = optimizer_kwargs['lr'] * min(cur_nimg / max(lr_rampup_kimg * 1000, 1e-8)...
{ "context_start_lineno": 0, "file": "training/training_loop.py", "groundtruth_start_lineno": 187, "repository": "Zhendong-Wang-Patch-Diffusion-929b0c0", "right_context_start_lineno": 188, "task_id": "project_cc_python/4564" }
{ "list": [ { "filename": "training/patch_loss.py", "retrieved_chunk": " D_yn = net(yn, sigma, x_pos=images_pos, class_labels=labels, augment_labels=augment_labels)\n loss = weight * ((D_yn - y) ** 2)\n return loss\n#----------------------------------------------------------------...
report('Loss/loss', loss)
{ "list": [ { "filename": "train.py", "retrieved_chunk": " if opts.implicit_mlp:\n c.network_kwargs.implicit_mlp = True\n c.network_kwargs.update(dropout=opts.dropout, use_fp16=opts.fp16)\n # Training options.\n c.total_kimg = max(int(opts.duration * 1000), 1)\n c.ema_halflife_ki...
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # This work is licensed under a Creative Commons # Attribution-NonCommercial-ShareAlike 4.0 International License. # You should have received a copy of the license along with this # work. If not, see http://creativecommons.org/licenses/by-nc-...
fields += [f"kimg {training_stats.report0('Progress/kimg', cur_nimg / 1e3):<9.1f}"] fields += [f"loss {loss.mean().item():<9.3f}"] fields += [f"time {dnnlib.util.format_time(training_stats.report0('Timing/total_sec', tick_end_time - start_time)):<12s}"] fields += [f"sec/tick {training_s...
{ "context_start_lineno": 0, "file": "training/training_loop.py", "groundtruth_start_lineno": 216, "repository": "Zhendong-Wang-Patch-Diffusion-929b0c0", "right_context_start_lineno": 217, "task_id": "project_cc_python/4565" }
{ "list": [ { "filename": "train.py", "retrieved_chunk": " if opts.seed is not None:\n c.seed = opts.seed\n else:\n seed = torch.randint(1 << 31, size=[], device=torch.device('cuda'))\n torch.distributed.broadcast(seed, src=0)\n c.seed = int(seed)\n # Transfer lear...
report0('Progress/tick', cur_tick):<5d}"]
{ "list": [ { "filename": "generate.py", "retrieved_chunk": " class_labels = None\n if net.label_dim:\n class_labels = torch.eye(net.label_dim, device=device)[rnd.randint(net.label_dim, size=[batch_size], device=device)]\n if class_idx is not None:\n class_la...
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # This work is licensed under a Creative Commons # Attribution-NonCommercial-ShareAlike 4.0 International License. # You should have received a copy of the license along with this # work. If not, see http://creativecommons.org/licenses/by-nc-...
data[key] = value.cpu() del value # conserve memory if dist.get_rank() == 0: with open(os.path.join(run_dir, f'network-snapshot-{cur_nimg//1000:06d}.pkl'), 'wb') as f: pickle.dump(data, f) del data # conserve memory ...
{ "context_start_lineno": 0, "file": "training/training_loop.py", "groundtruth_start_lineno": 241, "repository": "Zhendong-Wang-Patch-Diffusion-929b0c0", "right_context_start_lineno": 242, "task_id": "project_cc_python/4567" }
{ "list": [ { "filename": "generate.py", "retrieved_chunk": " images = sampler_fn(net, latents, latents_pos, mask_pos, class_labels, randn_like=rnd.randn_like, **sampler_kwargs)\n if on_latents:\n images = 1 / 0.18215 * images\n images = img_vae.decode(images.float(...
check_ddp_consistency(value)
{ "list": [ { "filename": "generate.py", "retrieved_chunk": " images = sampler_fn(net, latents, latents_pos, mask_pos, class_labels, randn_like=rnd.randn_like, **sampler_kwargs)\n if on_latents:\n images = 1 / 0.18215 * images\n images = img_vae.decode(images.float(...
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # This work is licensed under a Creative Commons # Attribution-NonCommercial-ShareAlike 4.0 International License. # You should have received a copy of the license along with this # work. If not, see http://creativecommons.org/licenses/by-nc-...
if dist.get_rank() == 0: if stats_jsonl is None: stats_jsonl = open(os.path.join(run_dir, 'stats.jsonl'), 'at') stats_jsonl.write(json.dumps(dict(training_stats.default_collector.as_dict(), timestamp=time.time())) + '\n') stats_jsonl.flush() dist.upda...
{ "context_start_lineno": 0, "file": "training/training_loop.py", "groundtruth_start_lineno": 254, "repository": "Zhendong-Wang-Patch-Diffusion-929b0c0", "right_context_start_lineno": 255, "task_id": "project_cc_python/4568" }
{ "list": [ { "filename": "generate.py", "retrieved_chunk": " if image_np.shape[2] == 1:\n PIL.Image.fromarray(image_np[:, :, 0], 'L').save(image_path)\n else:\n PIL.Image.fromarray(image_np, 'RGB').save(image_path)\n # Done.\n torch.distribute...
default_collector.update()
{ "list": [ { "filename": "util/outputWriter.py", "retrieved_chunk": " for sample_key, sample_value in each_candidate.support_cnv_calls.items():\n if sample_value:\n ids = []\n scores = []\n ...
import pandas as pd import re import logging as logger import os import pysam import gzip from analysis.cnv_candidate import CNVCandidate class VCFSNVParser(object): def __init__(self, min_chromosome_len=1e6, as_dev=False): self.as_dev = as_dev logger.basicConfig(level=logger.DEBUG) if as_dev else...
candidate.statistics['z-score']['sample_score'] = sample_gq if "GT" in format_set: gt_idx = format_set.index('GT') candidate.gt = sample_cells[gt_idx] # Could be left black as only details for the known variant are known and l...
{ "context_start_lineno": 0, "file": "util/vcf_parser.py", "groundtruth_start_lineno": 198, "repository": "fritzsedlazeck-Spectre-01b8ed5", "right_context_start_lineno": 199, "task_id": "project_cc_python/4573" }
{ "list": [ { "filename": "util/outputWriter.py", "retrieved_chunk": " file_handler.write(f'{vcf_header}\\n')\n file_handler.write(f'{vcf_sample_header}\\n')\n file_handler.write(f'{vcf_lines}\\n')\n file_handler.close()\nclass IntermediateFile(object):\n def __init__(se...
statistics['z-score'] = {}
{ "list": [ { "filename": "examples/classification/nin_cifar.py", "retrieved_chunk": " root=root, train=True, download=True, transform=augmentation\n)\ntrain_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size, shuffle=True)\nval_dataset = torchvision.datasets.CIFAR10(\n root=root...
import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms from catalyst import dl import sys import os from torch_integral import IntegralWrapper from torch_integral import UniformDistribution from torch_integral import standard_continuous_dims class MnistNet(nn.Module): de...
wrapper = IntegralWrapper(init_from_discrete=True) model = wrapper(model, [1, 1, 28, 28], continuous_dims) ranges = [[16, 16], [32, 64], [16, 32]] model.reset_distributions([UniformDistribution(*r) for r in ranges]) # ------------------------------------------------------------------------------------ # Train # -----...
{ "context_start_lineno": 0, "file": "examples/classification/mnist.py", "groundtruth_start_lineno": 68, "repository": "TheStageAI-TorchIntegral-baf578b", "right_context_start_lineno": 69, "task_id": "project_cc_python/4577" }
{ "list": [ { "filename": "examples/classification/nin_cifar.py", "retrieved_chunk": "# ------------------------------------------------------------------------------------\nmodel = nin_cifar10().cuda()\ncontinuous_dims = {}\nfor name, mod in model.named_modules():\n if \"stage3\" in name:\n ...
update({"linear.weight": [1], "linear.bias": [], "conv_1.weight": [0]})
{ "list": [ { "filename": "src/stripe_integrations/webhooks/subscriptions.py", "retrieved_chunk": " if self.event.customer:\n StripeCustomer.sync(self.event.customer)\nclass CustomerSubscriptionCreatedWebhook(CustomerSubscriptionBaseWebhook):\n name = \"customer.subscription.creat...
# Third Party Stuff from django.apps import apps from django.conf import settings # Stripe Integrations Stuff from stripe_integrations.actions import StripeCustomer from stripe_integrations.settings import stripe_settings from stripe_integrations.webhooks.base import BaseWebhook class CustomerUpdatedWebhook(BaseWebh...
{ "context_start_lineno": 0, "file": "src/stripe_integrations/webhooks/customers.py", "groundtruth_start_lineno": 55, "repository": "twopointone-stripe-integrations-ec992eb", "right_context_start_lineno": 56, "task_id": "project_cc_python/4524" }
{ "list": [ { "filename": "src/stripe_integrations/webhooks/subscriptions.py", "retrieved_chunk": "class CustomerSubscriptionTrialWillEndWebhook(CustomerSubscriptionBaseWebhook):\n name = \"customer.subscription.trial_will_end\"\n description = \"Occurs three days before the trial period of a su...
soft_delete(self.event.customer)
{ "list": [ { "filename": "examples/server.py", "retrieved_chunk": "import asyncio\nfrom sa import *\nfrom sa.samp import *\nimport traceback\nimport math\ndef on_message(message, internal_packet, peer, server):\n if message.id == MSG.RPC:\n rpc = message\n if rpc.rpc_id == RPC.CLICK_...
import asyncio from sa import samp from sa.samp import MSG, RPC ''' Login; placeholders(username + password) ''' class ZombieServer(samp.Server): def __init__(self): super().__init__(('127.0.0.1', 7777)) self.hostname = 'Zombie Apocalypse' self.gamemode = 'Survival' self.language =...
#todo peer.push_message(samp.ShowTextdraw(1, 0, samp.Vec2(5, 5), 0xff0000ff, samp.Vec2(5, 5), 0, 0, 0, 0, 0, 0, samp.Vec2(100, 100), 0, samp.Vec3(0,0,0), 0, 0, 0, 'aaa')) elif message.id == MSG.CONNECTION_REQUEST: peer.password = message.password async def main(): s = ZombieSer...
{ "context_start_lineno": 0, "file": "examples/zombie.py", "groundtruth_start_lineno": 20, "repository": "pitaya1001-hta-c83dc5c", "right_context_start_lineno": 21, "task_id": "project_cc_python/4515" }
{ "list": [ { "filename": "examples/server.py", "retrieved_chunk": " if rpc.player_id == 0:\n peer.push_message(GiveWeapon(WEAPON.M4, 250))\n elif rpc.player_id == 1:\n peer.push_message(RemoveAllWeapons())\n elif rpc.rpc_id == RPC.REQUEST_CHA...
ChatMessage('Welcome survivor!', 0x1aab84ff))
{ "list": [ { "filename": "torch_integral/model.py", "retrieved_chunk": " \"start_index\": start,\n }\n )\n self.rearranger(params, feature_maps, group.size)\n def preprocess_model(\n self,\n model,\n ...
import torch from .tsp_solver import two_opt_find_permutation def total_variance(tensors): """ Calculates total variation of tensors along given dimension. Parameters ---------- tensors: List[Dict[str, obj]]. List of dicts with keys 'value' and 'dim'. Returns ------- total_va...
return indices def _select_tensors(self, params, feature_maps): """Returns list of tensors which total variation should be optimized.""" return params class NOptOutFiltersPermutation(NOptPermutation): """ Class implements NOptPermutation interface for optimzation of out filt...
{ "context_start_lineno": 0, "file": "torch_integral/permutation.py", "groundtruth_start_lineno": 99, "repository": "TheStageAI-TorchIntegral-baf578b", "right_context_start_lineno": 100, "task_id": "project_cc_python/4575" }
{ "list": [ { "filename": "torch_integral/model.py", "retrieved_chunk": " if group is not another_group:\n start += another_group.size\n else:\n break\n for p in parent.params:\n param...
type(torch.long).to(device)
{ "list": [ { "filename": "examples/server.py", "retrieved_chunk": "import asyncio\nfrom sa import *\nfrom sa.samp import *\nimport traceback\nimport math\ndef on_message(message, internal_packet, peer, server):\n if message.id == MSG.RPC:\n rpc = message\n if rpc.rpc_id == RPC.CLICK_...
import asyncio from sa import samp from sa.samp import RPC, MSG def on_message(message, internal_packet, peer, client): print(message) #if message.id == MSG.RPC: # rpc = message # print(rpc) async def f(c): await asyncio.sleep(5) c.server_peer.push_message(samp.RconCommand('login changem...
c.name = 'bob' c.message_callbacks.append(on_message) await c.start() asyncio.get_event_loop().create_task(f(c)) while True: await asyncio.sleep(0.01) c.update() try: asyncio.run(main()) except KeyboardInterrupt: pass
{ "context_start_lineno": 0, "file": "examples/client.py", "groundtruth_start_lineno": 15, "repository": "pitaya1001-hta-c83dc5c", "right_context_start_lineno": 16, "task_id": "project_cc_python/4511" }
{ "list": [ { "filename": "examples/server.py", "retrieved_chunk": " if rpc.player_id == 0:\n peer.push_message(GiveWeapon(WEAPON.M4, 250))\n elif rpc.player_id == 1:\n peer.push_message(RemoveAllWeapons())\n elif rpc.rpc_id == RPC.REQUEST_CHA...
Client(('127.0.0.1', 7777))
{ "list": [ { "filename": "python/tests/test_vcf_reader.py", "retrieved_chunk": "def test_vcf_reader_missing_file():\n with pytest.raises(OSError):\n VCFReader(\"test.vcf\")\ndef test_vcf_indexed_reader_query():\n reader = VCFIndexedReader(DATA / \"vcf_file.vcf.gz\")\n rbr = reader.que...
# Test the fasta reader can be converted to a polars dataframe from pathlib import Path import importlib import pytest from biobear import BamReader, BamIndexedReader DATA = Path(__file__).parent / "data" @pytest.mark.skipif( not importlib.util.find_spec("polars"), reason="polars not installed" ) def test_bam...
assert 1 == sum(b.num_rows for b in rbr) def test_bam_indexed_reader_no_file(): with pytest.raises(OSError): BamIndexedReader("test.bam")
{ "context_start_lineno": 0, "file": "python/tests/test_bam_reader.py", "groundtruth_start_lineno": 41, "repository": "wheretrue-biobear-5be051c", "right_context_start_lineno": 42, "task_id": "project_cc_python/4606" }
{ "list": [ { "filename": "python/tests/test_bcf_reader.py", "retrieved_chunk": "def test_bcf_indexed_reader_query():\n \"\"\"Test the BCFIndexedReader.query() method.\"\"\"\n reader = BCFIndexedReader(DATA / \"index.bcf\")\n rbr = reader.query(\"1\")\n assert 191 == sum(b.num_rows for b i...
query("chr1:12203700-12205426")
{ "list": [ { "filename": "services/extract_metadata.py", "retrieved_chunk": " {\"role\": \"user\", \"content\": text},\n ]\n completion = get_chat_completion(messages, \"gpt-4\")\n print(f\"completion: {completion}\")\n try:\n metadata = json.loads(completion)\n except:\n...
from services.openai import get_chat_completion def screen_text_for_pii(text: str) -> bool: # This prompt is just an example, change it to fit your use case messages = [ { "role": "system", "content": f""" You can only respond with the word "True" or "False", where ...
return True return False
{ "context_start_lineno": 0, "file": "services/pii_detection.py", "groundtruth_start_lineno": 26, "repository": "jamescalam-ask-lex-plugin-3769174", "right_context_start_lineno": 27, "task_id": "project_cc_python/4507" }
{ "list": [ { "filename": "services/extract_metadata.py", "retrieved_chunk": " {\"role\": \"user\", \"content\": text},\n ]\n completion = get_chat_completion(messages, \"gpt-4\")\n print(f\"completion: {completion}\")\n try:\n metadata = json.loads(completion)\n except:\n...
startswith("True"):
{ "list": [ { "filename": "bot/manager.py", "retrieved_chunk": " def __init__(self, model: Model) -> None:\n self.piston_provider = Piston(model)\n self.providers: list[Provider] = [GodBolt(model), self.piston_provider]\n self.runtimes = models.RuntimeTree()\n self.model...
import crescent import hikari from bot.config import CONFIG from bot.manager import Manager Plugin = crescent.Plugin[hikari.GatewayBot, "Model"] INTENTS = hikari.Intents.ALL_UNPRIVILEGED | hikari.Intents.MESSAGE_CONTENT class Model: def __init__(self) -> None: self.manager = Manager(self) async def...
client = crescent.Client(app, model := Model()) @app.listen(hikari.StartingEvent) async def _(_: hikari.StartingEvent) -> None: await model.startup() @app.listen(hikari.StoppingEvent) async def _(_: hikari.StoppingEvent) -> None: await model.shutdown() client.plugins.load_fol...
{ "context_start_lineno": 0, "file": "bot/app.py", "groundtruth_start_lineno": 22, "repository": "CircuitSacul-io-775ac7c", "right_context_start_lineno": 23, "task_id": "project_cc_python/4598" }
{ "list": [ { "filename": "bot/manager.py", "retrieved_chunk": " await asyncio.gather(\n *(asyncio.create_task(p.shutdown()) for p in self.providers)\n )\n async def update_data(self) -> None:\n await asyncio.gather(\n *(asyncio.create_task(p.update_data()...
TOKEN, intents=INTENTS)
{ "list": [ { "filename": "bot/plugins/instance.py", "retrieved_chunk": " ComponentID.CODE_BLOCK,\n placeholder=\"Select the code block to run\",\n )\n for x, block in enumerate(self.codes):\n if block.filename:\n la...
from __future__ import annotations import re import typing as t from hikari import Attachment, Message from bot import models CODE_BLOCK_REGEX = re.compile(r"```(?P<lang>\w*)[\n\s]*(?P<code>(.|\n)*?)```") CODE_LINE_REGEX = re.compile(r"`(?P<code>[^`\n]+)`") async def get_codes(message: Message) -> list[models.Cod...
if language := dct.get("lang"): code.language = language blocks.append(code) content = CODE_BLOCK_REGEX.sub("", content) for line in CODE_LINE_REGEX.finditer(content): blocks.append(models.Code(code=line.groupdict()["code"])) return blocks async def _get_code_attachm...
{ "context_start_lineno": 0, "file": "bot/utils/parse.py", "groundtruth_start_lineno": 28, "repository": "CircuitSacul-io-775ac7c", "right_context_start_lineno": 29, "task_id": "project_cc_python/4600" }
{ "list": [ { "filename": "bot/plugins/help.py", "retrieved_chunk": " ):\n return\n await message.message.respond(embeds=HELP_EMBEDS, reply=True)", "score": 31.07049818212053 }, { "filename": "bot/plugins/instance.py", "retrieved_chunk": " # version\n ...
Code(code=dct["code"])
{ "list": [ { "filename": "ljd/rawdump/header.py", "retrieved_chunk": "class Flags:\n def __init__(self):\n self.is_big_endian = False\n self.is_stripped = False\n self.has_ffi = False\n self.fr2 = False\nclass Header:\n def __init__(self):\n self.version = 0\n...
# # Copyright (C) 2013 Andrian Nord. See Copyright Notice in main.py # import ljd.bytecode.constants as constants import ljd.bytecode.debuginfo as debug class Flags: def __init(self): self.has_sub_prototypes = False self.is_variadic = False self.has_ffi = False self.has_jit = True...
{ "context_start_lineno": 0, "file": "ljd/bytecode/prototype.py", "groundtruth_start_lineno": 30, "repository": "weaweawe01-luajit_decompile-2b32d4b", "right_context_start_lineno": 31, "task_id": "project_cc_python/4505" }
{ "list": [ { "filename": "ljd/rawdump/header.py", "retrieved_chunk": " self.origin = b''\n self.name = b''\ndef read(state, header):\n r = True\n header.origin = state.stream.name\n r = r and _check_magic(state)\n r = r and _read_version(state, header)\n r = r and _read_f...
DebugInformation()
{ "list": [ { "filename": "kaflow/_utils/inspect.py", "retrieved_chunk": "R = TypeVar(\"R\")\ndef is_not_coroutine_function(\n func: Callable[P, R | Awaitable[R]]\n) -> TypeGuard[Callable[P, R]]:\n \"\"\"Check if a function is not a coroutine function. This function narrows the type\n of the ...
from __future__ import annotations import asyncio import contextvars import functools from typing import Awaitable, Callable, TypeVar from typing_extensions import ParamSpec P = ParamSpec("P") R = TypeVar("R") # Inspired by https://github.com/tiangolo/asyncer def asyncify(func: Callable[P, R]) -> Callable[P, Await...
ctx = contextvars.copy_context() func_call = functools.partial(ctx.run, func, *args, **kwargs) return await loop.run_in_executor(None, func_call) # type: ignore return wrapper
{ "context_start_lineno": 0, "file": "kaflow/_utils/asyncio.py", "groundtruth_start_lineno": 26, "repository": "gabrielmbmb-kaflow-1c5ec86", "right_context_start_lineno": 27, "task_id": "project_cc_python/4672" }
{ "list": [ { "filename": "kaflow/_utils/inspect.py", "retrieved_chunk": " \"\"\"\n return not inspect.iscoroutinefunction(func)", "score": 114.08288852772068 }, { "filename": "kaflow/testclient.py", "retrieved_chunk": " self.app._publish = intercept_publish(self...
get_running_loop()
{ "list": [ { "filename": "tests/test_connections.py", "retrieved_chunk": " assert result is not None\n result = m.execute(line=\"\", cell=\"PRAGMA version\")\n assert result is not None\ndef test_cn_file():\n # Not expected to occur, but should gracefully handle\n ipshell = Interactive...
from IPython.terminal.embed import InteractiveShellEmbed from magic_duckdb import duckdb_mode def create_shell() -> object: ipshell = InteractiveShellEmbed() ipshell.run_cell("%load_ext magic_duckdb") return ipshell def test_types(): # Not expected to occur, but should gracefully handle ipshell ...
if "draw" not in e: er = ipshell.run_cell(f"%dql -e {e} select * from range(10)") assert er.error_in_exec is None o = er.result assert o is not None
{ "context_start_lineno": 0, "file": "tests/test_types.py", "groundtruth_start_lineno": 30, "repository": "iqmo-org-magic_duckdb-62e6fcc", "right_context_start_lineno": 31, "task_id": "project_cc_python/4701" }
{ "list": [ { "filename": "tests/test_connections.py", "retrieved_chunk": " assert len(df) == 1\n assert df.at[0, \"file\"].endswith(filename)\ndef test_co_file():\n # Not expected to occur, but should gracefully handle\n ipshell = InteractiveShellEmbed()\n m = DuckDbMagic(shell=ipshell...
DuckDbMode.explain_functions:
{ "list": [ { "filename": "magic_duckdb/autocomplete/autocompletion_v2.py", "retrieved_chunk": " # if ends in a period, checks to see if prefix is a tablename, and if so, returns column names\n # otherwise returns all sql phrases and tablenames\n # https://github.com/ipython/ipyth...
import duckdb from pandas import DataFrame import numpy as np from magic_duckdb import magic from magic_duckdb.autocomplete.autocompletion_v2 import DqlCustomCompleter from types import SimpleNamespace def test_simple_autocomplete(): with duckdb.connect() as con: con.execute( "CREATE TABLE IF ...
results = [sc.text for sc in r["completions"]] assert results is not None assert "SELECT" in results event = SimpleNamespace( token="from", full_text="%dql select * from ", ) r = completer.line_completer(event) results = [sc.text for sc i...
{ "context_start_lineno": 0, "file": "tests/test_autocomplete.py", "groundtruth_start_lineno": 44, "repository": "iqmo-org-magic_duckdb-62e6fcc", "right_context_start_lineno": 45, "task_id": "project_cc_python/4699" }
{ "list": [ { "filename": "magic_duckdb/autocomplete/common.py", "retrieved_chunk": "]\npragma_phrases = [\n \"PRAGMA version\",\n \"PRAGMA database_list\",\n \"PRAGMA database_size\",\n \"PRAGMA show_tables\",\n \"PRAGMA show_tables_expanded\",\n \"PRAGMA table_info('\",\n \"PRAG...
line_completer(event)
{ "list": [ { "filename": "jax/internal/camera_utils.py", "retrieved_chunk": " far: float,\n xnp: types.ModuleType) -> utils.Rays:\n \"\"\"Generates a spherical camera ray batch.\"\"\"\n theta_vals = xnp.linspace(0, 2 * xnp.pi, width + 1)\n phi_vals = x...
# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
if __name__ == '__main__': absltest.main()
{ "context_start_lineno": 0, "file": "jax/tests/ref_utils_test.py", "groundtruth_start_lineno": 82, "repository": "ZX-Yin-ms-nerf-9009137", "right_context_start_lineno": 83, "task_id": "project_cc_python/4666" }
{ "list": [ { "filename": "jax/internal/camera_utils.py", "retrieved_chunk": " xnp.sin(phi) * xnp.cos(theta),\n ],\n axis=-1)\n # For jax, need to specify high-precision matmul.\n matmul = math.matmul if xnp == jnp else xnp.matmul\n directions = matmul(camtoworld[:3, :...
any(jnp.isnan(de)))
{ "list": [ { "filename": "mmllama/datasets/prompter.py", "retrieved_chunk": " f\"Using prompt template {template_name}: {self.template['description']}\"\n )\n def generate_prompt(\n self,\n instruction: str,\n input: Union[None, str] = None,\n ...
import argparse import torch from mmengine.config import Config, DictAction from mmengine.logging import print_log from transformers import LlamaTokenizer from mmllama.datasets import Prompter from mmllama.registry import MODELS def parse_args(): parser = argparse.ArgumentParser( description='MMDet test...
inputs = tokenizer(prompt, return_tensors='pt') input_ids = inputs['input_ids'].to('cuda') model.model.test_cfg.temperature=temperature model.model.test_cfg.top_k=top_k model.model.test_cfg.max_new_tokens=max_new_tokens # TODO: beam search with torch.no_grad(): ...
{ "context_start_lineno": 0, "file": "tools/generate.py", "groundtruth_start_lineno": 72, "repository": "RangiLyu-llama.mmengine-1887d56", "right_context_start_lineno": 73, "task_id": "project_cc_python/4703" }
{ "list": [ { "filename": "mmllama/datasets/prompter.py", "retrieved_chunk": " if not template_name:\n # Enforce the default here, so the constructor can be called with '' and will not break.\n template_name = 'alpaca'\n file_name = osp.join('templates', f'{template...
generate_prompt(instruction, input)
{ "list": [ { "filename": "jax/internal/ref_utils.py", "retrieved_chunk": " dot(v, n) = dot(u, n), and dot(u, u) = dot(v, v). The solution to these two\n equations is u = 2 dot(n, v) n - v.\n Args:\n viewdirs: [..., 3] array of view directions.\n normals: [..., 3] array of normal directions (...
# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
cos_angle_reflected = jnp.sum(reflected_directions * normals, axis=-1) np.testing.assert_allclose( cos_angle_original, cos_angle_reflected, atol=1E-5, rtol=1E-5) def test_spherical_harmonics(self): """Make sure the fast spherical harmonics are accurate.""" shape = (12, 11, 13) # ...
{ "context_start_lineno": 0, "file": "jax/tests/ref_utils_test.py", "groundtruth_start_lineno": 54, "repository": "ZX-Yin-ms-nerf-9009137", "right_context_start_lineno": 55, "task_id": "project_cc_python/4659" }
{ "list": [ { "filename": "jax/tests/stepfun_test.py", "retrieved_chunk": " v_batch = stepfun.resample(t, tp, vp, use_avg=use_avg)\n v_indiv = []\n for i in range(t.shape[0]):\n v_indiv.append(\n jnp.array([\n stepfun.resample(t[i, j], tp[i, j], vp[i, j], use_avg=us...
sum(directions * normals, axis=-1)
{ "list": [ { "filename": "mmllama/models/llama.py", "retrieved_chunk": " # Enable model parallelism\n shift_labels = shift_labels.to(shift_logits.device)\n loss = loss_fct(shift_logits, shift_labels)\n return dict(loss=loss)\n @torch.no_grad()\n def predict(self, inp...
import argparse import torch from mmengine.config import Config, DictAction from mmengine.logging import print_log from transformers import LlamaTokenizer from mmllama.datasets import Prompter from mmllama.registry import MODELS def parse_args(): parser = argparse.ArgumentParser( description='MMDet test...
if args.instructions is not None: instructions = args.instructions else: instructions = [ 'Tell me about alpacas.', 'Tell me about the president of Mexico in 2019.', 'Tell me about the king of France in 2019.', 'List all Canadian provinces in alphabetical order....
{ "context_start_lineno": 0, "file": "tools/generate.py", "groundtruth_start_lineno": 83, "repository": "RangiLyu-llama.mmengine-1887d56", "right_context_start_lineno": 84, "task_id": "project_cc_python/4704" }
{ "list": [ { "filename": "mmllama/models/llama.py", "retrieved_chunk": " empty = torch.empty(B, T_new, dtype=input_ids.dtype, device=input_ids.device)\n empty[:, :T] = input_ids\n input_ids = empty\n max_seq_length = self.block_size\n # generate max_new_tokens token...
get_response(output)
{ "list": [ { "filename": "jax/tests/render_test.py", "retrieved_chunk": " np.testing.assert_allclose(\n jax.vmap(jax.vmap(jnp.diag))(cov), cov_diag, atol=1E-5, rtol=1E-5)\n def test_rotated_conic_frustums(self):\n # Test that conic frustum Gaussians are closed under rotation.\n diag ...
# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
phi = random.uniform(key2, shape, minval=0.0, maxval=2.0*jnp.pi) # Convert to Cartesian coordinates. x = jnp.sin(theta) * jnp.cos(phi) y = jnp.sin(theta) * jnp.sin(phi) z = jnp.cos(theta) xyz = jnp.stack([x, y, z], axis=-1) deg_view = 5 de = ref_utils.generate_dir_enc_fn(deg_view)(xyz...
{ "context_start_lineno": 0, "file": "jax/tests/ref_utils_test.py", "groundtruth_start_lineno": 67, "repository": "ZX-Yin-ms-nerf-9009137", "right_context_start_lineno": 68, "task_id": "project_cc_python/4660" }
{ "list": [ { "filename": "jax/tests/render_test.py", "retrieved_chunk": " i_results = []\n for i_t0, i_t1 in zip(t0, t1):\n key, rng = random.split(rng)\n i_results.append(\n conical_frustum_to_gaussian_sample(key, raydir, i_t0, i_t1, r))\n mean_gt, cov_gt = [j...
uniform(key1, shape, minval=0.0, maxval=jnp.pi)
{ "list": [ { "filename": "jax/tests/coord_test.py", "retrieved_chunk": " def test_construct_ray_warps_special_reciprocal(self):\n \"\"\"Test fn=1/x against its closed form.\"\"\"\n n = 100\n rng = random.PRNGKey(0)\n key, rng = random.split(rng)\n t_near = jnp.exp(jax.random.normal(ke...
# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
key, rng = random.split(rng) mat1 = jax.random.normal(key, [num_dims, num_points]) sq_dist = geopoly.compute_sq_dist(mat0, mat1) sq_dist_ref = np.zeros([num_points, num_points]) for i in range(num_points): for j in range(num_points): sq_dist_ref[i, j] = np.sum((mat0[:, i] - mat1[:, ...
{ "context_start_lineno": 0, "file": "jax/tests/geopoly_test.py", "groundtruth_start_lineno": 41, "repository": "ZX-Yin-ms-nerf-9009137", "right_context_start_lineno": 42, "task_id": "project_cc_python/4650" }
{ "list": [ { "filename": "jax/tests/stepfun_test.py", "retrieved_chunk": " key, rng = random.split(rng)\n d0, d1 = random.randint(key, [2], minval=10, maxval=20)\n key, rng = random.split(rng)\n t0 = jnp.sort(random.uniform(key, [d0 + 1]), axis=-1)\n key, rng = random.split(r...
random.normal(key, [num_dims, num_points])
{ "list": [ { "filename": "Solver/MCMCSolver.py", "retrieved_chunk": " self.device = torch.device('cuda')\n self.model = model.to(self.device)\n self.sampler = sampler\n def train(self,\n loader: DataLoader,\n total_epoch=2000,\n lr=1e-4,\...
from Solver import MCMCSolver from sampler import EnergyBasedLangevinDynamicSampler from data import get_CIFAR10_train, get_CIFAR10_test from models import UnconditionalResNet32 import torch from torchvision import transforms to_img = transforms.ToPILImage() loader = get_CIFAR10_train(batch_size=256) model = Uncondit...
print(model(x.cuda()).sum(), x.shape) # x = torch.rand(1, 3, 32, 32).cuda() print(model(x.cuda()).sum()) x = sampler.sample(x, step=600) print(model(x.cuda()).sum(), x.shape) x = to_img(x[0].squeeze()) x.save('test.png')
{ "context_start_lineno": 0, "file": "main.py", "groundtruth_start_lineno": 25, "repository": "huanranchen-EnergyBasedGenerativeModel-ad5989a", "right_context_start_lineno": 26, "task_id": "project_cc_python/4637" }
{ "list": [ { "filename": "Solver/MCMCSolver.py", "retrieved_chunk": " self.buffer = torch.rand(64, *self.sampler.img_size, device=self.device)\n optimizer = torch.optim.Adam(self.model.parameters(), lr=lr)\n for epoch in range(1, total_epoch + 1):\n pbar = tqdm(loader)...
sample(x, step=600)
{ "list": [ { "filename": "codegen/model.py", "retrieved_chunk": " # construct prompt\n message = (\n f\"Please complete the following code snippet.\\n```\\n{prompt.strip()}\\n```\"\n )\n config = create_chatgpt_config(\n message=message,\n ...
import ast import os import random from typing import Dict, List import openai from evalplus.data import to_raw from evalplus.gen import BaseGen from evalplus.gen.util import trusted_check_exec from evalplus.gen.util.api_request import create_chatgpt_config, request_chatgpt_engine class ChatGPTGen(BaseGen): def...
seeds = self.seed_selection() new_inputs = self.chatgpt_generate(seeds) for new_input in new_inputs: if hash(str(new_input)) not in self.seed_hash: if trusted_check_exec(self.contract, [new_input], self.entry_point): self.s...
{ "context_start_lineno": 0, "file": "evalplus/gen/chatgpt_gen.py", "groundtruth_start_lineno": 62, "repository": "evalplus-evalplus-8b713cd", "right_context_start_lineno": 63, "task_id": "project_cc_python/4589" }
{ "list": [ { "filename": "codegen/model.py", "retrieved_chunk": " model=self.model_name,\n )\n ret = request_chatgpt_engine(config)\n return self._chatgpt_parse(ret, prompt.strip())\nclass IncoderDecoder(HFTorchDecoder):\n def __init__(\n self, name: str, bat...
new_inputs) < num and self.iteration >= 0:
{ "list": [ { "filename": "MAESC_training_for_generated_dual_prompts_multitasks_Aspect.py", "retrieved_chunk": " best_dev_res = None\n best_dev_test_res = None\n best_test_res = None\n # res_dev = eval_utils.eval(model, dev_loader, metric, device)\n while epoch < args.epochs:\n l...
from datetime import datetime import numpy as np from torch.cuda.amp import autocast import src.model.utils as utils import src.eval_utils as eval_utils # from src.utils import TaskType import torch def pretrain(task_list, epoch, model, train_loaders, optimizer_dict...
utils.set_lr(optimizer, liner_warm_rate * args.lr) optimizer.zero_grad() loss.backward() utils.clip_gradient(optimizer, args.grad_clip) optimizer.step()
{ "context_start_lineno": 0, "file": "src/training_multitasks.py", "groundtruth_start_lineno": 162, "repository": "YangXiaocui1215-GMP-d3cb04f", "right_context_start_lineno": 163, "task_id": "project_cc_python/4644" }
{ "list": [ { "filename": "src/eval_utils_multitasks.py", "retrieved_chunk": " metric.evaluate(aesc_infos['spans'], predict,\n aesc_infos['labels'].to(device))\n # break\n aspects_num_eval_acc = num_correct/len(loader.dataset)\n res = metric.get_metric()\n ...
liner_warmup(cur_step, t_step, args.warmup)
{ "list": [ { "filename": "evalplus/gen/type_mut.py", "retrieved_chunk": " str: set(),\n }\n for x in inputs:\n self.fetch_ingredient(x)\n def seed_selection(self):\n # random for now.\n return random.choice(self.seed_pool)\n def mutate(self, see...
import random from abc import abstractmethod from typing import Any, List from evalplus.gen import BaseGen from evalplus.gen.util import trusted_check_exec class MutateGen(BaseGen): def __init__(self, inputs: List, signature: str, contract_code: str): super().__init__(inputs, signature, contract_code) ...
seed = self.seed_selection() new_input = self.mutate(seed) if hash(str(new_input)) not in self.seed_hash: if trusted_check_exec(self.contract, [new_input], self.entry_point): self.seed_pool.append(new_input) self.seed_hash.add(...
{ "context_start_lineno": 0, "file": "evalplus/gen/mut_gen.py", "groundtruth_start_lineno": 21, "repository": "evalplus-evalplus-8b713cd", "right_context_start_lineno": 22, "task_id": "project_cc_python/4579" }
{ "list": [ { "filename": "evalplus/gen/type_mut.py", "retrieved_chunk": " str: set(),\n }\n for x in inputs:\n self.fetch_ingredient(x)\n def seed_selection(self):\n # random for now.\n return random.choice(self.seed_pool)\n def mutate(self, see...
new_inputs) < num:
{ "list": [ { "filename": "MAESC_training_for_generated_dual_prompts_multitasks_Aspect.py", "retrieved_chunk": " best_dev_res = None\n best_dev_test_res = None\n best_test_res = None\n # res_dev = eval_utils.eval(model, dev_loader, metric, device)\n while epoch < args.epochs:\n l...
from datetime import datetime import numpy as np from torch.cuda.amp import autocast import src.model.utils as utils import src.eval_utils as eval_utils # from src.utils import TaskType import torch def pretrain(task_list, epoch, model, train_loaders, optimizer_dict...
optimizer.zero_grad() loss.backward() utils.clip_gradient(optimizer, args.grad_clip) optimizer.step()
{ "context_start_lineno": 0, "file": "src/training_multitasks.py", "groundtruth_start_lineno": 163, "repository": "YangXiaocui1215-GMP-d3cb04f", "right_context_start_lineno": 164, "task_id": "project_cc_python/4645" }
{ "list": [ { "filename": "MAESC_training_for_generated_dual_prompts_multitasks_Aspect.py", "retrieved_chunk": " metric=metric,\n optimizer=optimizer,\n args=args,\n device=device,\n logger=logger,\n ...
set_lr(optimizer, liner_warm_rate * args.lr)
{ "list": [ { "filename": "evalplus/_experimental/type_mut_for_eff.py", "retrieved_chunk": " # @dispatch(set)\n # def typed_fetch(self, seed_input: Set):\n # self._fetch_list_like(seed_input)\n # Dict\n @dispatch(dict)\n def typed_fetch(self, seed_input: Dict):\n self._fet...
import copy import random import string import time from typing import Any, Dict, List, Set, Tuple from multipledispatch import dispatch from evalplus.gen.mut_gen import MutateGen from evalplus.gen.util import trusted_check_exec MAX_MULTI_STEP_SIZE = 5 MUTATE_BOUND_SIZE = 8 NoneType = type(None) # decorator to us...
if num_generated % 1000 == 0: print( f"generated {num_generated} already with {len(self.new_inputs)} new inputs ... " ) new_input = self.seed_selection() # Multi-step instead of single-step for _ in range(random.randint...
{ "context_start_lineno": 0, "file": "evalplus/gen/type_mut.py", "groundtruth_start_lineno": 309, "repository": "evalplus-evalplus-8b713cd", "right_context_start_lineno": 310, "task_id": "project_cc_python/4584" }
{ "list": [ { "filename": "evalplus/_experimental/type_mut_for_eff.py", "retrieved_chunk": " def concat(x: int, y: int):\n return x + y\n @dispatch(float, float)\n def concat(x: float, y: float):\n return x + y\n @dispatch(bool, bool)\n def concat(x: bool, y: bool):\n ...
new_inputs) < num and time.time() - start < self.timeout:
{ "list": [ { "filename": "MAESC_training_for_generated_dual_prompts_multitasks_Aspect.py", "retrieved_chunk": " pad_token_id=eos_token_id,\n restricter=None)\n # model = MultiModalBartModel_AESC(bart_config, args.bart_...
from datetime import datetime import numpy as np from torch.cuda.amp import autocast import src.model.utils as utils import src.eval_utils as eval_utils # from src.utils import TaskType import torch def pretrain(task_list, epoch, model, train_loaders, optimizer_dict...
optimizer.step()
{ "context_start_lineno": 0, "file": "src/training_multitasks.py", "groundtruth_start_lineno": 168, "repository": "YangXiaocui1215-GMP-d3cb04f", "right_context_start_lineno": 169, "task_id": "project_cc_python/4646" }
{ "list": [ { "filename": "MAESC_training_for_generated_dual_prompts_multitasks_Aspect.py", "retrieved_chunk": " logger.info('Loading data...')\n collate_aesc = Collator(\n args.task,\n tokenizer,\n mlm_enabled=Fals...
clip_gradient(optimizer, args.grad_clip)
{ "list": [ { "filename": "evalplus/data/__init__.py", "retrieved_chunk": " return plus\ndef get_human_eval() -> Dict[str, Dict]:\n \"\"\"Get HumanEval from OpenAI's github repo and return as a list of parsed dicts.\n Returns:\n List[Dict[str, str]]: List of dicts with keys \"prompt\",...
import ast import os import random from typing import Dict, List import openai from evalplus.data import to_raw from evalplus.gen import BaseGen from evalplus.gen.util import trusted_check_exec from evalplus.gen.util.api_request import create_chatgpt_config, request_chatgpt_engine class ChatGPTGen(BaseGen): def...
@staticmethod def _parse_ret(ret: Dict) -> List: rets = [] output = ret["choices"][0]["message"]["content"] if "```" in output: for x in output.split("```")[1].splitlines(): if x.strip() == "": continue try: ...
{ "context_start_lineno": 0, "file": "evalplus/gen/chatgpt_gen.py", "groundtruth_start_lineno": 27, "repository": "evalplus-evalplus-8b713cd", "right_context_start_lineno": 28, "task_id": "project_cc_python/4588" }
{ "list": [ { "filename": "evalplus/data/__init__.py", "retrieved_chunk": " \"\"\"\n # Check if human eval file exists in CACHE_DIR\n human_eval_path = os.path.join(CACHE_DIR, \"HumanEval.jsonl\")\n human_eval = None\n if not os.path.exists(human_eval_path):\n # Install HumanEval...
seed_pool, k=min(len(self.seed_pool), 5))
{ "list": [ { "filename": "codegen/generate.py", "retrieved_chunk": " log += f\" (resuming from {n_existing})\"\n nsamples = args.n_samples - n_existing\n p.console.print(log)\n sidx = args.n_samples - nsamples\n while sidx < args.n_sample...
import json import os import pickle from os import PathLike from typing import List import matplotlib.pyplot as plt import numpy as np from tqdm import tqdm from evalplus.eval import estimate_pass_at_k SMALL_SIZE = 10 MEDIUM_SIZE = 14 BIGGER_SIZE = 18 plt.rc("font", size=SMALL_SIZE) # controls default text sizes p...
pass_at_k_new = estimate_pass_at_k(ntotal, npass_new, k).mean() * 100 d_old.setdefault(k, []).append(pass_at_k_old) d_new.setdefault(k, []).append(pass_at_k_new) for nsamples in passk_old: print("=====================================") print(f"{nsamp...
{ "context_start_lineno": 0, "file": "tools/viz_passrate.py", "groundtruth_start_lineno": 59, "repository": "evalplus-evalplus-8b713cd", "right_context_start_lineno": 60, "task_id": "project_cc_python/4593" }
{ "list": [ { "filename": "codegen/generate.py", "retrieved_chunk": " num_samples=args.n_samples - sidx,\n )\n for impl in outputs:\n try:\n with open(\n os.path.join(workdir, p_name, ...
mean() * 100
{ "list": [ { "filename": "nn/models/epd.py", "retrieved_chunk": " def predict(self, features: clrs.Features) -> Result:\n self.net_.eval()\n raw_preds, aux = self.net_(features)\n preds = decoders.postprocess(raw_preds, self._spec)\n return preds, (raw_preds, aux)\n ...
import clrs import torch from nn import losses as loss from nn.models.impl import _dimensions, _bfs_op_mask, _expand_to, \ _get_fts, _hints_i, _own_hints_i, _reset_hints from nn.models.impl import decoders from nn.models.epd import EncodeProcessDecode_Impl as Net from random import random from typing import Calla...
return preds, (raw_preds, aux) @torch.no_grad() def verbose_loss(self, feedback: _Feedback, preds, aux_preds): losses = {} total_loss = 0 n_hints = 0 for truth in feedback.features.hints: if self.no_feats(truth.name): continue n_...
{ "context_start_lineno": 0, "file": "nn/models/mf_net.py", "groundtruth_start_lineno": 105, "repository": "danilonumeroso-dar-64e8631", "right_context_start_lineno": 106, "task_id": "project_cc_python/4716" }
{ "list": [ { "filename": "nn/models/mf_net_pipeline.py", "retrieved_chunk": " raw_preds, aux = self.net_(features)\n preds = decoders.postprocess(raw_preds, self._spec)\n return preds, (raw_preds, aux)\n @torch.no_grad()\n def verbose_loss(self, feedback: _Feedback, preds, ...
postprocess(raw_preds, self.spec)
{ "list": [ { "filename": "nn/models/mf_net_pipeline.py", "retrieved_chunk": " dummy_trajectory,\n num_hidden,\n encode_hints,\n decode_hints,\n processor,\n ...
import clrs import torch from nn import losses as loss from nn.models.impl import _dimensions, _bfs_op_mask, _expand_to, \ _get_fts, _hints_i, _own_hints_i, _reset_hints from nn.models.impl import decoders from nn.models.epd import EncodeProcessDecode_Impl as Net from random import random from typing import Calla...
self.is_annealing_enabled = annealing self.annealing_state = 0 self.device = device self.spec = spec self.encode_hints = encode_hints self.to(device) self.hiddens = None def op(self, trajectories, h_bfs, adj, is_bfs_op): _, h_bfs, h_preds_bfs = sel...
{ "context_start_lineno": 0, "file": "nn/models/mf_net.py", "groundtruth_start_lineno": 166, "repository": "danilonumeroso-dar-64e8631", "right_context_start_lineno": 167, "task_id": "project_cc_python/4717" }
{ "list": [ { "filename": "nn/models/mf_net_pipeline.py", "retrieved_chunk": " dummy_trajectory,\n num_hidden,\n encode_hints,\n decode_hints,\n processor,\n ...
encoders['c_h']
{ "list": [ { "filename": "nn/models/mf_net.py", "retrieved_chunk": " self.no_feats = lambda x: x in no_feats or x.startswith('__') # noqa\n self.bfs_net = Net(spec, dummy_trajectory, num_hidden,\n encode_hints, decode_hints,\n process...
import clrs import torch from nn import losses as loss from nn.models.impl import _dimensions, _bfs_op_mask, _expand_to, \ _get_fts, _hints_i, _own_hints_i, _reset_hints from nn.models.impl import decoders from nn.models.epd import EncodeProcessDecode_Impl as Net from random import random from typing import Calla...
self.mincut_net = Net( spec, dummy_trajectory, num_hidden, encode_hints=False, decode_hints=False, processor=processor, aggregator=aggregator, max_steps=c.data.shape[2] + 1, ...
{ "context_start_lineno": 0, "file": "nn/models/mf_net_pipeline.py", "groundtruth_start_lineno": 174, "repository": "danilonumeroso-dar-64e8631", "right_context_start_lineno": 175, "task_id": "project_cc_python/4728" }
{ "list": [ { "filename": "nn/models/mf_net.py", "retrieved_chunk": " device=device)\n del self.bfs_net.encoders['c_h']\n self.is_annealing_enabled = annealing\n self.annealing_state = 0\n self.device = device\n self.spec = spec\n se...
data.shape[2])
{ "list": [ { "filename": "nn/models/epd.py", "retrieved_chunk": " encode_hints=encode_hints,\n decode_hints=decode_hints,\n processor=processor,\n ...
import clrs import os import torch import typer from config.hyperparameters import HP_SPACE from functools import partial from nn.models import EncodeProcessDecode, MF_Net, MF_NetPipeline from pathlib import Path from statistics import mean, stdev from utils.data import load_dataset from utils.experiments import evalu...
preds, aux = model.predict(features) for key in preds: preds[key].data = preds[key].data.cpu() metrics = {} for truth in feedback.outputs: type_ = preds[truth.name].type_ y_pred = preds[truth.name].data.numpy() y_true = truth.data.numpy(...
{ "context_start_lineno": 0, "file": "run.py", "groundtruth_start_lineno": 202, "repository": "danilonumeroso-dar-64e8631", "right_context_start_lineno": 203, "task_id": "project_cc_python/4705" }
{ "list": [ { "filename": "nn/models/epd.py", "retrieved_chunk": " self.no_feats = lambda x: x in no_feats or x.startswith('__')\n self.encode_hints = encode_hints\n self.decode_hints = decode_hints\n def dump_model(self, path):\n torch.save(self.net_.state_dict(), path)...
restore_model(test_path / f'trial_{i}' / 'model_0.pth', 'cuda')
{ "list": [ { "filename": "nn/models/epd.py", "retrieved_chunk": " encode_hints=encode_hints,\n decode_hints=decode_hints,\n processor=processor,\n ...
import clrs import torch from nn import losses as loss from nn.models.impl import _dimensions, _bfs_op_mask, _expand_to, \ _get_fts, _hints_i, _own_hints_i, _reset_hints from nn.models.impl import decoders from nn.models.epd import EncodeProcessDecode_Impl as Net from random import random from typing import Calla...
del self.flow_net.hint_decoders['c_h'] del self.bfs_net.hint_decoders['c_h'] del self.mincut_net.decoders['f'] self.is_annealing_enabled = annealing self.annealing_state = 0 self.device = device self.spec = spec self.encode_hints = encode_hin...
{ "context_start_lineno": 0, "file": "nn/models/mf_net_pipeline.py", "groundtruth_start_lineno": 187, "repository": "danilonumeroso-dar-64e8631", "right_context_start_lineno": 188, "task_id": "project_cc_python/4729" }
{ "list": [ { "filename": "nn/models/mf_net.py", "retrieved_chunk": " device=device)\n del self.bfs_net.encoders['c_h']\n self.is_annealing_enabled = annealing\n self.annealing_state = 0\n self.device = device\n self.spec = spec\n se...
decoders['c']
{ "list": [ { "filename": "nn/models/mf_net.py", "retrieved_chunk": " self.no_feats = lambda x: x in no_feats or x.startswith('__') # noqa\n self.bfs_net = Net(spec, dummy_trajectory, num_hidden,\n encode_hints, decode_hints,\n process...
import clrs import torch from nn import losses as loss from nn.models.impl import _dimensions, _bfs_op_mask, _expand_to, \ _get_fts, _hints_i, _own_hints_i, _reset_hints from nn.models.impl import decoders from nn.models.epd import EncodeProcessDecode_Impl as Net from random import random from typing import Calla...
del self.bfs_net.hint_decoders['c_h'] del self.mincut_net.decoders['f'] self.is_annealing_enabled = annealing self.annealing_state = 0 self.device = device self.spec = spec self.encode_hints = encode_hints self.to(device) def op(self, trajec...
{ "context_start_lineno": 0, "file": "nn/models/mf_net_pipeline.py", "groundtruth_start_lineno": 188, "repository": "danilonumeroso-dar-64e8631", "right_context_start_lineno": 189, "task_id": "project_cc_python/4730" }
{ "list": [ { "filename": "nn/models/mf_net.py", "retrieved_chunk": " device=device)\n del self.bfs_net.encoders['c_h']\n self.is_annealing_enabled = annealing\n self.annealing_state = 0\n self.device = device\n self.spec = spec\n se...
hint_decoders['c_h']
{ "list": [ { "filename": "code_genie/pipeline.py", "retrieved_chunk": " # there should be atleast 1 sink\n if all(step.sink is None for step in v):\n raise ValueError(\"atleast one of the steps should have a sink; none found\")\n return v\n def _get_filepath(self, f...
import os import pandas as pd import pytest from code_genie import Genie from code_genie.io import IntArg, StringArg from code_genie.io.local import CsvToDataFrameSource, DataFrameToCsvSink from code_genie.pipeline import GeniePipeline, PipelineStep @pytest.fixture(scope="module") def pipeline_cache_dir() -> str: ...
assert pipeline_imported == pipeline # now we will run this pipeline with a new df and multiplier and check results sink_path = os.path.join(pipeline_cache_dir, "data", "df_eval_result.csv") pipeline_imported.run({source_path_key: df_eval_path, multiplier_key: 5, sink_path_key: sink_path}) # read...
{ "context_start_lineno": 0, "file": "tests/test_pipeline.py", "groundtruth_start_lineno": 72, "repository": "thismlguy-code-genie-58f789c", "right_context_start_lineno": 73, "task_id": "project_cc_python/4684" }
{ "list": [ { "filename": "code_genie/pipeline.py", "retrieved_chunk": " steps: List[PipelineStep]\n \"\"\"List of steps in the pipeline\"\"\"\n def add(self, step: PipelineStep):\n \"\"\"Add a step to the pipeline\"\"\"\n return self.copy(update={\"steps\": self.steps + [step]}...
load(os.path.join(pipeline_cache_dir, "test-pipe.json"))
{ "list": [ { "filename": "code_genie/pipeline.py", "retrieved_chunk": " # there should be atleast 1 sink\n if all(step.sink is None for step in v):\n raise ValueError(\"atleast one of the steps should have a sink; none found\")\n return v\n def _get_filepath(self, f...
import os import pandas as pd import pytest from code_genie import Genie from code_genie.io import IntArg, StringArg from code_genie.io.local import CsvToDataFrameSource, DataFrameToCsvSink from code_genie.pipeline import GeniePipeline, PipelineStep @pytest.fixture(scope="module") def pipeline_cache_dir() -> str: ...
pipeline_imported = GeniePipeline.load(os.path.join(pipeline_cache_dir, "test-pipe.json")) assert pipeline_imported == pipeline # now we will run this pipeline with a new df and multiplier and check results sink_path = os.path.join(pipeline_cache_dir, "data", "df_eval_result.csv") pipeline_import...
{ "context_start_lineno": 0, "file": "tests/test_pipeline.py", "groundtruth_start_lineno": 70, "repository": "thismlguy-code-genie-58f789c", "right_context_start_lineno": 71, "task_id": "project_cc_python/4683" }
{ "list": [ { "filename": "code_genie/pipeline.py", "retrieved_chunk": " steps: List[PipelineStep]\n \"\"\"List of steps in the pipeline\"\"\"\n def add(self, step: PipelineStep):\n \"\"\"Add a step to the pipeline\"\"\"\n return self.copy(update={\"steps\": self.steps + [step]}...
export("test-pipe.json")
{ "list": [ { "filename": "tests/test_genie.py", "retrieved_chunk": " genie = Genie(data=df, client=client)\n # call the method\n assert genie.plz(instructions=\"sum of mean of x and y\").result == 7\n assert set(genie.plz(instructions=\"distinct values of x\").result) == {1, 2, 3}\ndef te...
import os import pandas as pd import pytest from code_genie import Genie from code_genie.io import IntArg, StringArg from code_genie.io.local import CsvToDataFrameSource, DataFrameToCsvSink from code_genie.pipeline import GeniePipeline, PipelineStep @pytest.fixture(scope="module") def pipeline_cache_dir() -> str: ...
genie = Genie(data=gr_grp.result, cache_dir=pipeline_cache_dir, client=client) gr_mul = genie.plz("multiply values of x by multiplier", additional_inputs={"multiplier": multiplier}) result_values = gr_mul.result.reset_index().set_index("y")["x"].to_dict() assert result_values == {"a": 3.0 * multiplier,...
{ "context_start_lineno": 0, "file": "tests/test_pipeline.py", "groundtruth_start_lineno": 45, "repository": "thismlguy-code-genie-58f789c", "right_context_start_lineno": 46, "task_id": "project_cc_python/4682" }
{ "list": [ { "filename": "tests/test_genie.py", "retrieved_chunk": " assert genie.plz(instructions=\"add all inputs\").result == 60\n assert genie.plz(instructions=\"multiply all inputs\").result == 6000\ndef test_math_additional_inputs(client):\n # use genie to get a method to add 2 numbers...
plz("create a df with mean values of x grouped by y")
{ "list": [ { "filename": "tests/test_pipeline.py", "retrieved_chunk": " multiplier = 2\n gr_grp = genie.plz(\"create a df with mean values of x grouped by y\")\n genie = Genie(data=gr_grp.result, cache_dir=pipeline_cache_dir, client=client)\n gr_mul = genie.plz(\"multiply values of x by m...
import pandas as pd import pytest from code_genie import Genie @pytest.fixture(scope="session") def df(): return pd.DataFrame({"x": [1, 2, 3, 1, 2, 3], "y": [4, 5, 6, 4, 5, 6]}) def test_math(client): # use genie to get a method to add 2 numbers genie = Genie(data=[10, 20, 30], client=client) # ca...
def test_cache(client): # use genie to get a method to add 2 numbers genie = Genie(data=[1, 2, 3, 4], client=client) # call the method gr_1 = genie.plz(instructions="add all elements of input") assert gr_1.result == 10 gr_2 = genie.plz(instructions="add all elements of input") assert gr...
{ "context_start_lineno": 0, "file": "tests/test_genie.py", "groundtruth_start_lineno": 46, "repository": "thismlguy-code-genie-58f789c", "right_context_start_lineno": 47, "task_id": "project_cc_python/4686" }
{ "list": [ { "filename": "tests/test_pipeline.py", "retrieved_chunk": " source = CsvToDataFrameSource(path=StringArg(name=source_path_key))\n sink = DataFrameToCsvSink(path=StringArg(name=sink_path_key))\n steps = [\n PipelineStep(\n genie_result=gr_grp,\n data=s...
custom(code=code).result) == {1, 2, 3}
{ "list": [ { "filename": "app.py", "retrieved_chunk": " for download_file in download:\n # Get file name from lookup\n zip_file_name = zip_file_lookup.get(download_file, os.path.basename(download_file))\n ...
import argparse import os import pathlib from urllib.parse import urlparse import warnings import numpy as np import threading import torch from app import VadOptions, WhisperTranscriber from src.config import VAD_INITIAL_PROMPT_MODE_VALUES, ApplicationConfig, VadInitialPromptMode from src.download import download_url...
taskArgs = dict(args) taskArgs["task"] = model_task["task"] result = transcriber.transcribe_file(model, source_path, temperature=temperature, vadOptions=vadOptions, **taskArgs) transcriber.write_result(result, source_name, output_dir, hig...
{ "context_start_lineno": 0, "file": "cli.py", "groundtruth_start_lineno": 198, "repository": "Cerlancism-faster-whisper-webui-884f5fd", "right_context_start_lineno": 199, "task_id": "project_cc_python/4745" }
{ "list": [ { "filename": "app.py", "retrieved_chunk": " print(\"Deleting source file \" + source.source_path)\n try:\n os.remove(source.source_path)\n except Exception as e:\n # ...
from_string(vad_initial_prompt_mode))
{ "list": [ { "filename": "app.py", "retrieved_chunk": " # Set default initial prompt mode\n if (initial_prompt_mode is None):\n initial_prompt_mode = VadInitialPromptMode.PREPREND_FIRST_SEGMENT\n if (initial_prompt_mode == VadInitialPromptMode.PREPEND_ALL_SEGMENTS or \...
from src.config import VadInitialPromptMode from src.prompts.abstractPromptStrategy import AbstractPromptStrategy class PrependPromptStrategy(AbstractPromptStrategy): """ A simple prompt strategy that prepends a single prompt to all segments of audio, or prepends the prompt to the first segment of audio. "...
raise ValueError(f"Unsupported initial prompt mode {initial_prompt_mode}") def get_segment_prompt(self, segment_index: int, whisper_prompt: str, detected_language: str) -> str: if (self.initial_prompt_mode == VadInitialPromptMode.PREPEND_ALL_SEGMENTS): return self._concat_prompt(se...
{ "context_start_lineno": 0, "file": "src/prompts/prependPromptStrategy.py", "groundtruth_start_lineno": 21, "repository": "Cerlancism-faster-whisper-webui-884f5fd", "right_context_start_lineno": 22, "task_id": "project_cc_python/4759" }
{ "list": [ { "filename": "app.py", "retrieved_chunk": " else:\n raise ValueError(\"Invalid vadInitialPromptMode: \" + initial_prompt_mode)\n # Callable for processing an audio file\n whisperCallable = model.create_callback(language, task, prompt_strategy=prompt_strateg...
PREPREND_FIRST_SEGMENT]:
{ "list": [ { "filename": "app.py", "retrieved_chunk": " # Set default initial prompt mode\n if (initial_prompt_mode is None):\n initial_prompt_mode = VadInitialPromptMode.PREPREND_FIRST_SEGMENT\n if (initial_prompt_mode == VadInitialPromptMode.PREPEND_ALL_SEGMENTS or \...
from src.config import VadInitialPromptMode from src.prompts.abstractPromptStrategy import AbstractPromptStrategy class PrependPromptStrategy(AbstractPromptStrategy): """ A simple prompt strategy that prepends a single prompt to all segments of audio, or prepends the prompt to the first segment of audio. "...
elif (self.initial_prompt_mode == VadInitialPromptMode.PREPREND_FIRST_SEGMENT): return self._concat_prompt(self.initial_prompt, whisper_prompt) if segment_index == 0 else whisper_prompt else: raise ValueError(f"Unknown initial prompt mode {self.initial_prompt_mode}")
{ "context_start_lineno": 0, "file": "src/prompts/prependPromptStrategy.py", "groundtruth_start_lineno": 26, "repository": "Cerlancism-faster-whisper-webui-884f5fd", "right_context_start_lineno": 27, "task_id": "project_cc_python/4760" }
{ "list": [ { "filename": "app.py", "retrieved_chunk": " else:\n raise ValueError(\"Invalid vadInitialPromptMode: \" + initial_prompt_mode)\n # Callable for processing an audio file\n whisperCallable = model.create_callback(language, task, prompt_strategy=prompt_strateg...
_concat_prompt(self.initial_prompt, whisper_prompt)
{ "list": [ { "filename": "src/prompts/prependPromptStrategy.py", "retrieved_chunk": " raise ValueError(f\"Unsupported initial prompt mode {initial_prompt_mode}\")\n def get_segment_prompt(self, segment_index: int, whisper_prompt: str, detected_language: str) -> str:\n if (self.in...
import json from typing import Dict from src.prompts.abstractPromptStrategy import AbstractPromptStrategy class JsonPromptSegment(): def __init__(self, segment_index: int, prompt: str, format_prompt: bool = False): self.prompt = prompt self.segment_index = segment_index self.format_prompt ...
{ "context_start_lineno": 0, "file": "src/prompts/jsonPromptStrategy.py", "groundtruth_start_lineno": 48, "repository": "Cerlancism-faster-whisper-webui-884f5fd", "right_context_start_lineno": 49, "task_id": "project_cc_python/4761" }
{ "list": [ { "filename": "src/prompts/prependPromptStrategy.py", "retrieved_chunk": " raise ValueError(f\"Unsupported initial prompt mode {initial_prompt_mode}\")\n def get_segment_prompt(self, segment_index: int, whisper_prompt: str, detected_language: str) -> str:\n if (self.in...
_concat_prompt(prompt.prompt, whisper_prompt)
{ "list": [ { "filename": "src/whisper/whisperFactory.py", "retrieved_chunk": " from src.whisper.whisperContainer import WhisperContainer\n return WhisperContainer(model_name=model_name, device=device, compute_type=compute_type, download_root=download_root, cache=cache, models=models)\n ...
import argparse import os import pathlib from urllib.parse import urlparse import warnings import numpy as np import threading import torch from app import VadOptions, WhisperTranscriber from src.config import VAD_INITIAL_PROMPT_MODE_VALUES, ApplicationConfig, VadInitialPromptMode from src.download import download_url...
transcriber.set_auto_parallel(auto_parallel) if (transcriber._has_parallel_devices()): print("Using parallel devices:", transcriber.parallel_device_list) for audio_path in args.pop("audio"): sources = [] # Detect URL and download the audio if (uri_validator(audio_path)): ...
{ "context_start_lineno": 0, "file": "cli.py", "groundtruth_start_lineno": 173, "repository": "Cerlancism-faster-whisper-webui-884f5fd", "right_context_start_lineno": 174, "task_id": "project_cc_python/4741" }
{ "list": [ { "filename": "src/whisper/whisperFactory.py", "retrieved_chunk": " from src.whisper.whisperContainer import WhisperContainer\n return WhisperContainer(model_name=model_name, device=device, compute_type=compute_type, download_root=download_root, cache=cache, models=models)\n ...
set_parallel_devices(args.pop("vad_parallel_devices"))
{ "list": [ { "filename": "app.py", "retrieved_chunk": " # Set default initial prompt mode\n if (initial_prompt_mode is None):\n initial_prompt_mode = VadInitialPromptMode.PREPREND_FIRST_SEGMENT\n if (initial_prompt_mode == VadInitialPromptMode.PREPEND_ALL_SEGMENTS or \...
from src.config import VadInitialPromptMode from src.prompts.abstractPromptStrategy import AbstractPromptStrategy class PrependPromptStrategy(AbstractPromptStrategy): """ A simple prompt strategy that prepends a single prompt to all segments of audio, or prepends the prompt to the first segment of audio. "...
raise ValueError(f"Unsupported initial prompt mode {initial_prompt_mode}") def get_segment_prompt(self, segment_index: int, whisper_prompt: str, detected_language: str) -> str: if (self.initial_prompt_mode == VadInitialPromptMode.PREPEND_ALL_SEGMENTS): return self._concat_prompt(se...
{ "context_start_lineno": 0, "file": "src/prompts/prependPromptStrategy.py", "groundtruth_start_lineno": 21, "repository": "Cerlancism-faster-whisper-webui-884f5fd", "right_context_start_lineno": 22, "task_id": "project_cc_python/4758" }
{ "list": [ { "filename": "app.py", "retrieved_chunk": " else:\n raise ValueError(\"Invalid vadInitialPromptMode: \" + initial_prompt_mode)\n # Callable for processing an audio file\n whisperCallable = model.create_callback(language, task, prompt_strategy=prompt_strateg...
PREPEND_ALL_SEGMENTS, VadInitialPromptMode.PREPREND_FIRST_SEGMENT]:
{ "list": [ { "filename": "src/whisper/whisperContainer.py", "retrieved_chunk": " if model.name == self.model_name:\n return model\n return None\n def _create_model(self):\n print(\"Loading whisper model \" + self.model_name)\n model_config = self._get...
import os from typing import List, Union from faster_whisper import WhisperModel, download_model from src.config import ModelConfig, VadInitialPromptMode from src.hooks.progressListener import ProgressListener from src.languages import get_language_from_name from src.modelCache import ModelCache from src.prompts.abstr...
model_config = self._get_model_config() model_url = model_config.url if model_config.type == "whisper": if model_url not in ["tiny", "base", "small", "medium", "large", "large-v1", "large-v2"]: raise Exception("FasterWhisperContainer does not yet support Whisper mod...
{ "context_start_lineno": 0, "file": "src/whisper/fasterWhisperContainer.py", "groundtruth_start_lineno": 40, "repository": "Cerlancism-faster-whisper-webui-884f5fd", "right_context_start_lineno": 41, "task_id": "project_cc_python/4755" }
{ "list": [ { "filename": "src/whisper/whisperContainer.py", "retrieved_chunk": " prompt_strategy: AbstractPromptStrategy = None,\n **decodeOptions: dict) -> AbstractWhisperCallback:\n \"\"\"\n Create a WhisperCallback object that can be used...
device))
{ "list": [ { "filename": "src/config.py", "retrieved_chunk": " self.device = device\n self.verbose = verbose\n self.task = task\n self.language = language\n self.vad_initial_prompt_mode = vad_initial_prompt_mode\n self.vad_merge_window = vad_merge_window\n ...
import argparse import os import pathlib from urllib.parse import urlparse import warnings import numpy as np import threading import torch from app import VadOptions, WhisperTranscriber from src.config import VAD_INITIAL_PROMPT_MODE_VALUES, ApplicationConfig, VadInitialPromptMode from src.download import download_url...
transcriber.write_result(result, source_name, output_dir, highlight_words, extras="_" + model.model_name + "_" + taskArgs["task"]) transcriber.close() def uri_validator(x): try: result = urlparse(x) return all([result.scheme, result.netloc]) except:...
{ "context_start_lineno": 0, "file": "cli.py", "groundtruth_start_lineno": 201, "repository": "Cerlancism-faster-whisper-webui-884f5fd", "right_context_start_lineno": 202, "task_id": "project_cc_python/4746" }
{ "list": [ { "filename": "src/config.py", "retrieved_chunk": " self.best_of = best_of\n self.beam_size = beam_size\n self.patience = patience\n self.length_penalty = length_penalty\n self.suppress_tokens = suppress_tokens\n self.initial_prompt = initial_promp...
transcribe_file(model, source_path, temperature=temperature, vadOptions=vadOptions, **taskArgs)
{ "list": [ { "filename": "exps/main.py", "retrieved_chunk": " args.batch_size,\n workers=args.workers,\n input_size=args.input_size,\n nclass=args.nclass,\n holdout=\"train\" if holdout else None,\n timm_aug=args.aug,\n )\n if holdout:\n holdout_...
import os import torch import torch.nn.parallel import torch.optim import torch.utils.data import torch.utils.data.distributed import torchvision.transforms as transforms import utils.datasets as datasets from timm.data import create_transform def get_train_loader( data_path, batch_size, workers=5, ...
if torch.distributed.is_initialized(): train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) else: train_sampler = None if holdout == "val": shfl = False else: shfl = train_sampler is None train_loader = torch.utils.data.DataLoader( ...
{ "context_start_lineno": 0, "file": "utils/loaders.py", "groundtruth_start_lineno": 59, "repository": "snu-mllab-Efficient-CNN-Depth-Compression-2828ae8", "right_context_start_lineno": 60, "task_id": "project_cc_python/4767" }
{ "list": [ { "filename": "utils/datasets.py", "retrieved_chunk": " and check if the file is a valid file (used to check of corrupt files)\n Attributes:\n classes (list): List of the class names sorted alphabetically.\n class_to_idx (dict): Dict with items (class_name, cla...
ImageFolder(traindir, aug, nclass=nclass, holdout=holdout)
{ "list": [ { "filename": "rayen/utils.py", "retrieved_chunk": "# Everything in Pytorch\ndef powerIteration(A, v, tol=1e-5, max_iter=100000, eps=1e-12, check_freq=2):\n\t\tn_iter = 0\n\t\tv = torch.nn.functional.normalize(v)\n\t\twhile n_iter < max_iter:\n\t\t\t\tn_iter += 1\n\t\t\t\tu = torch.nn.func...
# Import packages. import cvxpy as cp import numpy as np from numpy import linalg as LA import utils import torch import scipy A=torch.Tensor([ [[2.0, -12.0], [1.0, -5.0]], [[-7.0, 0.0], [0.0, 5.0]], [[-2.0, 0.0], [0...
L, V = torch.linalg.eig(A) print(L) print(f"Found lambda={lamb}") exit() dim=3 for trial in range(200): # Generate a random SDP. tmp = np.random.rand(dim, dim) # tmp = np.random.randint(0, 20, size=(dim, dim)) H = np.dot(tmp, tmp.transpose()) + np.eye(dim) #H is psd by construction tmp = np....
{ "context_start_lineno": 0, "file": "examples/other/testing_sdp.py", "groundtruth_start_lineno": 24, "repository": "leggedrobotics-rayen-2ac7086", "right_context_start_lineno": 25, "task_id": "project_cc_python/4802" }
{ "list": [ { "filename": "rayen/utils.py", "retrieved_chunk": "\t\t\t\t\t\t\t\tv = u\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\tv = u\n\t\telse:\n\t\t\t\tprint(f\"distance={distance}\")\n\t\t\t\tprint('Power iteration did not converge')\n\t\tlamb = torch.transpose(v,1,2)@A@v #torch.dot(v, torch.mv(A, v))\n\t\t...
findLargestEigenvalue(A, guess_v)
{ "list": [ { "filename": "ardilla/schemas.py", "retrieved_chunk": " pk = field.name\n fields.append(field_schema[\"schema\"])\n constrains.append(field_schema[\"constraint\"]) if field_schema[\n \"constraint\"\n ] else None\n schema = (\n f\"CREATE...
import sqlite3 from pathlib import Path from datetime import datetime from ardilla import Model, Field from ardilla.errors import ModelIntegrityError from pydantic import Json def test_default_tablename(): class Foo(Model): id: int assert Foo.__tablename__ == "foo" def test_field_pk(): cla...
def test_pk(): assert User.__pk__ == "id" def test_double_pks(): try: class Book(Model): id: int = Field(pk=True) name: str = Field(pk=True) except Exception as e: assert isinstance(e, ModelIntegrityError)
{ "context_start_lineno": 0, "file": "tests/test_models.py", "groundtruth_start_lineno": 82, "repository": "chrisdewa-ardilla-312a373", "right_context_start_lineno": 83, "task_id": "project_cc_python/4822" }
{ "list": [ { "filename": "ardilla/schemas.py", "retrieved_chunk": " return schema\ndef get_pk(schema: str) -> Optional[str]:\n \"\"\"Gets the primary key field name from the passed schema\n Args:\n schema (str): table schema\n Returns:\n Optional[str]: the name of the primar...
__schema__.strip() == schema.strip()
{ "list": [ { "filename": "ardilla/schemas.py", "retrieved_chunk": "SQLFieldType = Union[int, float, str, bool, datetime, bytes, date, time]\nFIELD_MAPPING: dict[type, str] = {\n int: \"INTEGER\",\n float: \"REAL\",\n str: \"TEXT\",\n bool: \"INTEGER\",\n datetime: \"DATETIME\",\n by...
from typing import Annotated from fastapi import FastAPI, Depends, status, HTTPException from pydantic import BaseModel, Field from ardilla import Model from ardilla.asyncio import Engine from ardilla.errors import QueryExecutionError app = FastAPI(docs_url="/") # set the docs to index for easier access class Ite...
await engine.crud(Item) # cruds are cached, calling this here means # we don't lose instantiating it elsewhere @app.on_event("shutdown") async def on_shutdown_event(): await engine.close() async def get_item_by_id(id_: int) -> Item: """Returns the item with the specified id ...
{ "context_start_lineno": 0, "file": "examples/fastapi_app.py", "groundtruth_start_lineno": 30, "repository": "chrisdewa-ardilla-312a373", "right_context_start_lineno": 31, "task_id": "project_cc_python/4825" }
{ "list": [ { "filename": "ardilla/models.py", "retrieved_chunk": " __schema__: str # best effort will be made if it's missing\n # there's no support for constrains or foreign fields yet but you can\n # define your own schema to support them\n def __init_subclass__(cls, **kws) -> None:\n ...
connect()
{ "list": [ { "filename": "tests/test_async.py", "retrieved_chunk": " await crud.save_many(*users)\n to_delete = users[:-1]\n await crud.delete_many(*to_delete)\n assert await crud.count() == 1, \"Delete many didn't delete the correct amount of users\"\n@pytest.mark.asyncio...
from typing import Annotated from fastapi import FastAPI, Depends, status, HTTPException from pydantic import BaseModel, Field from ardilla import Model from ardilla.asyncio import Engine from ardilla.errors import QueryExecutionError app = FastAPI(docs_url="/") # set the docs to index for easier access class Ite...
# we don't lose instantiating it elsewhere @app.on_event("shutdown") async def on_shutdown_event(): await engine.close() async def get_item_by_id(id_: int) -> Item: """Returns the item with the specified id Args: id_ (int): the id of the item to lookup Raise...
{ "context_start_lineno": 0, "file": "examples/fastapi_app.py", "groundtruth_start_lineno": 31, "repository": "chrisdewa-ardilla-312a373", "right_context_start_lineno": 32, "task_id": "project_cc_python/4826" }
{ "list": [ { "filename": "tests/test_async.py", "retrieved_chunk": " await engine.close()\n await crud.insert(name='moni')\n except Exception as e:\n assert isinstance(e, DisconnectedEngine), f'Wrong exception raised'\n finally:\n await engine.close()\n unlink...
crud(Item) # cruds are cached, calling this here means
{ "list": [ { "filename": "deps/volume-rendering-jax/src/volrendjax/morton3d/lowering.py", "retrieved_chunk": " ctx: mlir.LoweringRule,\n # input array\n idcs: ir.Value,\n):\n length, = ir.RankedTensorType(idcs.type).shape\n opaque = volrendutils_cuda.make_morton3d_descriptor(length)\n ...
from jax.interpreters import mlir from jax.interpreters.mlir import ir from .. import volrendutils_cuda try: from jaxlib.mhlo_helpers import custom_call except ModuleNotFoundError: # A more recent jaxlib would have `hlo_helpers` instead of `mhlo_helpers` # <https://github.com/google/jax/commit/b8ae8e3fa10...
shapes = { "in.density_threshold": (n_bits,), "in.density_grid": (n_bits,), "out.occupied_mask": (n_bits,), "out.occupancy_bitfield": (n_bytes,), } return custom_call( call_target_name="pack_density_into_bits", out_types = [ ir.RankedTensorType...
{ "context_start_lineno": 0, "file": "deps/volume-rendering-jax/src/volrendjax/packbits/lowering.py", "groundtruth_start_lineno": 28, "repository": "blurgyy-jaxngp-adbe49e", "right_context_start_lineno": 29, "task_id": "project_cc_python/4680" }
{ "list": [ { "filename": "deps/volume-rendering-jax/src/volrendjax/morton3d/lowering.py", "retrieved_chunk": " \"in.xyzs\": (length, 3),\n \"out.idcs\": (length,),\n }\n return [custom_call(\n call_target_name=\"morton3d\",\n out_types=[\n ir.RankedTensorT...
make_packbits_descriptor(n_bytes)
{ "list": [ { "filename": "deps/volume-rendering-jax/src/volrendjax/packbits/lowering.py", "retrieved_chunk": "def default_layouts(*shapes):\n return [range(len(shape) - 1, -1, -1) for shape in shapes]\ndef packbits_lowering_rule(\n ctx: mlir.LoweringRule,\n # input array\n density_thresho...
from jax.interpreters import mlir from jax.interpreters.mlir import ir from .. import volrendutils_cuda try: from jaxlib.mhlo_helpers import custom_call except ModuleNotFoundError: # A more recent jaxlib would have `hlo_helpers` instead of `mhlo_helpers` # <https://github.com/google/jax/commit/b8ae8e3fa10...
shapes = { "in.xyzs": (length, 3), "out.idcs": (length,), } return [custom_call( call_target_name="morton3d", out_types=[ ir.RankedTensorType.get(shapes["out.idcs"], ir.IntegerType.get_unsigned(32)), ], operands=[ xyzs, ], ...
{ "context_start_lineno": 0, "file": "deps/volume-rendering-jax/src/volrendjax/morton3d/lowering.py", "groundtruth_start_lineno": 26, "repository": "blurgyy-jaxngp-adbe49e", "right_context_start_lineno": 27, "task_id": "project_cc_python/4679" }
{ "list": [ { "filename": "deps/volume-rendering-jax/src/volrendjax/packbits/lowering.py", "retrieved_chunk": " opaque = volrendutils_cuda.make_packbits_descriptor(n_bytes)\n shapes = {\n \"in.density_threshold\": (n_bits,),\n \"in.density_grid\": (n_bits,),\n \"out.occupied...
make_morton3d_descriptor(length)
{ "list": [ { "filename": "ardilla/migration.py", "retrieved_chunk": " cols = ', '.join(name for name in new.__fields__)\n script = f'''\n \\rALTER TABLE {tablename} RENAME TO _{tablename};\n \\r\n \\r{new_table_schema}\n \\r\n \\rINSERT INTO {tablename...
import sqlite3 from pathlib import Path from datetime import datetime from ardilla import Model, Field from ardilla.errors import ModelIntegrityError from pydantic import Json def test_default_tablename(): class Foo(Model): id: int assert Foo.__tablename__ == "foo" def test_field_pk(): cla...
def test_complex_schema_works(): try: db = Path(__file__).parent / 'db.sqlite3' db.unlink(missing_ok=True) con = sqlite3.connect(db) con.execute(Complex.__schema__) con.commit() finally: con.close() db.unlink(missing_ok=True) class User(Model): id...
{ "context_start_lineno": 0, "file": "tests/test_models.py", "groundtruth_start_lineno": 53, "repository": "chrisdewa-ardilla-312a373", "right_context_start_lineno": 54, "task_id": "project_cc_python/4821" }
{ "list": [ { "filename": "ardilla/migration.py", "retrieved_chunk": " \\rDROP TABLE _{tablename};\n \\r'''\n scripts.append(script)\n return \"\\n\\n\".join(scripts)", "score": 54.183045649211245 }, { "filename": "ardilla/schemas.py", "retrieved_chunk...
__schema__.strip() == complex_schema.strip()
{ "list": [ { "filename": "deps/volume-rendering-jax/src/volrendjax/marching/lowering.py", "retrieved_chunk": " occupancy_bitfield: ir.Value,\n # static args\n total_samples: int, # int\n diagonal_n_steps: int, # int\n K: int, # int\n G: int, # int\n bound: float, # float\n ...
from jax.interpreters import mlir from jax.interpreters.mlir import ir from .. import volrendutils_cuda try: from jaxlib.mhlo_helpers import custom_call except ModuleNotFoundError: # A more recent jaxlib would have `hlo_helpers` instead of `mhlo_helpers` # <https://github.com/google/jax/commit/b8ae8e3fa10...
shapes = { "in.rays_sample_startidx": (n_rays,), "in.rays_n_samples": (n_rays,), "in.bgs": (n_rays, 3), "in.dss": (total_samples,), "in.z_vals": (total_samples,), "in.drgbs": (total_samples, 4), "in.final_rgbds": (n_rays, 4), "in.final_opacities": ...
{ "context_start_lineno": 0, "file": "deps/volume-rendering-jax/src/volrendjax/integrating/lowering.py", "groundtruth_start_lineno": 106, "repository": "blurgyy-jaxngp-adbe49e", "right_context_start_lineno": 107, "task_id": "project_cc_python/4677" }
{ "list": [ { "filename": "deps/spherical-harmonics-encoding-jax/src/shjax/__init__.py", "retrieved_chunk": " opaque = cudaops.make_spherical_harmonics_encoding_descriptor(n, degree)\n # Documentation says directly return the `custom_call` would suffice, but directly returning\n # here result...
make_integrating_backward_descriptor(n_rays, total_samples, near_distance)
{ "list": [ { "filename": "ardilla/schemas.py", "retrieved_chunk": " pk = field.name\n fields.append(field_schema[\"schema\"])\n constrains.append(field_schema[\"constraint\"]) if field_schema[\n \"constraint\"\n ] else None\n schema = (\n f\"CREATE...
import sqlite3 from pathlib import Path from datetime import datetime from ardilla import Model, Field from ardilla.errors import ModelIntegrityError from pydantic import Json def test_default_tablename(): class Foo(Model): id: int assert Foo.__tablename__ == "foo" def test_field_pk(): cla...
def test_double_pks(): try: class Book(Model): id: int = Field(pk=True) name: str = Field(pk=True) except Exception as e: assert isinstance(e, ModelIntegrityError)
{ "context_start_lineno": 0, "file": "tests/test_models.py", "groundtruth_start_lineno": 86, "repository": "chrisdewa-ardilla-312a373", "right_context_start_lineno": 87, "task_id": "project_cc_python/4823" }
{ "list": [ { "filename": "ardilla/schemas.py", "retrieved_chunk": " return schema\ndef get_pk(schema: str) -> Optional[str]:\n \"\"\"Gets the primary key field name from the passed schema\n Args:\n schema (str): table schema\n Returns:\n Optional[str]: the name of the primar...
__pk__ == "id"
{ "list": [ { "filename": "deps/spherical-harmonics-encoding-jax/src/shjax/__init__.py", "retrieved_chunk": "def _spherical_harmonics_encoding_lowering_cuda(\n ctx: mlir.LoweringRuleContext,\n coord: ir.Value,\n hint: ir.Value,\n ):\n coord_type = ir.RankedTensorType(coord.t...
from jax.interpreters import mlir from jax.interpreters.mlir import ir from .. import volrendutils_cuda try: from jaxlib.mhlo_helpers import custom_call except ModuleNotFoundError: # A more recent jaxlib would have `hlo_helpers` instead of `mhlo_helpers` # <https://github.com/google/jax/commit/b8ae8e3fa10...
shapes = { "in.rays_sample_startidx": (n_rays,), "in.rays_n_samples": (n_rays,), "in.bgs": (n_rays, 3), "in.dss": (total_samples,), "in.z_vals": (total_samples,), "in.drgbs": (total_samples, 4), "helper.measured_batch_size": (1,), "out.final_rgbds...
{ "context_start_lineno": 0, "file": "deps/volume-rendering-jax/src/volrendjax/integrating/lowering.py", "groundtruth_start_lineno": 32, "repository": "blurgyy-jaxngp-adbe49e", "right_context_start_lineno": 33, "task_id": "project_cc_python/4676" }
{ "list": [ { "filename": "deps/spherical-harmonics-encoding-jax/src/shjax/__init__.py", "retrieved_chunk": " opaque = cudaops.make_spherical_harmonics_encoding_descriptor(n, degree)\n # Documentation says directly return the `custom_call` would suffice, but directly returning\n # here result...
make_integrating_descriptor(n_rays, total_samples)
{ "list": [ { "filename": "tests/test_entities_viewers.py", "retrieved_chunk": " </head>\n <body>\n<p><span class=\"entity lb-PERSON\"><span class=\"label\">PERSON</span>Ted</span> is a <span class=\"entity lb-POSITION\"><span class=\"label\">POSITION</span>Pitcher</span>.</p>\n </body>\n</ht...
import os import sys import re sys.path.insert(0, os.path.join('../src')) from extr import RegEx, RegExLabel, Entity, Location from extr.entities import create_entity_extractor, \ EntityAnnotator, \ HtmlEntityAnnotator, \ KnowledgeBaseEntit...
assert annotated_text == '##ENTITY_PERSON_2## is a ##ENTITY_POSITION_1##.' def test_html_annotate(): entities = [ Entity(1, 'POSITION', 'Pitcher', Location(9, 16)), Entity(2, 'PERSON', 'Ted', Location(0, 3)) ] annotated_text = HtmlEntityAnnotator().annotate('Ted is a Pitcher.', entit...
{ "context_start_lineno": 0, "file": "tests/test_entities.py", "groundtruth_start_lineno": 69, "repository": "dpasse-extr-f695d3c", "right_context_start_lineno": 70, "task_id": "project_cc_python/4779" }
{ "list": [ { "filename": "tests/test_entities_viewers.py", "retrieved_chunk": " viewer = HtmlViewer()\n viewer.append('Ted is a Pitcher.', entities)\n html_doc = viewer.create_view(\"\"\"\n.lb-PERSON { background-color: orange; }\n.lb-POSITION { background-color: yellow; }\n\"\"\")\n asse...
annotate('Ted is a Pitcher.', entities)
{ "list": [ { "filename": "src/chatgpdp/modules/ui/chat_window.py", "retrieved_chunk": " if is_loading:\n self.loading_text, self.loading_index, self.loading_timer = \" Thinking\", 0, QTimer()\n self.loading_timer.timeout.connect(self.update_loading_text)\n sel...
import markdown2 from PyQt5.QtWidgets import QSizePolicy, QTextEdit, QLabel, QWidget, QVBoxLayout from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtGui import QIcon from chatgpdp.modules.utils.settings import Settings from chatgpdp.modules.utils.utilities import Utilities from chatgpdp.styles.use_style import Style...
return style def format_code(self, code): return f"<style>{Message.styles}</style>{code}" if Message.styles else code def resize(self): margins = self.contentsMargins() height = int(self.doc.size().height() + margins.top() + margins.bottom()) self.setFixedHeight(height...
{ "context_start_lineno": 0, "file": "src/chatgpdp/modules/chat/message.py", "groundtruth_start_lineno": 85, "repository": "gabacode-chatGPDP-4701532", "right_context_start_lineno": 86, "task_id": "project_cc_python/4788" }
{ "list": [ { "filename": "src/chatgpdp/modules/ui/chat_window.py", "retrieved_chunk": " self.send_button.setText(f\"{self.loading_text}{'.' * self.loading_index}{' ' * (3 - self.loading_index)}\")\n def set_to_save(self):\n self.setWindowTitle(\n f\"{self.window_title} - {...
get_style("markdown.css")
{ "list": [ { "filename": "src/chatgpdp/modules/chat/message.py", "retrieved_chunk": " def __init__(self, chatbot, message, mode):\n super().__init__()\n self.layout = QVBoxLayout(self)\n self.setLayout(self.layout)\n styles = {\n \"author\": f\"color: {self.c...
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import ( QWidget, QVBoxLayout, QScrollArea, ) from chatgpdp.modules.chat.message import MessageBox class ChatBox(QScrollArea): def __init__(self, parent): super().__init__() self.parent = parent self.setWidgetResizable(True) ...
self.layout.addWidget(message_widget) def clear(self): for i in reversed(range(self.layout.count())): self.layout.itemAt(i).widget().deleteLater() def scroll_to_bottom(self): if not self.is_editing: self.scrollbar.setValue(self.scrollbar.maximum())
{ "context_start_lineno": 0, "file": "src/chatgpdp/modules/ui/components/chat_box.py", "groundtruth_start_lineno": 32, "repository": "gabacode-chatGPDP-4701532", "right_context_start_lineno": 33, "task_id": "project_cc_python/4793" }
{ "list": [ { "filename": "src/chatgpdp/modules/chat/message.py", "retrieved_chunk": " self.text_message = Message(chatbot, message)\n self.text_message.messageChanged.connect(self.emit_signal)\n self.text_message.setStyleSheet(styles[\"message\"])\n self.layout.addWidget(s...
messageChanged.connect(self.parent.set_to_save)
{ "list": [ { "filename": "src/chatgpdp/modules/dialogs/components/color_picker.py", "retrieved_chunk": " label = QLabel(self.title)\n self.button = QPushButton()\n self.button.setFixedSize(20, 20)\n self.button.setCursor(Qt.PointingHandCursor)\n self.set_color()\n ...
from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap, QCursor from PyQt5.QtWidgets import QDialog, QVBoxLayout, QLabel, QPushButton, QHBoxLayout from chatgpdp.resources import resources_rc from chatgpdp.modules.utils.utilities import Utilities class AboutDialog(QDialog): metadata = Utilities.get_metadata(...
layout.addWidget(label) layout.addWidget(QLabel("")) button_layout = QHBoxLayout() ok_button = QPushButton("Cheers!") ok_button.setCursor(QCursor(Qt.PointingHandCursor)) ok_button.clicked.connect(self.accept) button_layout.addWidget(ok_button) layou...
{ "context_start_lineno": 0, "file": "src/chatgpdp/modules/dialogs/about.py", "groundtruth_start_lineno": 34, "repository": "gabacode-chatGPDP-4701532", "right_context_start_lineno": 35, "task_id": "project_cc_python/4798" }
{ "list": [ { "filename": "src/chatgpdp/modules/dialogs/components/color_picker.py", "retrieved_chunk": " if color.isValid():\n self.color = color.name()\n self.set_color()\n def set_color(self):\n self.button.setStyleSheet(f\"background-color: {self.color}; bord...
open_link(url))
{ "list": [ { "filename": "src/chatgpdp/modules/ui/components/prompt_box.py", "retrieved_chunk": " self.installEventFilter(self)\n self.textChanged.connect(self.resize_prompt)\n def eventFilter(self, obj, event):\n if event.type() == QEvent.KeyPress and obj is self:\n ...
import markdown2 from PyQt5.QtWidgets import QSizePolicy, QTextEdit, QLabel, QWidget, QVBoxLayout from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtGui import QIcon from chatgpdp.modules.utils.settings import Settings from chatgpdp.modules.utils.utilities import Utilities from chatgpdp.styles.use_style import Style...
super().mouseReleaseEvent(event) def wheelEvent(self, event): event.ignore()
{ "context_start_lineno": 0, "file": "src/chatgpdp/modules/chat/message.py", "groundtruth_start_lineno": 164, "repository": "gabacode-chatGPDP-4701532", "right_context_start_lineno": 165, "task_id": "project_cc_python/4789" }
{ "list": [ { "filename": "src/chatgpdp/modules/ui/components/prompt_box.py", "retrieved_chunk": " return super().eventFilter(obj, event)\n def resize_prompt(self):\n documentHeight = self.document().size().height()\n scrollbarHeight = self.verticalScrollBar().sizeHint().height...
open_link(anchor)
{ "list": [ { "filename": "tests/test_context.py", "retrieved_chunk": " regexes=[\n RegEx([r'is ruled out'], flags=re.IGNORECASE)\n ]\n ),\n RegExLabel(\n 'HISTORY_RIGHT',\n regexes=[\n RegEx([r'history of'], flags=re.IGNORECASE)\n ]\n ...
import os import sys import re sys.path.insert(0, os.path.join('../src')) from extr import RegEx, RegExLabel, Entity, Location from extr.entities import create_entity_extractor, \ EntityAnnotator, \ HtmlEntityAnnotator, \ KnowledgeBaseEntit...
assert len(entities) == 2 def test_get_entities_with_overlap(): regex_labels = [ RegExLabel('PERSON', [ RegEx([r'ted'], re.IGNORECASE) ]), RegExLabel('POSITION', [ RegEx([r'pitch'], re.IGNORECASE), RegEx([r'pitcher'], re.IGNORECASE) ]), ...
{ "context_start_lineno": 0, "file": "tests/test_entities.py", "groundtruth_start_lineno": 23, "repository": "dpasse-extr-f695d3c", "right_context_start_lineno": 24, "task_id": "project_cc_python/4778" }
{ "list": [ { "filename": "tests/test_context.py", "retrieved_chunk": " RegExLabel(\n 'INFECTION',\n regexes=[\n RegEx([r'pneumonia'], flags=re.IGNORECASE)\n ]\n ),\n]\nrules = [\n ConTextRule(\n 'NEGATED',", "score": 34.32314314817424 }, {...
get_entities('Ted is a Pitcher.')
{ "list": [ { "filename": "src/chatgpdp/modules/dialogs/settings.py", "retrieved_chunk": "from PyQt5.QtCore import Qt\nfrom chatgpdp.modules.chat.bot import Chatbot\nfrom chatgpdp.modules.dialogs.components.color_picker import ColorPicker\nfrom chatgpdp.modules.utils.settings import Settings\nclass Se...
from PyQt5.QtWidgets import ( QDialog, QDialogButtonBox, QTextEdit, QVBoxLayout, ) from chatgpdp.modules.utils.settings import Settings class PersonalityDialog(QDialog): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Change Personality") sel...
self.text_area = QTextEdit() button_box = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Cancel) button_box.accepted.connect(self.save_file_and_close) button_box.rejected.connect(self.reject) vbox = QVBoxLayout() vbox.addWidget(self.text_area) vbox....
{ "context_start_lineno": 0, "file": "src/chatgpdp/modules/dialogs/personality.py", "groundtruth_start_lineno": 16, "repository": "gabacode-chatGPDP-4701532", "right_context_start_lineno": 17, "task_id": "project_cc_python/4799" }
{ "list": [ { "filename": "src/chatgpdp/modules/dialogs/settings.py", "retrieved_chunk": " self.api_settings = ApiSettings(self.settings)\n colors_settings = ColorSetting(self.settings)\n button_box = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Cancel)\n for b...
get_by_key("chat/initial_prompt")
{ "list": [ { "filename": "src/extr/models.py", "retrieved_chunk": " @property\n def actual_end(self) -> int:\n return self.end - 1\n def is_in(self: TLocation, other: TLocation) -> bool:\n return self.start >= other.start and self.start <= other.actual_end \\\n or se...
from abc import ABC, abstractmethod from typing import Callable, Generator, List, Optional, Set from enum import Enum from dataclasses import dataclass from ..models import Entity, Token from ..tokenizers import word_tokenizer as tokenizer class DirectionType(Enum): LEFT=0 RIGHT=1 BOTH=2 class ConTextRul...
tokens = token_group.tokens for current_index, token in enumerate(tokens): for rule in self._rule_grouping.get_rules(token): for tokens_by_direction in self._get_tokens_for_rule( current_index, rule, tokens ...
{ "context_start_lineno": 0, "file": "src/extr/entities/context.py", "groundtruth_start_lineno": 90, "repository": "dpasse-extr-f695d3c", "right_context_start_lineno": 91, "task_id": "project_cc_python/4771" }
{ "list": [ { "filename": "src/extr/tokenizers/tokenizer.py", "retrieved_chunk": " actual_term = cache[start:end]\n assert actual_term == term, f'mismatch(\"{actual_term}\", \"{term}\")'\n tokens_in_sentence.append(\n Token(term, Location(offset + start, offset + end), ...
apply_entities(entities)
{ "list": [ { "filename": "src/chatgpdp/modules/dialogs/settings.py", "retrieved_chunk": " self.api_settings = ApiSettings(self.settings)\n colors_settings = ColorSetting(self.settings)\n button_box = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Cancel)\n for b...
from PyQt5.QtWidgets import ( QDialog, QDialogButtonBox, QTextEdit, QVBoxLayout, ) from chatgpdp.modules.utils.settings import Settings class PersonalityDialog(QDialog): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Change Personality") sel...
self.accept() def reject(self): self.done(QDialog.Rejected)
{ "context_start_lineno": 0, "file": "src/chatgpdp/modules/dialogs/personality.py", "groundtruth_start_lineno": 33, "repository": "gabacode-chatGPDP-4701532", "right_context_start_lineno": 34, "task_id": "project_cc_python/4800" }
{ "list": [ { "filename": "src/chatgpdp/modules/dialogs/settings.py", "retrieved_chunk": " scroll_area_content = QWidget(scroll_area)\n scroll_area.setWidget(scroll_area_content)\n scroll_area_layout = QVBoxLayout(scroll_area_content)\n scroll_area_layout.addWidget(self.api...
get().setValue("chat/initial_prompt", self.personality)
{ "list": [ { "filename": "src/chatgpdp/modules/utils/settings.py", "retrieved_chunk": " self._load()\n def _setup(self):\n \"\"\"\n Creates the config file if it doesn't exist and returns the QSettings object\n \"\"\"\n documents_path = QStandardPaths.writableLoc...
import os import openai from chatgpdp.modules.utils.config import PATHS, engines from langchain.prompts import ( ChatPromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, HumanMessagePromptTemplate, ) from langchain.schema import AIMessage, HumanMessage from langchain.chains import Convers...
openai.api_key = key def create_messages(self, prompt): self.add_to_history({"role": "user", "content": prompt}) return self.history def get_initial_prompt(self): for message in self.history: if message["role"] == "system": return message["content"]...
{ "context_start_lineno": 0, "file": "src/chatgpdp/modules/chat/bot.py", "groundtruth_start_lineno": 37, "repository": "gabacode-chatGPDP-4701532", "right_context_start_lineno": 38, "task_id": "project_cc_python/4785" }
{ "list": [ { "filename": "src/chatgpdp/modules/utils/settings.py", "retrieved_chunk": " settings.setIniCodec(\"UTF-8\")\n return settings\n def _load(self):\n \"\"\"\n Loads the saved settings from the config file, if present, otherwise sets default options\n \"\...
get_by_key("OPENAI_API_KEY")
{ "list": [ { "filename": "src/chatgpdp/modules/dialogs/settings.py", "retrieved_chunk": " def __init__(self, settings):\n super().__init__(\"OpenAI API Key\")\n self.settings = settings\n layout = QVBoxLayout(self)\n self.value = QLineEdit(self.settings.value(\"OPENAI_A...
import markdown2 from PyQt5.QtWidgets import QSizePolicy, QTextEdit, QLabel, QWidget, QVBoxLayout from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtGui import QIcon from chatgpdp.modules.utils.settings import Settings from chatgpdp.modules.utils.utilities import Utilities from chatgpdp.styles.use_style import Style...
class Message(QTextEdit): heightChanged = pyqtSignal() messageChanged = pyqtSignal() plugins = ["fenced-code-blocks", "codehilite", "tables", "break-on-newline"] styles = "" def __init__(self, chatbot, message): super().__init__() self.doc = self.document() self.chatbot =...
{ "context_start_lineno": 0, "file": "src/chatgpdp/modules/chat/message.py", "groundtruth_start_lineno": 55, "repository": "gabacode-chatGPDP-4701532", "right_context_start_lineno": 56, "task_id": "project_cc_python/4787" }
{ "list": [ { "filename": "src/chatgpdp/modules/dialogs/settings.py", "retrieved_chunk": " super().__init__(\"Colors\")\n self.settings = settings\n layout = QVBoxLayout(self)\n for scope in [\"system\", \"assistant\", \"user\"]:\n group_box = QGroupBox(scope.cap...
get_name_from_mode(mode) + ":")
{ "list": [ { "filename": "src/processing/02_ica.py", "retrieved_chunk": "bad_subjects = ['01P', '02P', '03P', '04P', '05P', '06P', '07P']#these ica need to be done manually\nall_fnames = zip(\n get_all_fnames(args.subject, kind='filt', exclude=exclude),\n get_all_fnames(args.subject, kind='ica'...
""" Compute the Power Spectral Density (PSD) for each channel. Running: import subprocess subprocess.run('/net/tera2/home/aino/work/mtbi-eeg/python/processing/eeg/runall.sh', shell=True) """ import argparse from mne.io import read_raw_fif from mne.time_frequency import psd_array_welch from h5io import write_hdf5 fr...
elif '2' in task: task_wo_run = task.removesuffix('_run2') run = 2 else: task_wo_run = task raw = read_raw_fif(fname.clean(subject=args.subject, task=task_wo_run, run=run,ses='01'), preload=True) # Reduce logging level (technically, one could...
{ "context_start_lineno": 0, "file": "src/processing/03_psds.py", "groundtruth_start_lineno": 50, "repository": "BioMag-mtbi_meeg-b757aa8", "right_context_start_lineno": 51, "task_id": "project_cc_python/4887" }
{ "list": [ { "filename": "src/processing/02_ica.py", "retrieved_chunk": " # Reduce logging level (technically, one could define it in the read_raw_fif function, but it seems to be buggy)\n # More info about the bug can be found here: https://github.com/mne-tools/mne-python/issues/8872\n set_...
removesuffix('_run1')
{ "list": [ { "filename": "local_groundingdino/util/inference.py", "retrieved_chunk": " except ValueError:\n class_ids.append(None)\n return np.array(class_ids)", "score": 22.227762920743313 }, { "filename": "scripts/sam.py", "retrieved_chunk"...
import os import gc import glob import copy from PIL import Image from collections import OrderedDict import numpy as np import torch import cv2 from sam_hq.automatic import SamAutomaticMaskGeneratorHQ from modules import scripts, shared from modules.paths import extensions_dir from modules.devices import torch_gc gl...
annotations = sorted(annotations, key=lambda x: x['area'], reverse=True) print(f"Auto SAM generated {len(annotations)} masks") for ann in annotations: valid_mask = torch.tensor(maskUtils.decode(ann['segmentation'])).bool() propose_classes_ids = torch.tensor(class_ids[valid_mask]) nu...
{ "context_start_lineno": 0, "file": "scripts/auto.py", "groundtruth_start_lineno": 84, "repository": "continue-revolution-sd-webui-segment-anything-5df716b", "right_context_start_lineno": 85, "task_id": "project_cc_python/4828" }
{ "list": [ { "filename": "local_groundingdino/util/inference.py", "retrieved_chunk": " except ValueError:\n class_ids.append(None)\n return np.array(class_ids)", "score": 22.227762920743313 }, { "filename": "scripts/sam.py", "retrieved_chunk"...
generate(img)
{ "list": [ { "filename": "src/analysis/02_plot_processed_data.py", "retrieved_chunk": "import sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nSRC_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))\nsys.path.append(SRC_DIR)\nfrom ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 11 12:18:46 2022 @author: aino Plots histograms for each frequency band. (should these be moved to plot.py??) Performs the Wilcoxon signed rank test. """ from readdata import dataframe as df from plot import global_df as gdf import matplotlib.pypl...
controls = gdf.loc[gdf['Group']==0] plot = True delta_p = patients.iloc[:, 1] delta_c =controls.iloc[:, 1] theta_p = patients.iloc[:, 2] theta_c = controls.iloc[:, 2] alpha_p = patients.iloc[:, 3] alpha_c = controls.iloc[:, 3] beta_p = patients.iloc[:, 4] beta_c = controls.iloc[:, 4] gamma_p = patients.iloc[:, 5] g...
{ "context_start_lineno": 0, "file": "src/other_files/wilcoxon.py", "groundtruth_start_lineno": 21, "repository": "BioMag-mtbi_meeg-b757aa8", "right_context_start_lineno": 22, "task_id": "project_cc_python/4885" }
{ "list": [ { "filename": "src/analysis/02_plot_processed_data.py", "retrieved_chunk": "#sns.set_style()\ndef initialize_argparser(metadata):\n \"\"\" Initialize argparser and add args to metadata.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('-v', '--verbosity', action='s...
loc[gdf['Group']==1]
{ "list": [ { "filename": "local_groundingdino/models/GroundingDINO/backbone/swin_transformer.py", "retrieved_chunk": " ):\n super().__init__()\n self.pretrain_img_size = pretrain_img_size\n self.num_layers = len(depths)\n self.embed_dim = embed_dim\n self.ape = a...
# ------------------------------------------------------------------------ # Grounding DINO # url: https://github.com/IDEA-Research/GroundingDINO # Copyright (c) 2023 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # -------------------------------------------------...
else: raise NotImplementedError("Unknown backbone {}".format(args.backbone)) assert len(bb_num_channels) == len( return_interm_indices ), f"len(bb_num_channels) {len(bb_num_channels)} != len(return_interm_indices) {len(return_interm_indices)}" model = Joiner(backbone, position_embeddi...
{ "context_start_lineno": 0, "file": "local_groundingdino/models/GroundingDINO/backbone/backbone.py", "groundtruth_start_lineno": 206, "repository": "continue-revolution-sd-webui-segment-anything-5df716b", "right_context_start_lineno": 207, "task_id": "project_cc_python/4829" }
{ "list": [ { "filename": "local_groundingdino/models/GroundingDINO/backbone/swin_transformer.py", "retrieved_chunk": " # if use_checkpoint:\n # print(\"use_checkpoint!!!!!!!!!!!!!!!!!!!!!!!!\")\n # split image into non-overlapping patches\n self.patch_embed = PatchEmbe...
num_features[4 - len(return_interm_indices) :]
{ "list": [ { "filename": "src/powermanim/showcase/layouts/arrangedbullets.py", "retrieved_chunk": " Bullet(\"Elements:\"),\n Bullet(\"First element\", level=1, symbol=\"(1)\"),\n Bullet(\"Second element\", level=1, symbol=\"(2)\"),\n Bullet(\"Third element\...
from manim import * from powermanim.layouts.arrangedbullets import Bullet from powermanim.showcase.showcasescene import ShowcaseScene from powermanim.templates.bulletlist import BulletList class BulletListShowcase(ShowcaseScene): def showcasing(): return BulletList def construct(self): rows ...
self.play(bullets.also_next()) self.play(bullets.also_next()) self.play(bullets.also_next()) self.play(bullets.also_next()) self.play(bullets.also_next()) self.play(bullets.also_next()) self.play(bullets.clear()) self.play(bullets.only_next()) se...
{ "context_start_lineno": 0, "file": "src/powermanim/showcase/templates/bulletlist.py", "groundtruth_start_lineno": 26, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 27, "task_id": "project_cc_python/4875" }
{ "list": [ { "filename": "src/powermanim/showcase/layouts/arrangedbullets.py", "retrieved_chunk": " ).set_opacity(1)\n self.play(\n MoveToTarget(g_rows),\n rate_func=there_and_back_with_pause,\n run_time=3,\n )\n self.wait()", "score"...
add(bullets)
{ "list": [ { "filename": "src/fnames.py", "retrieved_chunk": "\"\"\"Utility class to manage a list of filenames.\nUse the `add` method to add new filenames. You specify a short \"alias\" for\nthem, which you can use to retrieve the full filename later:\n>>> fname = FileNames()\n>>> fname.add('my_file...
""" These are all the relevant parameters that are unique to the EEG analysis pipeline. """ import os from fnames import FileNames from config_common import (raw_data_dir, processed_data_dir, figures_dir, reports_dir) tasks = ['ec', 'eo', 'PASAT'] #######################################...
fname.add('processed_data_dir', processed_data_dir) # Continuous data fname.add('raw', '{raw_data_dir}/sub-{subject}/ses-{ses}/meg/sub-{subject}_ses-{ses}_task-{task}_run-0{run}_proc-raw_meg.fif') fname.add('filt', '{processed_data_dir}/sub-{subject}/ses-01/eeg/sub-{subject}_ses-{ses}_task-{task}_run-0{run}_filt.fif'...
{ "context_start_lineno": 0, "file": "src/config_eeg.py", "groundtruth_start_lineno": 380, "repository": "BioMag-mtbi_meeg-b757aa8", "right_context_start_lineno": 381, "task_id": "project_cc_python/4884" }
{ "list": [ { "filename": "src/fnames.py", "retrieved_chunk": " files = dict()\n for name, value in self.__dict__.items():\n public_methods = ['list_filenames', 'add']\n if not name.startswith('_') and name not in public_methods:\n files[name] = value...
add('raw_data_dir', raw_data_dir)
{ "list": [ { "filename": "src/powermanim/components/vgrouphighlight.py", "retrieved_chunk": "import typing as T\nfrom manim import *\nclass VGroupHighlight(VGroup):\n def __init__(\n self,\n *args: VMobject,\n anim_run_time: float = 1.0,\n anim_lag_ratio: float = 0,\n ...
from manim import * from powermanim.components.vgrouphighlight import VGroupHighlight from powermanim.showcase.showcasescene import ShowcaseScene class VGroupHighlightShowcase(ShowcaseScene): def showcasing(): return VGroupHighlight def construct(self): dots = [ Dot(radius=0.25, ...
self.play(group.highlight(1)) self.play(group.highlight([2, 3])) self.play(group.highlight([1, 3])) self.play(group.highlight([])) self.play(group.highlight([2, 4])) self.play(group.highlight([])) self.wait(0.5)
{ "context_start_lineno": 0, "file": "src/powermanim/showcase/components/vgroupghighlight.py", "groundtruth_start_lineno": 27, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 28, "task_id": "project_cc_python/4865" }
{ "list": [ { "filename": "src/powermanim/components/vgrouphighlight.py", "retrieved_chunk": " scale_about_point=None,\n scale_about_edge=None,\n **kwargs: VMobject,\n ) -> None:\n \"\"\"Group component that can highlight a subset of its submobjects.\n Args:\n ...
play(group.highlight(0))
{ "list": [ { "filename": "src/powermanim/components/chartbars.py", "retrieved_chunk": " width_ratio: float = 1.0,\n offset: float = 0.5,\n fill_color: Color = BLUE,\n fill_opacity: float = 0.5,\n stroke_color: Color = WHITE,\n stroke_width: float = 1.0,\n ...
from manim import * from scipy.special import softmax from powermanim.components.chartbars import ChartBars from powermanim.showcase.showcasescene import ShowcaseScene class ChartBarsShowcase(ShowcaseScene): def showcasing(): return ChartBars def construct(self): axes = Axes(x_range=[0, 6], ...
for i in range(changes): dist2 = softmax(np.random.randn(size)) self.play(bars.animate.set_values(dist2), run_time=2) self.play(bars.animate.set_values(dist1), run_time=2)
{ "context_start_lineno": 0, "file": "src/powermanim/showcase/components/chartbars.py", "groundtruth_start_lineno": 19, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 20, "task_id": "project_cc_python/4861" }
{ "list": [ { "filename": "src/powermanim/components/chartbars.py", "retrieved_chunk": " values: The values to plot. There should be one value for each bar.\n xs: The x-coordinates of the bars. If None, the bars will be centered on\n each integer from 1 to the numb...
add(axes, bars)
{ "list": [ { "filename": "src/powermanim/components/vgrouphighlight.py", "retrieved_chunk": " self.scale_about_point = scale_about_point\n self.scale_about_edge = scale_about_edge\n self.previously_active_idxs = []\n def highlight(self, indices: T.Union[int, T.Sequence[int]]) ...
import typing as T from manim import * from powermanim.components.vgrouphighlight import VGroupHighlight from powermanim.layouts.arrangedbullets import ArrangedBullets class BulletList(VGroup): def __init__( self, *rows: T.Union[Tex, Text], line_spacing: float = MED_LARGE_BUFF * 1.5, ...
def only_next(self) -> Animation: """Highlights only the next item in the list.""" if self.highlighted > self.arranged_list.ngroups: raise StopIteration("No more elements to highlight.") anims = self.rows.highlight(indices=self.highlighted) self.highlighted += 1 ...
{ "context_start_lineno": 0, "file": "src/powermanim/templates/bulletlist.py", "groundtruth_start_lineno": 57, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 58, "task_id": "project_cc_python/4882" }
{ "list": [ { "filename": "src/powermanim/components/vgrouphighlight.py", "retrieved_chunk": " If a sequence of integers is given, all indices in the sequence are highlighted. The\n previously highlighted indices are dehighlighted smoothly.\n \"\"\"\n anims ...
highlight(indices=list(range(self.highlighted)))
{ "list": [ { "filename": "src/powermanim/showcase/layouts/arrangedbullets.py", "retrieved_chunk": " Bullet(\"Elements:\"),\n Bullet(\"First element\", level=1, symbol=\"(1)\"),\n Bullet(\"Second element\", level=1, symbol=\"(2)\"),\n Bullet(\"Third element\...
from manim import * from powermanim.layouts.arrangedbullets import Bullet from powermanim.showcase.showcasescene import ShowcaseScene from powermanim.templates.bulletlist import BulletList class BulletListShowcase(ShowcaseScene): def showcasing(): return BulletList def construct(self): rows ...
self.play(bullets.also_next()) self.play(bullets.also_next()) self.play(bullets.also_next()) self.play(bullets.also_next()) self.play(bullets.also_next()) self.play(bullets.clear()) self.play(bullets.only_next()) self.play(bullets.only_next()) sel...
{ "context_start_lineno": 0, "file": "src/powermanim/showcase/templates/bulletlist.py", "groundtruth_start_lineno": 28, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 29, "task_id": "project_cc_python/4877" }
{ "list": [ { "filename": "src/powermanim/showcase/layouts/arrangedbullets.py", "retrieved_chunk": " ).set_opacity(1)\n self.play(\n MoveToTarget(g_rows),\n rate_func=there_and_back_with_pause,\n run_time=3,\n )\n self.wait()", "score"...
also_next())
{ "list": [ { "filename": "src/powermanim/showcase/templates/bulletlist.py", "retrieved_chunk": " )\n self.add(bullets)\n self.play(bullets.also_next())\n self.play(bullets.also_next())\n self.play(bullets.also_next())\n self.play(bullets.also_next())\n ...
from manim import * from powermanim.components.vgrouphighlight import VGroupHighlight from powermanim.showcase.showcasescene import ShowcaseScene class VGroupHighlightShowcase(ShowcaseScene): def showcasing(): return VGroupHighlight def construct(self): dots = [ Dot(radius=0.25, ...
{ "context_start_lineno": 0, "file": "src/powermanim/showcase/components/vgroupghighlight.py", "groundtruth_start_lineno": 34, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 35, "task_id": "project_cc_python/4867" }
{ "list": [ { "filename": "src/powermanim/showcase/templates/bulletlist.py", "retrieved_chunk": " )\n self.add(bullets)\n self.play(bullets.also_next())\n self.play(bullets.also_next())\n self.play(bullets.also_next())\n self.play(bullets.also_next())\n ...
wait(0.5)
{ "list": [ { "filename": "src/powermanim/layouts/arrangedbullets.py", "retrieved_chunk": " if group is None:\n group = i\n group2bullet[group].append(row)\n group_rows = []\n for _, bullets in group2bullet.items():\n group_rows.append(VGro...
from manim import * from powermanim.layouts.arrangedbullets import Bullet from powermanim.showcase.showcasescene import ShowcaseScene from powermanim.templates.bulletlist import BulletList class BulletListShowcase(ShowcaseScene): def showcasing(): return BulletList def construct(self): rows ...
self.play(bullets.only_next()) self.play(bullets.only_next()) self.play(bullets.only_next()) self.play(bullets.only_next()) self.play(bullets.only_next()) self.play(bullets.clear()) self.wait()
{ "context_start_lineno": 0, "file": "src/powermanim/showcase/templates/bulletlist.py", "groundtruth_start_lineno": 35, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 36, "task_id": "project_cc_python/4879" }
{ "list": [ { "filename": "src/powermanim/layouts/arrangedbullets.py", "retrieved_chunk": " if group is None:\n group = i\n group2bullet[group].append(row)\n group_rows = []\n for _, bullets in group2bullet.items():\n group_rows.append(VGro...
only_next())
{ "list": [ { "filename": "src/powermanim/components/vgrouphighlight.py", "retrieved_chunk": "import typing as T\nfrom manim import *\nclass VGroupHighlight(VGroup):\n def __init__(\n self,\n *args: VMobject,\n anim_run_time: float = 1.0,\n anim_lag_ratio: float = 0,\n ...
from manim import * from powermanim.components.vgrouphighlight import VGroupHighlight from powermanim.showcase.showcasescene import ShowcaseScene class VGroupHighlightShowcase(ShowcaseScene): def showcasing(): return VGroupHighlight def construct(self): dots = [ Dot(radius=0.25, ...
self.play(group.highlight(1)) self.play(group.highlight([2, 3])) self.play(group.highlight([1, 3])) self.play(group.highlight([])) self.play(group.highlight([2, 4])) self.play(group.highlight([])) self.wait(0.5)
{ "context_start_lineno": 0, "file": "src/powermanim/showcase/components/vgroupghighlight.py", "groundtruth_start_lineno": 27, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 28, "task_id": "project_cc_python/4866" }
{ "list": [ { "filename": "src/powermanim/components/vgrouphighlight.py", "retrieved_chunk": " scale_about_point=None,\n scale_about_edge=None,\n **kwargs: VMobject,\n ) -> None:\n \"\"\"Group component that can highlight a subset of its submobjects.\n Args:\n ...
highlight(0))
{ "list": [ { "filename": "src/powermanim/components/vgrouphighlight.py", "retrieved_chunk": "import typing as T\nfrom manim import *\nclass VGroupHighlight(VGroup):\n def __init__(\n self,\n *args: VMobject,\n anim_run_time: float = 1.0,\n anim_lag_ratio: float = 0,\n ...
from manim import * from powermanim.components.vgrouphighlight import VGroupHighlight from powermanim.showcase.showcasescene import ShowcaseScene class VGroupHighlightShowcase(ShowcaseScene): def showcasing(): return VGroupHighlight def construct(self): dots = [ Dot(radius=0.25, ...
self.play(group.highlight(0)) self.play(group.highlight(1)) self.play(group.highlight([2, 3])) self.play(group.highlight([1, 3])) self.play(group.highlight([])) self.play(group.highlight([2, 4])) self.play(group.highlight([])) self.wait(0.5)
{ "context_start_lineno": 0, "file": "src/powermanim/showcase/components/vgroupghighlight.py", "groundtruth_start_lineno": 26, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 27, "task_id": "project_cc_python/4864" }
{ "list": [ { "filename": "src/powermanim/components/vgrouphighlight.py", "retrieved_chunk": " scale_about_point=None,\n scale_about_edge=None,\n **kwargs: VMobject,\n ) -> None:\n \"\"\"Group component that can highlight a subset of its submobjects.\n Args:\n ...
add(group)
{ "list": [ { "filename": "src/powermanim/components/chartbars.py", "retrieved_chunk": " width_ratio: float = 1.0,\n offset: float = 0.5,\n fill_color: Color = BLUE,\n fill_opacity: float = 0.5,\n stroke_color: Color = WHITE,\n stroke_width: float = 1.0,\n ...
from manim import * from scipy.special import softmax from powermanim.components.chartbars import ChartBars from powermanim.showcase.showcasescene import ShowcaseScene class ChartBarsShowcase(ShowcaseScene): def showcasing(): return ChartBars def construct(self): axes = Axes(x_range=[0, 6], ...
self.play(bars.animate.set_values(dist1), run_time=2)
{ "context_start_lineno": 0, "file": "src/powermanim/showcase/components/chartbars.py", "groundtruth_start_lineno": 22, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 23, "task_id": "project_cc_python/4863" }
{ "list": [ { "filename": "src/powermanim/components/chartbars.py", "retrieved_chunk": " values: The values to plot. There should be one value for each bar.\n xs: The x-coordinates of the bars. If None, the bars will be centered on\n each integer from 1 to the numb...
animate.set_values(dist2), run_time=2)
{ "list": [ { "filename": "src/powermanim/components/chartbars.py", "retrieved_chunk": " width_ratio: float = 1.0,\n offset: float = 0.5,\n fill_color: Color = BLUE,\n fill_opacity: float = 0.5,\n stroke_color: Color = WHITE,\n stroke_width: float = 1.0,\n ...
from manim import * from scipy.special import softmax from powermanim.components.chartbars import ChartBars from powermanim.showcase.showcasescene import ShowcaseScene class ChartBarsShowcase(ShowcaseScene): def showcasing(): return ChartBars def construct(self): axes = Axes(x_range=[0, 6], ...
self.play(bars.animate.set_values(dist1), run_time=2)
{ "context_start_lineno": 0, "file": "src/powermanim/showcase/components/chartbars.py", "groundtruth_start_lineno": 22, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 23, "task_id": "project_cc_python/4862" }
{ "list": [ { "filename": "src/powermanim/components/chartbars.py", "retrieved_chunk": " values: The values to plot. There should be one value for each bar.\n xs: The x-coordinates of the bars. If None, the bars will be centered on\n each integer from 1 to the numb...
play(bars.animate.set_values(dist2), run_time=2)
{ "list": [ { "filename": "src/powermanim/layouts/arrangedbullets.py", "retrieved_chunk": " Args:\n rows: A list of items to be displayed.\n line_spacing: The spacing between the rows.\n indent_buff: The spacing between the bullet and the text.\n left...
import typing as T from manim import * from powermanim.components.vgrouphighlight import VGroupHighlight from powermanim.layouts.arrangedbullets import ArrangedBullets class BulletList(VGroup): def __init__( self, *rows: T.Union[Tex, Text], line_spacing: float = MED_LARGE_BUFF * 1.5, ...
self.rows = VGroupHighlight( *self.arranged_list, active_opacity=active_opacity, scale_active=scale_active, scale_about_edge=LEFT, ) super().__init__(self.rows) self.highlighted = 0 def also_next(self) -> Animation: """Highl...
{ "context_start_lineno": 0, "file": "src/powermanim/templates/bulletlist.py", "groundtruth_start_lineno": 38, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 39, "task_id": "project_cc_python/4881" }
{ "list": [ { "filename": "src/powermanim/layouts/arrangedbullets.py", "retrieved_chunk": " self.global_shift = global_shift\n rows = [(row if isinstance(row, MathBullet) else Bullet(row)) for row in rows]\n self.arrage_rows((row for row in rows if row.autoplace))\n groups ...
set_opacity(inactive_opacity)
{ "list": [ { "filename": "src/powermanim/layouts/arrangedbullets.py", "retrieved_chunk": " if group is None:\n group = i\n group2bullet[group].append(row)\n group_rows = []\n for _, bullets in group2bullet.items():\n group_rows.append(VGro...
from manim import * from powermanim.layouts.arrangedbullets import Bullet from powermanim.showcase.showcasescene import ShowcaseScene from powermanim.templates.bulletlist import BulletList class BulletListShowcase(ShowcaseScene): def showcasing(): return BulletList def construct(self): rows ...
self.play(bullets.only_next()) self.play(bullets.only_next()) self.play(bullets.only_next()) self.play(bullets.only_next()) self.play(bullets.only_next()) self.play(bullets.only_next()) self.play(bullets.clear()) self.wait()
{ "context_start_lineno": 0, "file": "src/powermanim/showcase/templates/bulletlist.py", "groundtruth_start_lineno": 34, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 35, "task_id": "project_cc_python/4878" }
{ "list": [ { "filename": "src/powermanim/layouts/arrangedbullets.py", "retrieved_chunk": " if group is None:\n group = i\n group2bullet[group].append(row)\n group_rows = []\n for _, bullets in group2bullet.items():\n group_rows.append(VGro...
clear())
{ "list": [ { "filename": "src/powermanim/showcase/layouts/arrangedbullets.py", "retrieved_chunk": " Bullet(\"Elements:\"),\n Bullet(\"First element\", level=1, symbol=\"(1)\"),\n Bullet(\"Second element\", level=1, symbol=\"(2)\"),\n Bullet(\"Third element\...
from manim import * from powermanim.layouts.arrangedbullets import Bullet from powermanim.showcase.showcasescene import ShowcaseScene from powermanim.templates.bulletlist import BulletList class BulletListShowcase(ShowcaseScene): def showcasing(): return BulletList def construct(self): rows ...
self.play(bullets.also_next()) self.play(bullets.also_next()) self.play(bullets.also_next()) self.play(bullets.also_next()) self.play(bullets.also_next()) self.play(bullets.clear()) self.play(bullets.only_next()) self.play(bullets.only_next()) sel...
{ "context_start_lineno": 0, "file": "src/powermanim/showcase/templates/bulletlist.py", "groundtruth_start_lineno": 28, "repository": "lucmos-powermanim-1bcf62a", "right_context_start_lineno": 29, "task_id": "project_cc_python/4876" }
{ "list": [ { "filename": "src/powermanim/showcase/layouts/arrangedbullets.py", "retrieved_chunk": " ).set_opacity(1)\n self.play(\n MoveToTarget(g_rows),\n rate_func=there_and_back_with_pause,\n run_time=3,\n )\n self.wait()", "score"...
play(bullets.also_next())
{ "list": [ { "filename": "protovalidate/internal/constraints.py", "retrieved_chunk": " return _repeated_field_to_cel(msg, field)\n elif field.message_type is not None and not msg.HasField(field.name):\n return None\n else:\n return _scalar_field_value_to_cel(getattr(msg, fi...
# Copyright 2023 Buf Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
for constraint in self._factory.get(message.DESCRIPTOR): constraint.validate(ctx, message) if ctx.done: break return ctx.violations class ValidationError(ValueError): """ An error raised when a message fails to validate. """ violations: express...
{ "context_start_lineno": 0, "file": "protovalidate/validator.py", "groundtruth_start_lineno": 83, "repository": "bufbuild-protovalidate-python-2eee9ba", "right_context_start_lineno": 84, "task_id": "project_cc_python/4892" }
{ "list": [ { "filename": "protovalidate/internal/constraints.py", "retrieved_chunk": " def __init__(self, rules: message.Message | None):\n self._runners = []\n if rules is not None:\n self._rules_cel = _msg_to_cel(rules)\n def _validate_cel(self, ctx: ConstraintContext...
ConstraintContext(fail_fast=fail_fast, violations=into)
{ "list": [ { "filename": "protovalidate/validator.py", "retrieved_chunk": "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport typing\nfrom google.protobuf import me...
# Copyright 2023 Buf Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
assert len(violations.violations) == 0 def test_oneofs(): msg1 = oneofs_pb2.Oneof() msg1.y = 123 protovalidate.validate(msg1) msg2 = oneofs_pb2.Oneof() msg2.z.val = True protovalidate.validate(msg2) violations = protovalidate.collect_violations(msg1) protovalidate.collect_violat...
{ "context_start_lineno": 0, "file": "tests/validate_test.py", "groundtruth_start_lineno": 22, "repository": "bufbuild-protovalidate-python-2eee9ba", "right_context_start_lineno": 23, "task_id": "project_cc_python/4897" }
{ "list": [ { "filename": "protovalidate/validator.py", "retrieved_chunk": "class Validator:\n \"\"\"\n Validates protobuf messages against static constraints.\n Each validator instance caches internal state generated from the static\n constraints, so reusing the same instance for multiple...
collect_violations(msg)