version
stringclasses
1 value
style
stringclasses
2 values
subset
stringclasses
12 values
question_id
stringlengths
9
23
question
stringlengths
27
8.13k
solution
stringlengths
99
5.97k
test
stringlengths
105
4.45k
test_info
listlengths
0
13
gpt_pass_sequence
listlengths
1
10
gpt_pass_trial_num
int64
1
10
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
trials
dict
chosen_trial
stringclasses
10 values
metadata
dict
benchmark_similarity
float64
0.16
0.93
benchmark_instruction
stringclasses
1 value
benchmark_task_id
stringclasses
1 value
filter_reason
stringclasses
1 value
base_id
stringlengths
7
21
variant
stringclasses
2 values
top_function_names
listlengths
2
13
n_top_functions
int64
2
13
helper_call_edges
listlengths
1
16
n_helper_call_edges
int64
1
16
harness_functions
listlengths
0
3
structural_wrapper
bool
1 class
class_names
listlengths
0
5
has_class
bool
2 classes
test_kind
stringclasses
1 value
test_has_solution_import
bool
2 classes
third_party_imports
listlengths
0
5
stdlib_only
bool
2 classes
question_norm_sha1
stringlengths
40
40
solution_ast_sha1
stringlengths
40
40
v1.0
instruct
Docs
Docs: Python310_40473_I
### Parallel Computation with "concurrent.futures" You are required to write a Python program that uses the "concurrent.futures" module to execute parallel tasks. The task involves calculating the sum of squares for a list of numbers. To achieve this, you must split the list into chunks and compute the sum of squares ...
from typing import List from concurrent.futures import ThreadPoolExecutor def sum_of_squares_chunk(numbers: List[int]) -> int: """ Helper function to compute the sum of squares of a given list of numbers. """ return sum(x ** 2 for x in numbers) def parallel_sum_of_squares(numbers: List[int], chunk_siz...
from solution import parallel_sum_of_squares def test_small_list(): assert parallel_sum_of_squares([1, 2, 3, 4, 5], 2) == 55 def test_single_chunk(): assert parallel_sum_of_squares([1, 3, 5, 7, 9], 5) == 165 def test_multiple_full_chunks(): assert parallel_sum_of_squares([1, 2, 3, 4, 5, 6, 7, 8, 9, 1...
[ { "docstring": "Helper function to compute the sum of squares of a given list of numbers.", "function_declaration": "def sum_of_squares_chunk(numbers):", "function_name": "sum_of_squares_chunk", "parameter_list": "(numbers)" }, { "docstring": "Computes the total sum of squares of all numbers...
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ThreadPoolExecutor\nfrom typing import List\n\ndef parallel_sum_of_squares(numbers: List[int], chunk_size: int) -> int:\n def sum_of_s...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00040473", "row_id": 40473, "seed_ids": "[224]" }
0.66831
Docs: Python310_40473
I
[ "sum_of_squares_chunk", "parallel_sum_of_squares" ]
2
[ [ "parallel_sum_of_squares", "sum_of_squares_chunk" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ab9a31d78c6673fe24a70e731ab79e8cc4bb602b
52f66e636f154d9cef46724ae83dc63d565437ec
v1.0
instruct
Docs
Docs: Python310_40535_I
### Advanced Python Coding Assessment **Objective:** You are required to implement a custom traceback handler that mimics some functionalities of the deprecated `cgitb` module. This will assess your understanding of Python's exception handling, traceback management, and string formatting. **Instructions:** 1. Write a...
import traceback import datetime import sys import os def detailed_traceback(info, context_lines=5, output_format='text', logdir=None): exc_type, exc_value, exc_tb = info tb_lines = traceback.format_tb(exc_tb, limit=None) context_str = "" for tb in tb_lines: tb_parts = tb.split("\n") f...
import sys import os import tempfile from solution import detailed_traceback def test_detailed_traceback_text_format(): try: 1 / 0 except ZeroDivisionError: info = sys.exc_info() result = detailed_traceback(info, context_lines=3, output_format='text', logdir=None) assert 'ZeroDi...
[ { "docstring": null, "function_declaration": "def detailed_traceback(info, context_lines=5, output_format='text', logdir=None):", "function_name": "detailed_traceback", "parameter_list": "(info, context_lines=5, output_format='text', logdir=None)" }, { "docstring": "Fetch the context lines a...
[ 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import traceback\nimport datetime\nimport sys\nimport os\n\ndef detailed_traceback(info, context_lines=5, output_format='text', logdir=None):\n \"\"\"\n Generate ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00040535", "row_id": 40535, "seed_ids": "[385]" }
0.511405
Docs: Python310_40535
I
[ "detailed_traceback", "format_context" ]
2
[ [ "detailed_traceback", "format_context" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a61ca6bc424b8d82e0f4ed06484caf6c9b810010
3e40c50130caadd68474630d3d390cf69725625a
v1.0
instruct
Docs
Docs: Scikit_40554_I
#### Objective You are tasked with training a text classification model on a dataset that is too large to fit into the memory using scikit-learn. You will use out-of-core learning techniques with an incremental classifier. #### Task 1. **Data Streaming:** Write a function `stream_data` that simulates streaming data in...
import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split def stream_data(file_path, batch_size): """ A generator function to simulate streaming ...
from solution import stream_data, train_incremental_model, evaluate_model from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score import tempfile import os def test_stream_data(): # Create a temporary file with sample d...
[ { "docstring": "A generator function to simulate streaming of data in batches.\n\nArgs:\nfile_path (str): The path to the large text file.\nbatch_size (int): Number of samples per batch.\n\nYields:\nX_batch (list): List of text samples.\ny_batch (list): List of labels for the text samples.", "function_decla...
[ 1, 0, 1, 0, 1, 0, 1, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00040554", "row_id": 40554, "seed_ids": "[63]" }
0.537147
Docs: Scikit_40554
I
[ "stream_data", "train_incremental_model", "evaluate_model" ]
3
[ [ "train_incremental_model", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
ca44b7b45790abdb174d027758b058f6fad8ecab
f52b9142356341d5d72af5756d86a062917405c4
v1.0
instruct
Docs
Docs: Scikit_40560_I
### Question: You are developing a classifier to help medical practitioners identify patients who might have cancer. Given the critical nature of this application, your primary goal is to maximize recall, ensuring that fewer actual cases of cancer are missed, which justifies higher false-positive rates. You are provi...
import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_predict, KFold from sklearn.metrics import make_scorer, recall_score, confusion_matrix, precision_recall_curve def tune_threshold_for_recall(y_true, y_proba, pos_label=1): precision, recall, thresho...
import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from solution import tune_and_evaluate_threshold def generate_synthetic_data(): X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, n_informativ...
[ { "docstring": null, "function_declaration": "def tune_threshold_for_recall(y_true, y_proba, pos_label=1):", "function_name": "tune_threshold_for_recall", "parameter_list": "(y_true, y_proba, pos_label=1)" }, { "docstring": null, "function_declaration": "def tune_and_evaluate_threshold(X...
[ 0, 0, 0, 1, 0, 1, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import StratifiedKFold, cross_val_predict\nfrom sklearn.metrics im...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00040560", "row_id": 40560, "seed_ids": "[19]" }
0.616747
Docs: Scikit_40560
I
[ "tune_threshold_for_recall", "tune_and_evaluate_threshold" ]
2
[ [ "tune_and_evaluate_threshold", "tune_threshold_for_recall" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
6e72b07d584dfa647df7582e330dbd6bec3dc688
56d34b9e65c9f0ca329c7e5491f8bd21172a63e7
v1.0
instruct
Docs
Docs: Pytorch_40720_I
### PyTorch Distributed Training Configuration #### Objective Design and implement a Python script using PyTorch that demonstrates setting up a distributed training environment for a neural network model. The script should specifically leverage the ProcessGroupNCCL environment variables to customize the behavior of th...
import os import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim # Set environment variables os.environ['TORCH_NCCL_ASYNC_ERROR_HANDLING'] = '1' os.environ['TORCH_NCCL_BLOCKING_WAIT'] = '1' os.environ['TORCH_NCCL_ENABLE_TIMING'] = '1' os.environ['TORCH_NCCL_TRACE_BUFFER_SIZE'] ...
# Since we can't directly test distributed computing in an isolated test environment, # the tests will mainly focus on ensuring that the script can be imported and executed # without syntax errors and can detect the specified environment variables correctly. def test_environment_variables(): import os assert o...
[]
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\n\ndef setup_environment():\n # Set environment variabl...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00040720", "row_id": 40720, "seed_ids": "[5]" }
0.537937
Docs: Pytorch_40720
I
[ "setup_process", "train" ]
2
[ [ "train", "setup_process" ] ]
1
[]
false
[ "SimpleModel" ]
true
pytest
true
[ "torch" ]
false
882acb2941541642bd3bbb162a78f8325022a57e
0c1f4a2532f266a897595a1a0c33986563dff190
v1.0
instruct
Docs
Docs: Python310_40741_I
#### Objective To assess the students' understanding of asynchronous programming with the `asyncio` module in Python, evaluating their ability to create and handle coroutines, manage concurrency, and address common pitfalls. #### Problem Statement You are tasked with designing a concurrent application that processes...
import asyncio import random import logging async def process_task(task_id): """ Simulates processing a task by sleeping for a random duration and printing a completion message. """ await asyncio.sleep(random.uniform(0.1, 1.0)) print(f"Task {task_id} completed") async def main(tasks): """ ...
import pytest import asyncio from solution import process_task, main def test_process_task(): """ Test that process_task runs without raising exceptions. """ async def run_task(): await process_task(1) asyncio.run(run_task()) assert True # If no exception is raised, the test passes de...
[ { "docstring": "Top-level code to run the asyncio application with proper\nexception handling and debug mode activated.", "function_declaration": "def run_application():", "function_name": "run_application", "parameter_list": "()" } ]
[ 1, 1, 0, 1, 1, 1, 0, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\nimport logging\n\nasync def process_task(task_id):\n \"\"\"\n Simulates processing a task by sleeping for a random duration\n an...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00040741", "row_id": 40741, "seed_ids": "[200]" }
0.592358
Docs: Python310_40741
I
[ "process_task", "main", "run_application" ]
3
[ [ "run_application", "main" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f10186594cc4922e5df8828c50c23df39d2ffd0b
b5463a8509df177c6c83baca2771ae73fe058da0
v1.0
instruct
Docs
Docs: Pytorch_40800_I
You are tasked with implementing a distributed system using the PyTorch distributed RPC framework. Your system needs to coordinate computations across multiple workers while correctly managing remote references (RRef) to avoid premature deletion of shared objects. ### Instructions 1. Set up a distributed environment ...
import torch import torch.distributed.rpc as rpc from torch.distributed.rpc import RRef import torch.multiprocessing as mp def initialize_workers(rank, world_size): """ This function initializes the RPC framework on each worker. """ options = rpc.TensorPipeRpcBackendOptions(num_worker_threads=16) r...
import pytest import torch import torch.distributed.rpc as rpc from torch.multiprocessing import Process from solution import main def run_main(world_size): """ Helper function to run the main function in a multi-process environment. """ rpc.init_rpc("tester", rank=0, world_size=world_size, rpc_backend...
[ { "docstring": "This function initializes the RPC framework on each worker.", "function_declaration": "def initialize_workers(rank, world_size):", "function_name": "initialize_workers", "parameter_list": "(rank, world_size)" }, { "docstring": "Creates a tensor on worker0.", "function_dec...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.distributed.rpc as rpc\nfrom torch.distributed.rpc import RRef\n\ndef initialize_workers():\n \"\"\"\n Initialize the RPC framework for...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00040800", "row_id": 40800, "seed_ids": "[158]" }
0.399765
Docs: Pytorch_40800
I
[ "initialize_workers", "worker0_tensor", "worker1_addition", "worker2_multiplication", "distribute_computation", "final_result", "main" ]
7
[ [ "distribute_computation", "worker0_tensor" ], [ "distribute_computation", "worker1_addition" ], [ "distribute_computation", "worker2_multiplication" ], [ "final_result", "distribute_computation" ] ]
4
[]
false
[]
false
pytest
true
[ "torch" ]
false
ab975cb8d749bf025fecdcfe38e4b910eba792d3
e4a751dcc9a07f251594ffa3ad4fab7d2106d28c
v1.0
instruct
Docs
Docs: Python310_40820_I
### Question: Handling Special Exceptions in Asynchronous Programming You are tasked with writing an asynchronous function that performs read and write operations on multiple files. This function should handle various exceptions from the `asyncio` module that may be raised during these operations. #### Function Signa...
import asyncio async def read_file(file_path, timeout): try: with open(file_path, "rb") as file: return await asyncio.wait_for(file.read(), timeout=timeout) except asyncio.TimeoutError: return None, "Read operation timed out" except asyncio.CancelledError as e: return No...
import asyncio import pytest from solution import read_write_async @pytest.mark.asyncio async def test_read_write_async_success(): files = ["test_file1.txt", "test_file2.txt"] for file in files: with open(file, "wb") as f: f.write(b"Initial data") data = b"Example data" timeout = 5....
[]
[ 1, 1, 1, 0, 0, 1, 0, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def read_write_async(files: list, data: bytes, timeout: float) -> dict:\n results = {}\n\n async def read(file_path):\n await async...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00040820", "row_id": 40820, "seed_ids": "[396]" }
0.556393
Docs: Python310_40820
I
[ "read_file", "write_file", "read_write_async" ]
3
[ [ "read_write_async", "read_file" ], [ "read_write_async", "write_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
0397f68effbf4c888893ac3ee6772a1366f5e49b
a802934c8f80341bde06a9267a1ae9c611d68911
v1.0
instruct
Docs
Docs: Python310_40869_I
**Title: Implementing a Custom Python 2 to Python 3 Transformation** **Objective:** You are required to manually implement a function that transforms a piece of Python 2.x code to Python 3.x code by applying specific fixers. This exercise will test your understanding of common compatibility issues between Python 2 and...
import re from typing import List def print_fixer(code: str) -> str: """ Convert Python 2 print statements to Python 3 print function. """ return re.sub(r'print (.*)', r'print(\1)', code) def raw_input_fixer(code: str) -> str: """ Convert Python 2 raw_input() to Python 3 input(). """ r...
from solution import transform_code def test_print_fixer(): code = '''print "Hello, World!"''' expected = '''print("Hello, World!")''' assert transform_code(code, ["print"]) == expected def test_raw_input_fixer(): code = '''name = raw_input()''' expected = '''name = input()''' assert transform...
[ { "docstring": "Convert Python 2 print statements to Python 3 print function.", "function_declaration": "def print_fixer(code):", "function_name": "print_fixer", "parameter_list": "(code)" }, { "docstring": "Convert Python 2 raw_input() to Python 3 input().", "function_declaration": "def...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nfrom typing import List\n\ndef fix_print(code: str) -> str:\n \"\"\"\n Fix the print statements from Python 2 style to Python 3 style.\n \"\"\"\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00040869", "row_id": 40869, "seed_ids": "[308]" }
0.499507
Docs: Python310_40869
I
[ "print_fixer", "raw_input_fixer", "except_fixer", "transform_code" ]
4
[ [ "transform_code", "except_fixer" ], [ "transform_code", "print_fixer" ], [ "transform_code", "raw_input_fixer" ] ]
3
[]
false
[]
false
pytest
true
[]
true
54bd13a43c92939ebd47e8b76adab312226da5a0
f156900cf3dfe8215026825638ade1b96a7ff025
v1.0
instruct
Docs
Docs: Python310_40875_I
### Question: Context Management with `contextvars` in Python #### Objective: Your task is to demonstrate your understanding of the `contextvars` module by implementing a function that manages context-local state and performs a specific computation asynchronously. #### Problem Statement: Implement a function `process...
import asyncio import contextvars from typing import List, Dict # Define context variable to store the current dictionary context = contextvars.ContextVar('context', default={}) async def process_number(number: int) -> int: # Get the current context state ctx = context.get() # Double the number double...
import pytest import asyncio from solution import process_numbers, get_context_summary @pytest.mark.asyncio async def test_process_numbers(): numbers = [1, 2, 3] expected_doubled = [2, 4, 6] result = await process_numbers(numbers) assert result == expected_doubled context_summary = get_context_summ...
[ { "docstring": null, "function_declaration": "def get_context_summary():", "function_name": "get_context_summary", "parameter_list": "()" } ]
[ 0, 1, 0, 0, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import contextvars\nimport asyncio\nfrom typing import List, Dict\n\n# Define the context variable at the module level\ncontext_data = contextvars.ContextVar('context_d...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00040875", "row_id": 40875, "seed_ids": "[392]" }
0.563358
Docs: Python310_40875
I
[ "process_number", "process_numbers", "get_context_summary" ]
3
[ [ "process_numbers", "process_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ed05e63746f36e090e7e3757d0e992d4ce7b3d04
2dfe529b91e4a35d3fbc442ff36945f7473e9a13
v1.0
instruct
Docs
Docs: Python310_40883_I
### Python Coding Assessment Question #### Objective To assess your proficiency in using Python's `multiprocessing` module to create and manage processes, establish communication between them, and ensure proper synchronization. #### Problem Statement You are tasked with creating a parallel processing system using Pyt...
from multiprocessing import Pool, Queue, Lock, Process def calculate_square(n): return n ** 2 def worker_task(n, output_queue, lock): result = calculate_square(n) with lock: print(f"Process-{n}: {n}^2 = {result}") output_queue.put(result) def main(): numbers = list(range(1, 21)) pool ...
from solution import calculate_square, worker_task from multiprocessing import Queue, Lock def test_calculate_square(): assert calculate_square(2) == 4 assert calculate_square(3) == 9 assert calculate_square(4) == 16 def test_worker_task(capsys): output_queue = Queue() lock = Lock() # Tes...
[ { "docstring": null, "function_declaration": "def calculate_square(n):", "function_name": "calculate_square", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def worker_task(n, output_queue, lock):", "function_name": "worker_task", "parameter_list": "(n, ...
[ 0, 0, 0, 0, 1, 1, 0, 1, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from multiprocessing import Pool, Queue, Lock, current_process\n\ndef calculate_square(n):\n \"\"\"\n Returns the square of the given number n.\n \"\"\"\n r...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00040883", "row_id": 40883, "seed_ids": "[338]" }
0.633361
Docs: Python310_40883
I
[ "calculate_square", "worker_task", "main" ]
3
[ [ "worker_task", "calculate_square" ] ]
1
[]
false
[]
false
pytest
true
[]
true
efaa04f962b84bef652ac752e8c925f2640cf802
0484dbc1df000bab5ebf90a9c7e0494c64a085a3
v1.0
instruct
Docs
Docs: Python310_40968_I
### Question: Create a Text Adventure Game Using Python `curses` Module As a programming challenge, you will create a simple text adventure game using the `curses` module. In this game, the player explores a grid-based dungeon, moving their character '@' around and avoiding or interacting with various objects. #### ...
import curses import random def start_curses_app(stdscr): curses.curs_set(0) # Hide cursor stdscr.keypad(True) # Enable special keys curses.start_color() height, width = 20, 20 treasures_collected = 0 game_over = False # Create dungeon and place elements dungeon, player_pos = cr...
import pytest from solution import create_dungeon, handle_movement def test_initial_dungeon(): height, width = 20, 20 dungeon, player_pos = create_dungeon(height, width) assert len(dungeon) == height assert len(dungeon[0]) == width assert dungeon[1][1] == '@' walls = [dungeon[i][0] == '#' and...
[ { "docstring": null, "function_declaration": "def start_curses_app(stdscr):", "function_name": "start_curses_app", "parameter_list": "(stdscr)" }, { "docstring": null, "function_declaration": "def create_dungeon(height, width):", "function_name": "create_dungeon", "parameter_list...
[ 1, 1, 0, 0, 1, 0, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import curses\nimport random\n\ndef start_curses_app(stdscr):\n curses.curs_set(0) # Hide cursor\n stdscr.keypad(True) # Enable special keys\n curses.start_c...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00040968", "row_id": 40968, "seed_ids": "[294]" }
0.505305
Docs: Python310_40968
I
[ "start_curses_app", "create_dungeon", "place_randomly", "render_dungeon", "handle_movement", "main" ]
6
[ [ "create_dungeon", "place_randomly" ], [ "start_curses_app", "create_dungeon" ], [ "start_curses_app", "handle_movement" ], [ "start_curses_app", "render_dungeon" ] ]
4
[]
false
[]
false
pytest
true
[]
true
723dc6b0e08ad0a7dcc36e44f1456e07431cf74c
7f83a6923f5faecadef4dd224234b58b2099d46e
v1.0
instruct
Docs
Docs: Pytorch_41001_I
**Advanced Distributed Training in PyTorch** ### Background Distributed training is an essential technique for scaling the training of neural network models across multiple GPUs or machines. PyTorch provides several optimizers to facilitate distributed training, such as `DistributedOptimizer`, `PostLocalSGDOptimizer`,...
import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim import torch.multiprocessing as mp import random # Define a simple neural network class SimpleNN(nn.Module): def __init__(self): super(SimpleNN, self).__init__() self.fc1 = nn.Linear(10, 50) self...
from solution import train_model_with_distributed_optimizer import pytest # This test requires the code to be executed within a proper distributed environment. # Hence, it's more of an E2E test. For simplicity, we won't run this here but this is # how one could structure the test. @pytest.mark.skip(reason="This test r...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\n\n# Si...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00041001", "row_id": 41001, "seed_ids": "[137]" }
0.52725
Docs: Pytorch_41001
I
[ "setup", "cleanup", "synthetic_data", "train", "train_model_with_distributed_optimizer" ]
5
[ [ "train", "cleanup" ], [ "train", "setup" ], [ "train", "synthetic_data" ], [ "train_model_with_distributed_optimizer", "train" ] ]
4
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
33f47696511cd6eb4ed466b204f64f94b405634b
4dbdea4b5f364226658a33a26a519704809cf24f
v1.0
instruct
Docs
Docs: Python310_41002_I
<|Analysis Begin|> The provided documentation is for Python's `traceback` module, which facilitates handling and manipulating stack tracebacks. Here's a summary of the significant features and functions covered in this documentation: 1. **Printing and Formatting**: - `traceback.print_tb()`, `traceback.print_except...
import traceback def log_exception_to_file(exc: Exception, file_path: str) -> None: """ Captures the exception details and writes them to a specified log file. Args: exc (Exception): The caught exception. file_path (str): The path to the log file where exception details should be written. ...
import os from solution import log_exception_to_file, raise_and_log_exception, forced_error def test_log_exception_to_file(): try: forced_error() except Exception as exc: log_exception_to_file(exc, 'test_error_log.txt') with open('test_error_log.txt', 'r') as f: contents = f.read()...
[ { "docstring": "Captures the exception details and writes them to a specified log file.\n\nArgs:\nexc (Exception): The caught exception.\nfile_path (str): The path to the log file where exception details should be written.", "function_declaration": "def log_exception_to_file(exc, file_path):", "function...
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import traceback\n\ndef log_exception_to_file(exc: Exception, file_path: str) -> None:\n \"\"\"\n Logs the details of an exception to a file.\n \n :param ex...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00041002", "row_id": 41002, "seed_ids": "[335]" }
0.42765
Docs: Python310_41002
I
[ "log_exception_to_file", "raise_and_log_exception", "forced_error" ]
3
[ [ "raise_and_log_exception", "forced_error" ], [ "raise_and_log_exception", "log_exception_to_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3777d974af3bf87b0dd0bfba683df472a92b5fb6
5db7d01b87b8a526e66471feb364c3a879921ec1
v1.0
instruct
Docs
Docs: Python310_41004_I
#### Objective Demonstrate your understanding of the `timeit` module in Python by writing a function that compares the performance of different implementations of a particular task. #### Task Implement the function `compare_sorting_algorithms` which: 1. Accepts a list of integers. 2. Compares the execution time of sor...
import timeit from typing import List, Dict import copy def bubble_sort(data: List[int]) -> List[int]: n = len(data) for i in range(n): for j in range(0, n-i-1): if data[j] > data[j+1]: data[j], data[j+1] = data[j+1], data[j] return data def quick_sort(data: List[int]) ...
from solution import compare_sorting_algorithms def test_compare_sorting_algorithms_basic(): data = [5, 3, 8, 6, 2, 7, 4, 1] results = compare_sorting_algorithms(data) assert set(results.keys()) == {'built-in', 'bubble_sort', 'quick_sort'} assert all(isinstance(value, float) for value in results.values...
[ { "docstring": null, "function_declaration": "def bubble_sort(data):", "function_name": "bubble_sort", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def quick_sort(data):", "function_name": "quick_sort", "parameter_list": "(data)" }, { "docst...
[ 1, 1, 0, 0, 1, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import timeit\nfrom typing import List, Dict\n\ndef bubble_sort(data: List[int]) -> List[int]:\n arr = data[:]\n n = len(arr)\n for i in range(n):\n for...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00041004", "row_id": 41004, "seed_ids": "[328]" }
0.557379
Docs: Python310_41004
I
[ "bubble_sort", "quick_sort", "compare_sorting_algorithms" ]
3
[ [ "compare_sorting_algorithms", "bubble_sort" ], [ "compare_sorting_algorithms", "quick_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a7b45474ad206c154911a32784253b4fc4d11a63
f6f2e4d68ff66840a0eaf67f9ae3d64b0c89c203
v1.0
instruct
Docs
Docs: Python310_41051_I
**Objective**: To evaluate your understanding of the `contextvars` module and its integration with asynchronous programming in Python. **Problem Statement**: You are required to implement an asynchronous logging system that keeps track of user-specific events. Each user interaction should be logged with a unique iden...
import contextvars import asyncio # Define the context variable to store the user ID user_id_var = contextvars.ContextVar('user_id') def log_event(event: str) -> None: """ Logs the event message along with the current user ID retrieved from the context variable. """ user_id = user_id_var.get() pri...
import asyncio from io import StringIO import sys from solution import log_event, handle_user_interaction, main def test_log_event(): user_id_var.set(99) old_stdout = sys.stdout sys.stdout = mystdout = StringIO() log_event("Test Event") assert mystdout.getvalue() == "User 99: Test Event\n" sys...
[ { "docstring": "Logs the event message along with the current user ID retrieved from the context variable.", "function_declaration": "def log_event(event):", "function_name": "log_event", "parameter_list": "(event)" } ]
[ 1, 0, 1, 0, 1, 0, 1, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\n\n# Define a context variable to store the user ID\nuser_id_var = contextvars.ContextVar('user_id', default=None)\n\ndef log_event(e...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00041051", "row_id": 41051, "seed_ids": "[392]" }
0.414248
Docs: Python310_41051
I
[ "log_event", "handle_user_interaction", "main" ]
3
[ [ "handle_user_interaction", "log_event" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8cf3c0bb903b7f29a82f9d8746ed61b31f00439f
05e742ddc1ac0e39770b06fc62b52dcabc83fb5d
v1.0
instruct
Docs
Docs: Pytorch_41095_I
You are tasked with implementing a fault-tolerant distributed training loop using PyTorch. The goal is to demonstrate your understanding of distributed multiprocessing and how to handle errors that occur within a distributed setting. You must utilize the provided `torch.distributed.elastic.multiprocessing.errors` modul...
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist import torch.multiprocessing as mp from torch.distributed.elastic.multiprocessing.errors import ( record, ChildFailedError, ErrorHandler, ProcessFailure ) import random import logging logging.basicConfig(lev...
from solution import distributed_training_loop def test_distributed_training_loop(): try: distributed_training_loop() except ChildFailedError as e: assert isinstance(e, ChildFailedError) except ProcessFailure as e: assert isinstance(e, ProcessFailure) else: assert True ...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nfrom torch.distributed.elastic.multiprocessing.errors import record,...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00041095", "row_id": 41095, "seed_ids": "[147]" }
0.418861
Docs: Pytorch_41095
I
[ "train", "distributed_training_loop" ]
2
[ [ "distributed_training_loop", "train" ] ]
1
[]
false
[ "SimpleModel" ]
true
pytest
true
[ "torch" ]
false
99c5b62bd66beb6a420f3f4e089d6133e35a6a54
8589c789dfc518793a158e42042f1267565aed75
v1.0
instruct
Docs
Docs: Scikit_41105_I
### Coding Challenge: Implementing Custom Pairwise Distance Function #### Objective: Your task is to implement a custom function that calculates pairwise distances between samples using various distance metrics supported by `scikit-learn`. In addition to implementing standard metrics, you will also implement a custom ...
import numpy as np from sklearn.metrics import pairwise_distances def custom_distance(a, b): """ Custom distance metric defined as: d_custom(a, b) = sqrt(sum((a - b)^2) / (1 + sum((a + b)^2))) """ return np.sqrt(np.sum((a - b) ** 2) / (1 + np.sum((a + b) ** 2))) def compute_pairwise_distances(X, Y...
import numpy as np import pytest from solution import compute_pairwise_distances def test_euclidean_distances(): X = np.array([[2, 3], [3, 5], [5, 8]]) Y = np.array([[1, 0], [2, 1]]) expected = pairwise_distances(X, Y, metric='euclidean') result = compute_pairwise_distances(X, Y, metric='euclidean') ...
[ { "docstring": "Custom distance metric defined as:\nd_custom(a, b) = sqrt(sum((a - b)^2) / (1 + sum((a + b)^2)))", "function_declaration": "def custom_distance(a, b):", "function_name": "custom_distance", "parameter_list": "(a, b)" }, { "docstring": "Computes pairwise distances between the r...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.metrics import pairwise_distances\n\ndef custom_metric(a, b):\n \"\"\"\n Custom distance metric: sqrt(sum((a - b)^2) / (1 + sum((...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00041105", "row_id": 41105, "seed_ids": "[38]" }
0.653528
Docs: Scikit_41105
I
[ "custom_distance", "compute_pairwise_distances" ]
2
[ [ "compute_pairwise_distances", "custom_distance" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
398e16f7fe811555db6535550c68dca59b47db03
7554ec28cdc9a0a4fe73740f00da2affa8105073
v1.0
instruct
Docs
Docs: Python310_41117_I
### Complex Number Operations using Py_complex Struct Your task is to implement a function that takes four parameters: two complex numbers, each represented by a tuple of two floats (real and imaginary parts), and a string specifying the operation to perform. The function should return the result of the specified oper...
class Py_complex: def __init__(self, real, imag): self.real = real self.imag = imag def _Py_c_sum(left, right): return Py_complex(left.real + right.real, left.imag + right.imag) def _Py_c_diff(left, right): return Py_complex(left.real - right.real, left.imag - right.imag) def _Py_c_neg(nu...
from solution import complex_operation def test_add(): assert complex_operation((1.0, 2.0), (3.0, 4.0), "add") == (4.0, 6.0) def test_subtract(): assert complex_operation((1.0, 2.0), (3.0, 4.0), "subtract") == (-2.0, -2.0) def test_negate(): assert complex_operation((1.0, 2.0), (0.0, 0.0), "negate") == (...
[]
[ 1, 0, 0, 1, 1, 0, 1, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Py_complex:\n def __init__(self, real, imag):\n self.real = real\n self.imag = imag\n\ndef _Py_c_sum(left, right):\n return Py_complex(left.re...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00041117", "row_id": 41117, "seed_ids": "[1]" }
0.578953
Docs: Python310_41117
I
[ "_Py_c_sum", "_Py_c_diff", "_Py_c_neg", "_Py_c_prod", "_Py_c_quot", "_Py_c_pow", "complex_operation" ]
7
[ [ "complex_operation", "_Py_c_diff" ], [ "complex_operation", "_Py_c_neg" ], [ "complex_operation", "_Py_c_pow" ], [ "complex_operation", "_Py_c_prod" ], [ "complex_operation", "_Py_c_quot" ], [ "complex_operation", "_Py_c_sum" ] ]
6
[]
false
[ "Py_complex" ]
true
pytest
true
[]
true
a60a08895798381c327c812ef3d74c345a046ed1
a0b4519f6356d70b52352d186cc85630c2303b98
v1.0
instruct
Docs
Docs: Pytorch_41147_I
### Advanced PyTorch DataLoader Implementation #### Objective: Create an efficient custom data loading pipeline using `torch.utils.data.DataLoader`, demonstrating mastery of: 1. Custom collate functions. 2. Handling both map-style and iterable-style datasets. 3. Optimizing data loading with multi-process workers and m...
import torch from torch.utils.data import DataLoader, Dataset, IterableDataset import random import numpy as np class CustomMapDataset(Dataset): def __init__(self, data): self.data = data def __getitem__(self, index): image, label = self.data[index] image_tensor = torch.tensor(image, d...
import pytest import torch from solution import CustomMapDataset, CustomIterableDataset, custom_collate_fn from torch.utils.data import DataLoader def test_custom_map_dataset(): data = [([1, 2, 3], 1), ([4, 5, 6, 7], 0)] dataset = CustomMapDataset(data) assert len(dataset) == 2 image, label = dataset[0...
[]
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import torch\nfrom torch.utils.data import DataLoader, Dataset, IterableDataset\nimport torch.nn.functional as F\nimport numpy as np\n\nclass C...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00041147", "row_id": 41147, "seed_ids": "[78]" }
0.38178
Docs: Pytorch_41147
I
[ "pad_sequence", "custom_collate_fn", "main" ]
3
[ [ "custom_collate_fn", "pad_sequence" ] ]
1
[]
false
[ "CustomMapDataset", "CustomIterableDataset" ]
true
pytest
true
[ "numpy", "torch" ]
false
ac2d3857dccb7abca1358602b6be133eff825c26
cb0301fdb89abcd61d6d99ef14fa5f7fac981b6a
v1.0
instruct
Docs
Docs: Python310_41188_I
#### Objective Your task is to build a simple file download manager using `asyncio`. The file download manager should be able to handle multiple downloads concurrently, manage the download queue, and handle timeouts and cancellations. #### Requirements 1. **Function: `download_file(url: str) -> None`** - This fu...
import asyncio import random from typing import List async def download_file(url: str) -> None: try: print(f"Starting download from {url}") await asyncio.sleep(random.randint(1, 5)) print(f"Completed download from {url}") except asyncio.CancelledError: print(f"Download from {url...
import asyncio import pytest from unittest.mock import patch from solution import download_file, manage_downloads @pytest.mark.asyncio async def test_download_file(): url = "http://example.com/file" with patch("random.randint", return_value=2): await download_file(url) @pytest.mark.asyncio async def ...
[]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\nfrom typing import List\n\nasync def download_file(url: str) -> None:\n try:\n print(f\"Starting download from {url}\")\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00041188", "row_id": 41188, "seed_ids": "[360]" }
0.50251
Docs: Python310_41188
I
[ "download_file", "manage_downloads" ]
2
[ [ "manage_downloads", "download_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8e6b49115ab77574e5691974b089993175e89706
7c23a01e4356325cdc9e9a2c8b683275ba23254c
v1.0
instruct
Docs
Docs: Pytorch_41209_I
As a developer, your task is to implement a PyTorch-based neural network model to perform a simple binary classification. The model and data should leverage the MPS backend to utilize the GPU on a macOS device with Metal Performance Shaders. #### Requirements: 1. **Check MPS Availability**: Implement a check to verify...
import torch import torch.nn as nn import torch.optim as optim def check_mps_available(): """ Check if the MPS device is available on this machine. """ if not torch.backends.mps.is_available(): if not torch.backends.mps.is_built(): raise EnvironmentError("MPS not available because t...
import pytest import torch from solution import ( check_mps_available, create_synthetic_data, SimpleNN, train_model ) def test_check_mps_available(): if not torch.backends.mps.is_available(): with pytest.raises(EnvironmentError): check_mps_available() else: assert ch...
[]
[ 1, 0, 1, 0, 1, 0, 0, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\n# Check that MPS is available\ndef check_mps_availability():\n if not torch.backends.mps.is_avail...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00041209", "row_id": 41209, "seed_ids": "[167]" }
0.464658
Docs: Pytorch_41209
I
[ "check_mps_available", "create_synthetic_data", "train_model" ]
3
[ [ "train_model", "check_mps_available" ], [ "train_model", "create_synthetic_data" ] ]
2
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
05bd8f004fff46e835444f8b1b9d0634835cbe33
88cf7619f75b5dd752ec057b436615a03e7633be
v1.0
instruct
Docs
Docs: Python310_41276_I
### Problem Description You are required to simulate a simplified data processing pipeline using concurrent execution techniques. The pipeline consists of three stages: 1. **Data Generation**: Generate a list of integers. 2. **Data Processing**: Multiply each integer by 2. 3. **Data Aggregation**: Calculate the sum o...
import random import threading from multiprocessing import Pool from concurrent.futures import ThreadPoolExecutor def generate_data(N): random.seed(42) # For reproducibility in tests return [random.randint(1, 100) for _ in range(N)] def process_data_chunk(chunk): return [x * 2 for x in chunk] def execut...
from solution import execute_pipeline, generate_data, process_data_chunk def test_generate_data(): data = generate_data(10) assert len(data) == 10 assert all(1 <= x <= 100 for x in data) def test_process_data_chunk(): chunk = [1, 2, 3, 4, 5] result = process_data_chunk(chunk) assert result == ...
[ { "docstring": null, "function_declaration": "def generate_data(N):", "function_name": "generate_data", "parameter_list": "(N)" }, { "docstring": null, "function_declaration": "def process_data_chunk(chunk):", "function_name": "process_data_chunk", "parameter_list": "(chunk)" }...
[ 1, 1, 0, 0, 0, 0, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport threading\nfrom multiprocessing import Pool\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef generate_data(N):\n \"\"\"\n Generates...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00041276", "row_id": 41276, "seed_ids": "[206]" }
0.582513
Docs: Python310_41276
I
[ "generate_data", "process_data_chunk", "execute_pipeline" ]
3
[ [ "execute_pipeline", "generate_data" ], [ "execute_pipeline", "process_data_chunk" ] ]
2
[]
false
[]
false
pytest
true
[]
true
926d7df596ed54807efa21f339c040c030175ef5
4cd15d0e52b9303d6e99f70182b7175cac7ec3dc
v1.0
instruct
Docs
Docs: Python310_41295_I
**Question Title**: Implementing and Managing Concurrent Execution in Python **Objective**: Write a Python program that demonstrates the use of threading and multiprocessing for concurrent execution. Your solution must include the creation and management of threads and processes, as well as synchronization mechanisms....
import threading import multiprocessing from typing import List, Dict, Tuple def cpu_bound_task(n: int) -> int: """ Computes the sum of the first n natural numbers. """ return n * (n + 1) // 2 def io_bound_task(filename: str) -> int: """ Reads a file and returns the number of lines in the file...
import os import pytest from solution import cpu_bound_task, io_bound_task, scheduler def test_cpu_bound_task(): assert cpu_bound_task(5) == 15 assert cpu_bound_task(100) == 5050 assert cpu_bound_task(0) == 0 def test_io_bound_task(tmpdir): file_path = tmpdir.join("testfile.txt") file_path.write("...
[ { "docstring": "Computes the sum of the first n natural numbers.", "function_declaration": "def cpu_bound_task(n):", "function_name": "cpu_bound_task", "parameter_list": "(n)" }, { "docstring": "Reads a file and returns the number of lines in the file.", "function_declaration": "def io_b...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import threading\nfrom multiprocessing import Process, Pipe\nimport os\n\ndef cpu_bound_task(n: int) -> int:\n \"\"\"\n CPU-bound task that computes the sum of th...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00041295", "row_id": 41295, "seed_ids": "[206]" }
0.594158
Docs: Python310_41295
I
[ "cpu_bound_task", "io_bound_task", "execute_task", "scheduler" ]
4
[ [ "execute_task", "cpu_bound_task" ], [ "execute_task", "io_bound_task" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a9c348aa72b5d53d9f9a2a84147926674bd4f6dd
6a7558887807fc8c8e3dcd7753690538d21815ea
v1.0
instruct
Docs
Docs: Python310_41359_I
**Problem Statement** You are required to implement a set of functions to process and manipulate sequences of data efficiently using functional programming techniques. Specifically, you will need to create generators, use iterators, and employ modules like `itertools` and `functools`. ### Objective Implement the fol...
from typing import Iterator import itertools def fibonacci_seq(n: int) -> Iterator[int]: """ Generates the first n numbers of the Fibonacci sequence. :param n: Number of Fibonacci numbers to generate :return: Iterator of the first n Fibonacci numbers """ def fibonacci_gen(): a, b = 0, 1...
import pytest from solution import ( fibonacci_seq, filter_primes, sum_of_combinations ) def test_fibonacci_seq(): assert list(fibonacci_seq(1)) == [0] assert list(fibonacci_seq(2)) == [0, 1] assert list(fibonacci_seq(5)) == [0, 1, 1, 2, 3] assert list(fibonacci_seq(10)) == [0, 1, 1, 2, 3, ...
[ { "docstring": "Generates the first n numbers of the Fibonacci sequence.\n:param n: Number of Fibonacci numbers to generate\n:return: Iterator of the first n Fibonacci numbers", "function_declaration": "def fibonacci_seq(n):", "function_name": "fibonacci_seq", "parameter_list": "(n)" }, { "d...
[ 0, 1, 0, 1, 1, 1, 0, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import Iterator\nimport itertools\nimport math\n\ndef fibonacci_seq(n: int) -> Iterator[int]:\n \"\"\"\n Generates the first `n` numbers of the Fibona...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00041359", "row_id": 41359, "seed_ids": "[78]" }
0.608746
Docs: Python310_41359
I
[ "fibonacci_seq", "is_prime", "filter_primes", "sum_of_combinations" ]
4
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7de150d377d84e51290c1047ed1ba1e6b40eac66
c05d4165d128a0952b3071464082b671f1ec3924
v1.0
instruct
Docs
Docs: Python310_41374_I
**Objective:** Design and implement a Python function using the `gzip` module to compress files in a given directory and then decompress them into another specified directory, while handling possible exceptions. **Problem Statement:** Write a Python function `compress_and_decompress_files(input_dir: str, compressed_di...
import os import gzip import shutil import logging def compress_file(input_path, output_path): try: with open(input_path, 'rb') as f_in, gzip.open(output_path, 'wb', compresslevel=9) as f_out: shutil.copyfileobj(f_in, f_out) except Exception as e: logging.error(f"Failed to compress ...
import os import shutil import pytest from solution import compress_and_decompress_files # Set up test directories input_dir = 'test_input_dir' compressed_dir = 'test_compressed_dir' decompressed_dir = 'test_decompressed_dir' @pytest.fixture(scope="module", autouse=True) def setup_and_teardown(): # Setup: Create ...
[ { "docstring": null, "function_declaration": "def compress_file(input_path, output_path):", "function_name": "compress_file", "parameter_list": "(input_path, output_path)" }, { "docstring": null, "function_declaration": "def decompress_file(input_path, output_path):", "function_name"...
[ 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport gzip\nimport shutil\n\ndef compress_and_decompress_files(input_dir: str, compressed_dir: str, decompressed_dir: str) -> None:\n if not os.path.exis...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00041374", "row_id": 41374, "seed_ids": "[346]" }
0.749742
Docs: Python310_41374
I
[ "compress_file", "decompress_file", "compress_and_decompress_files" ]
3
[ [ "compress_and_decompress_files", "compress_file" ], [ "compress_and_decompress_files", "decompress_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
70fe7d7486c8c8a8f58d737ca034d452e8cc9268
5635492b2719d09259bc3f3d30086e8328c74238
v1.0
instruct
Docs
Docs: Python310_41376_I
**Question: Performance Benchmarking Using the `timeit` Module** The purpose of this exercise is to assess your understanding of the Python `timeit` module and your ability to benchmark the performance of different code snippets. ### Problem Statement: You are tasked with benchmarking the performance of three functio...
import timeit def square_using_loop(nums): result = [] for num in nums: result.append(num ** 2) return result def square_using_list_comprehension(nums): return [num ** 2 for num in nums] def square_using_map(nums): return list(map(lambda x: x ** 2, nums)) def benchmark_square_functions(n...
from solution import ( square_using_loop, square_using_list_comprehension, square_using_map, benchmark_square_functions ) def test_square_using_loop(): nums = [1, 2, 3, 4, 5] assert square_using_loop(nums) == [1, 4, 9, 16, 25] def test_square_using_list_comprehension(): nums = [1, 2, 3, 4,...
[ { "docstring": null, "function_declaration": "def square_using_loop(nums):", "function_name": "square_using_loop", "parameter_list": "(nums)" }, { "docstring": null, "function_declaration": "def square_using_list_comprehension(nums):", "function_name": "square_using_list_comprehensio...
[ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import timeit\n\ndef square_using_loop(nums):\n result = []\n for num in nums:\n result.append(num ** 2)\n return result\n\ndef square_using_list_compre...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00041376", "row_id": 41376, "seed_ids": "[328]" }
0.536781
Docs: Python310_41376
I
[ "square_using_loop", "square_using_list_comprehension", "square_using_map", "benchmark_square_functions" ]
4
[ [ "benchmark_square_functions", "square_using_list_comprehension" ], [ "benchmark_square_functions", "square_using_loop" ], [ "benchmark_square_functions", "square_using_map" ] ]
3
[]
false
[]
false
pytest
true
[]
true
6fd80af8c94e7518ff046aa3a14a05b5fe862588
dc758284c5d0dbb575d3a68a78d1fc54f1591448
v1.0
instruct
Docs
Docs: Python310_41378_I
**Question:** ### Asynchronous File Downloader using `asyncio` You are required to implement an asynchronous file downloader using Python's `asyncio` module. Your downloader should be capable of downloading multiple files concurrently and reporting the progress of each download. #### Requirements: 1. Write an asynch...
import aiohttp import asyncio import os from typing import List async def download_file(url: str, destination: str) -> None: async with aiohttp.ClientSession() as session: async with session.get(url) as response: response.raise_for_status() total_size = int(response.headers.get('con...
import aiohttp import asyncio import os import pytest from unittest.mock import patch, mock_open from solution import download_file, download_files @pytest.mark.asyncio async def test_download_file_success(): url = "http://example.com/file1.txt" destination = "./downloads/file1.txt" # Mock the aiohtt...
[]
[ 1, 1, 1, 1, 0, 0, 0, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import aiohttp\nimport asyncio\nimport os\nfrom typing import List\n\nasync def download_file(url: str, destination: str) -> None:\n \"\"\"\n Downloads a file fro...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041378", "row_id": 41378, "seed_ids": "[270]" }
0.582803
Docs: Python310_41378
I
[ "download_file", "download_files" ]
2
[ [ "download_files", "download_file" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
d2bc6077f0a0c12e737f17a8fefb2b1ed79afcf5
12000c0f94ed927b90304be029cfa564332ae18c
v1.0
instruct
Docs
Docs: Python310_41458_I
### Asyncio Currency Conversion Tasks You are required to build a small asyncio program that concurrently fetches and processes currency conversion rates from multiple sources. #### Problem Statement Implement a function `fetch_conversion_rate(source: str) -> float` which simulates fetching a conversion rate from di...
import asyncio import random from typing import List async def fetch_conversion_rate(source: str) -> float: """ Simulates fetching a conversion rate from a given source. Args: - source: str: The name of the source. Returns: - float: A mock conversion rate between 0.8 and 1.2. """ ...
import asyncio import pytest from solution import fetch_conversion_rate, get_average_conversion_rate # Helper coroutine to run async tests def run(coro): return asyncio.run(coro) # Test for fetch_conversion_rate function to check return type and value range def test_fetch_conversion_rate(): rate = run(fetch_c...
[]
[ 1, 1, 0, 1, 1, 1, 1, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\nfrom typing import List\n\nasync def fetch_conversion_rate(source: str) -> float:\n \"\"\" Simulate fetching a conversion rate from a ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00041458", "row_id": 41458, "seed_ids": "[360]" }
0.592776
Docs: Python310_41458
I
[ "fetch_conversion_rate", "get_average_conversion_rate" ]
2
[ [ "get_average_conversion_rate", "fetch_conversion_rate" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cf43709bc0e04cb14777a1d6b46fdf96f45bd48e
d89b3c42602fa259ddd2b9b93e021437486589e5
v1.0
instruct
Docs
Docs: Python310_41480_I
### Python Coding Assessment #### Objective: To assess your understanding of the Python `warnings` module, including issuing warnings, handling them through filtering mechanisms, and using context managers to manage the behavior of warnings. #### Problem Statement: You are required to implement a set of functions to...
import warnings def issue_warnings(): """ Issue a DeprecationWarning and a UserWarning. """ warnings.warn("Deprecated feature", DeprecationWarning) warnings.warn("User alert", UserWarning) def set_warning_filter(action, category): """ Set a filter on warnings using warnings.filterwarnings(...
import warnings from solution import issue_warnings, set_warning_filter, suppress_warnings_temporarily, test_warnings def test_issue_warnings(): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") issue_warnings() assert len(w) == 2 assert any(isinstance(...
[ { "docstring": "Issue a DeprecationWarning and a UserWarning.", "function_declaration": "def issue_warnings():", "function_name": "issue_warnings", "parameter_list": "()" }, { "docstring": "Set a filter on warnings using warnings.filterwarnings().\n\nParameters:\n- action (str): The action t...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import warnings\n\ndef issue_warnings():\n \"\"\"\n Issues two types of warnings:\n - DeprecationWarning with the message \"Deprecated feature\".\n - UserWa...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00041480", "row_id": 41480, "seed_ids": "[125]" }
0.509153
Docs: Python310_41480
I
[ "issue_warnings", "set_warning_filter", "suppress_warnings_temporarily", "test_warnings" ]
4
[ [ "test_warnings", "issue_warnings" ], [ "test_warnings", "set_warning_filter" ], [ "test_warnings", "suppress_warnings_temporarily" ] ]
3
[]
false
[]
false
pytest
true
[]
true
202e38d08b422d93b83b64e1c7cb1e9f32a9afe1
c957bb08192fb2af6588ee3ff73336f8d3804e4a
v1.0
instruct
Docs
Docs: Python310_41490_I
### Advanced Curses Window Management in Python Let's create a text-based user interface that mimics a basic text viewer/editor: **Task**: Implement a Python program using the `curses` module to create a scrollable text viewer. **Requirements**: 1. Initialize the `curses` library and create a window (`stdscr`) that ...
import curses def main(stdscr): """ Main function to run the scrollable text viewer using curses. """ # Turn off cursor blinking curses.curs_set(0) # Load a large block of text (hardcoded for this example) lines = [f"Line {i}: This is a sample text viewer using Python curses." for i in ran...
import curses from unittest import mock from io import StringIO from solution import run_curses_program def test_curses_program_initialization(): """ Test if the curses program initializes and closes without error. """ with mock.patch('curses.wrapper') as mock_curses_wrapper: run_curses_program...
[ { "docstring": "Main function to run the scrollable text viewer using curses.", "function_declaration": "def main(stdscr):", "function_name": "main", "parameter_list": "(stdscr)" }, { "docstring": "Function to properly start the curses application.", "function_declaration": "def run_curs...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import curses\n\ndef main(stdscr):\n # Disable cursor blinking\n curses.curs_set(0)\n \n # Load a large block of text (hard-coded for the example)\n line...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00041490", "row_id": 41490, "seed_ids": "[74]" }
0.405696
Docs: Python310_41490
I
[ "main", "run_curses_program" ]
2
[ [ "run_curses_program", "main" ] ]
1
[]
false
[]
false
pytest
true
[]
true
be71b65b9a7bb6963d56988e7a840bb4ba7e6606
858809ffda2fb09a73c91f237ab89cf110492852
v1.0
instruct
Docs
Docs: Python310_41559_I
#### Objective: Write a Python program where you will: 1. Use the `sys` module to add an audit hook. 2. Implement a memory tracing function to track and print the memory allocation of a specific function. 3. Monitor and record the number of times specific events (e.g., function calls) are triggered during the program's...
import sys # Part 1: Add Audit Hook def audit_hook(event, args): print(f"Audit Event: {event}, Arguments: {args}") sys.addaudithook(audit_hook) # Part 2: Memory Tracing Decorator def memory_tracer(func): def wrapper(*args, **kwargs): before = sys.getallocatedblocks() result = func(*args, **kw...
from solution import memory_tracer, example_function, monitor_events, audit_hook import sys def test_audit_hook(capsys): audit_hook("test_event", ("arg1", "arg2")) captured = capsys.readouterr() assert "Audit Event: test_event, Arguments: ('arg1', 'arg2')" in captured.out def test_memory_tracer(capsys): ...
[ { "docstring": null, "function_declaration": "def audit_hook(event, args):", "function_name": "audit_hook", "parameter_list": "(event, args)" }, { "docstring": null, "function_declaration": "def memory_tracer(func):", "function_name": "memory_tracer", "parameter_list": "(func)" ...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\n\n# Part 1: Add Audit Hook\ndef audit_hook(event, args):\n print(f\"Audit Event: {event}, Arguments: {args}\")\n\nsys.addaudithook(audit_hook)\n\n# Part ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00041559", "row_id": 41559, "seed_ids": "[348]" }
0.561279
Docs: Python310_41559
I
[ "audit_hook", "memory_tracer", "example_function", "trace_function", "monitor_events" ]
5
[ [ "monitor_events", "example_function" ], [ "monitor_events", "trace_function" ] ]
2
[]
false
[]
false
pytest
true
[]
true
45bc335b11a4eecff78a975512b22e39c21d376e
3a8620b401c776dfa50656b1a84c1fb00126a728
v1.0
instruct
Docs
Docs: Python310_41653_I
### Priority Queue Management with Dynamic Tasks **Objective:** Implement a priority queue system using the `heapq` module, accommodating dynamic task priorities. This exercise will test your understanding of heap operations, dynamic updates, and efficient algorithms. **Scenario:** You are managing tasks with varying...
import heapq import itertools REMOVED = '<removed-task>' counter = itertools.count() def add_task(pq, entry_finder, task, priority): """ Adds a new task to the priority queue or updates the priority of an existing task. Parameters: - pq: List representing the heap-based priority queue. - entr...
from solution import add_task, remove_task, pop_task def test_add_and_pop_task(): pq = [] entry_finder = {} add_task(pq, entry_finder, 'task1', 5) add_task(pq, entry_finder, 'task2', 9) add_task(pq, entry_finder, 'task3', 3) assert pop_task(pq, entry_finder) == 'task3' assert pop_task(...
[ { "docstring": "Adds a new task to the priority queue or updates the priority of an existing task.\n\nParameters:\n- pq: List representing the heap-based priority queue.\n- entry_finder: Dictionary mapping tasks to their heap entries.\n- task: The name of the task being added or updated.\n- priority: The new pr...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\nimport itertools\n\nREMOVED = '<removed-task>' # Placeholder for a removed task\ncounter = itertools.count() # Unique sequence count\n\ndef add_task(pq,...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041653", "row_id": 41653, "seed_ids": "[241]" }
0.562423
Docs: Python310_41653
I
[ "add_task", "remove_task", "pop_task" ]
3
[ [ "add_task", "remove_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
48ce78fad6363c1aab8122a7f74787cffdc1f44b
03284bc9fa885a6cb1207efe1349ec29ca67a8b5
v1.0
instruct
Docs
Docs: Python310_41681_I
### Question: Enhanced Traceback Handler You are required to implement a custom exception handler using the `cgitb` module. The custom handler should: 1. Enable `cgitb` with the ability to log tracebacks to a specified directory. 2. Format the tracebacks in both text and HTML formats. 3. Handle uncaught exceptions and...
import cgitb import os import sys import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def enable_cgitb(logdir: str, display: bool = False): """ Enables cgitb error logging. Args: logdir (str): Directory for log files. display (bool): Flag ...
import os import pytest from solution import enable_cgitb, format_traceback, email_traceback def test_enable_cgitb(): logdir = './test_tracebacks' if os.path.exists(logdir): os.rmdir(logdir) enable_cgitb(logdir, display=False) assert os.path.exists(logdir) def test_format_traceback(): try...
[ { "docstring": "Enables cgitb error logging.\n\nArgs:\n logdir (str): Directory for log files.\n display (bool): Flag to display tracebacks in console.", "function_declaration": "def enable_cgitb(logdir, display=False):", "function_name": "enable_cgitb", "parameter_list": "(logdir, display=Fal...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cgitb\nimport os\nimport sys\nimport traceback\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\ndef enabl...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00041681", "row_id": 41681, "seed_ids": "[385]" }
0.45653
Docs: Python310_41681
I
[ "enable_cgitb", "format_traceback", "email_traceback" ]
3
[ [ "email_traceback", "format_traceback" ] ]
1
[]
false
[]
false
pytest
true
[]
true
72515c7f7dcdfc22fb1abfb368c977dae57e28c8
35685f4bf5124e8a5e8383a09137051dfbb5c419
v1.0
instruct
Docs
Docs: Python310_41725_I
**Question: Custom Object Serialization and Deserialization** In this challenge, you are required to implement a pair of functions `custom_serialize` and `custom_deserialize` that utilize the `marshal` module to serialize and deserialize specific Python objects. Your implementation should handle both the writing to/re...
import marshal SUPPORTED_TYPES = (bool, int, float, str, bytes, list, tuple, set, dict, type(None), type(...), StopIteration) def replace_unsupported(v): if isinstance(v, SUPPORTED_TYPES): if isinstance(v, (list, tuple, set)): return type(v)(replace_unsupported(i) for i in v) elif isin...
from solution import custom_serialize, custom_deserialize import os def test_serialize_deserialize_file(): obj = {"key1": 123, "key2": [1, 2, 3]} file_path = "test.marshal" custom_serialize(obj, file_path=file_path) deserialized_obj = custom_deserialize(file_path=file_path) assert deserialize...
[ { "docstring": null, "function_declaration": "def replace_unsupported(v):", "function_name": "replace_unsupported", "parameter_list": "(v)" }, { "docstring": null, "function_declaration": "def custom_serialize(obj, file_path=None, to_bytes=False):", "function_name": "custom_serialize...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import marshal\nimport os\n\ndef filter_supported_types(obj):\n if isinstance(obj, (bool, int, float, str, bytes, type(None), type(Ellipsis), StopIteration)):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00041725", "row_id": 41725, "seed_ids": "[190]" }
0.583705
Docs: Python310_41725
I
[ "replace_unsupported", "custom_serialize", "custom_deserialize" ]
3
[ [ "custom_serialize", "replace_unsupported" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c5d2c1b85d1d640c56b84bb0927ec7fabfa4cd85
5a8595aab7e40a809db3dd3dfe2bbc48cdaea477
v1.0
instruct
Docs
Docs: Python310_41730_I
#### Objective Demonstrate your understanding of handling cell objects in Python by implementing a set of wrappers around some of the core functions provided in the Python C API documentation. #### Task You need to write a Python module that provides functions for creating, accessing, and modifying cell objects. These...
import types def is_cell(obj): """ Returns True if the object is a cell object, False otherwise. """ return isinstance(obj, types.CellType) def create_cell(value): """ Creates a new cell object containing the given value. """ # Using a closure to create a cell object def closure():...
from solution import is_cell, create_cell, get_cell_value, set_cell_value import types import pytest def test_is_cell(): # Create a cell and non-cell object cell = create_cell(10) non_cell = 10 assert is_cell(cell) == True assert is_cell(non_cell) == False def test_create_cell(): cell...
[ { "docstring": "Returns True if the object is a cell object, False otherwise.", "function_declaration": "def is_cell(obj):", "function_name": "is_cell", "parameter_list": "(obj)" }, { "docstring": "Creates a new cell object containing the given value.", "function_declaration": "def creat...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import types\n\ndef is_cell(obj):\n \"\"\"\n Returns True if the object is a cell object, False otherwise.\n \"\"\"\n return isinstance(obj, types.CellType)...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00041730", "row_id": 41730, "seed_ids": "[38]" }
0.458514
Docs: Python310_41730
I
[ "is_cell", "create_cell", "get_cell_value", "set_cell_value" ]
4
[ [ "get_cell_value", "is_cell" ], [ "set_cell_value", "is_cell" ] ]
2
[]
false
[]
false
pytest
true
[]
true
cfb94e68fd43d6e711a09b97e9e385e95e50a626
eb61f3e3c69371509a52416713cca9dadc9f4da8
v1.0
instruct
Docs
Docs: Python310_41751_I
### Asyncio Event Loop and Network Operations #### Problem Statement: You are provided with a task to build an asynchronous TCP echo server using Python's `asyncio` library. The server should accept incoming client connections, read messages sent by the clients, and echo the same messages back to them. Additionally, t...
import asyncio import signal import functools async def handle_client(reader, writer): address = writer.get_extra_info('peername') print(f"Connection from {address}") try: while True: data = await reader.read(100) if not data: break message = dat...
import asyncio import pytest from solution import handle_client, start_echo_server @pytest.mark.asyncio async def test_handle_client_echo(): server = await asyncio.start_server(handle_client, '127.0.0.1', 0) addr = server.sockets[0].getsockname() reader, writer = await asyncio.open_connection(*addr) t...
[ { "docstring": null, "function_declaration": "def ask_exit(signame, loop):", "function_name": "ask_exit", "parameter_list": "(signame, loop)" } ]
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import asyncio\nimport signal\nimport functools\n\nasync def handle_client(reader, writer):\n address = writer.get_extra_info('peername')\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00041751", "row_id": 41751, "seed_ids": "[267]" }
0.690796
Docs: Python310_41751
I
[ "handle_client", "start_echo_server", "ask_exit", "main" ]
4
[ [ "start_echo_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1630b6bf33681949b493f0b5920e89d57e5c8213
cb109013569cb5a9e72ea4ba1f3bf02b1c8412dd
v1.0
instruct
Docs
Docs: Python310_41789_I
#### Objective: Your task is to implement a robust Python module that can handle multiple operations and exceptions from a given set of tasks. You are required to demonstrate your understanding of advanced exception handling and recursion control in Python. #### Requirements: 1. **Function Implementation**: Impleme...
import math import warnings def divide(a, b): try: return a / b except ZeroDivisionError as e: raise ZeroDivisionError(f"ZeroDivisionError: Cannot divide {a} by zero.") def sqrt(x): try: if x < 0: raise ValueError(f"ValueError: Cannot calculate square root of negative n...
import pytest from solution import process_tasks, factorial def test_process_tasks(): tasks = [ {"operation": "divide", "args": [10, 2]}, {"operation": "sqrt", "args": [16]}, {"operation": "concat", "args": ["Hello", " ", "world"]}, {"operation": "add", "args": [1, 2, 3]}, {...
[ { "docstring": null, "function_declaration": "def divide(a, b):", "function_name": "divide", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def sqrt(x):", "function_name": "sqrt", "parameter_list": "(x)" }, { "docstring": null, "function_d...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nimport warnings\n\ndef divide(a, b):\n try:\n return a / b\n except ZeroDivisionError as e:\n raise ZeroDivisionError(f\"ZeroDivisionEr...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00041789", "row_id": 41789, "seed_ids": "[33]" }
0.611307
Docs: Python310_41789
I
[ "divide", "sqrt", "concat", "sum_args", "factorial", "process_tasks" ]
6
[ [ "process_tasks", "concat" ], [ "process_tasks", "divide" ], [ "process_tasks", "sqrt" ], [ "process_tasks", "sum_args" ] ]
4
[]
false
[]
false
pytest
true
[]
true
de48ad81634ae199546603c3015cd517369ed91e
fdc71e563b23d4d907a40d811212e8ab9195b29d
v1.0
instruct
Docs
Docs: Python310_41891_I
**Question: Implement and Utilize Asyncio Queues for a Task Scheduler** ### Problem Statement You are to design a task scheduling system that concurrently processes tasks with varying priorities. Use the `asyncio.PriorityQueue` to schedule tasks based on their priorities. Each task must be associated with a priority ...
import asyncio from typing import List, Tuple async def worker(name: str, queue: asyncio.PriorityQueue, output_list: List[str]): while True: priority, task = await queue.get() if priority is None: # Break out of the loop if we encounter the stop signal break await as...
import asyncio from solution import schedule_tasks def test_schedule_tasks(capsys): tasks = [ (1, 'Clean the house'), (3, 'Buy groceries'), (2, 'Pay bills'), (0, 'Emergency meeting') ] asyncio.run(schedule_tasks(tasks)) expected_output = [ 'Emergency me...
[]
[ 1, 0, 1, 1, 1, 1, 1, 0, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def worker(name: str, queue: asyncio.PriorityQueue, output_list: List[str]):\n while True:\n priority,...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00041891", "row_id": 41891, "seed_ids": "[111]" }
0.596158
Docs: Python310_41891
I
[ "worker", "schedule_tasks" ]
2
[ [ "schedule_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6a27b900bd62f65d6fde29b0468009924bcfe43b
41e1c5c03c22e64a0826921a03829b1a3e2aeece
v1.0
instruct
Docs
Docs: Pytorch_41899_I
## Coding Assessment Question ### Objective You are required to demonstrate your understanding of PyTorch's Generic Join Context Manager for handling distributed training with uneven input sizes. You will implement a distributed training loop using PyTorch, ensuring correct synchronization and completion using the `Jo...
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torch.distributed.algorithms.join import Join, Joinable # Define your neural network model class SimpleNet(nn.Module): def __init__(self): super(SimpleNet, self).__init__() self.fc1 = nn.Linear(10, ...
def test_distributed_training(): rank = 0 world_size = 2 num_epochs = 5 # Simulate the function call for each rank from multiprocessing import Process processes = [] for rank in range(world_size): p = Process(target=distributed_training, args=(rank, world_size, num_epochs)) ...
[]
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nfrom torch.distributed.algorithms.join import Join, Joinable, JoinHo...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00041899", "row_id": 41899, "seed_ids": "[135]" }
0.500428
Docs: Pytorch_41899
I
[ "setup", "cleanup", "distributed_training" ]
3
[ [ "distributed_training", "cleanup" ], [ "distributed_training", "setup" ] ]
2
[]
false
[ "SimpleNet" ]
true
pytest
false
[ "torch" ]
false
4e02019d793207f6e5c990b0afb85e0dfa92e3d0
7b120cb278ded6648ff132ca320fc8d6bf453039
v1.0
instruct
Docs
Docs: Python310_41922_I
### Multi-threaded File Processing with Thread Pool and Synchronization **Objective:** Implement a multi-threaded file processing system where multiple threads read data from different files, process the data, and store the results in a shared resource. Use synchronization primitives to ensure thread-safe operations. ...
import threading from typing import List, Dict import os def read_and_process_file(file_name: str, results_dict: Dict[str, int], lock: threading.Lock) -> None: """ This function reads the file, processes the numbers, and updates the shared dictionary. """ try: with open(file_name, 'r') as file:...
import os import threading from solution import read_and_process_file, process_files_concurrently def create_file(file_name, contents): with open(file_name, 'w') as f: f.write(contents) def test_read_and_process_file(): try: create_file('test1.txt', '1\n2\n3\n') results = {} lo...
[ { "docstring": "This function reads the file, processes the numbers, and updates the shared dictionary.", "function_declaration": "def read_and_process_file(file_name, results_dict, lock):", "function_name": "read_and_process_file", "parameter_list": "(file_name, results_dict, lock)" }, { "d...
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import threading\nfrom typing import List, Dict\n\ndef read_and_process_file(file_name: str, results_dict: Dict[str, int], lock: threading.Lock) -> None:\n \"\"\"\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00041922", "row_id": 41922, "seed_ids": "[120]" }
0.479711
Docs: Python310_41922
I
[ "read_and_process_file", "process_files_concurrently" ]
2
[ [ "process_files_concurrently", "read_and_process_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
51c36e5deba661b41a2ec13173f6e91fb1c0ff72
ff4a0ac196b71f9785c89e5b51442a135505cc2e
v1.0
instruct
Docs
Docs: Python310_41996_I
**Question: Implement a Custom Task Scheduler** You are required to create a task scheduler using Python's `sched` module to manage a series of tasks. Implement the following functions to demonstrate your understanding of the `sched` module: 1. **Function: `display_event()`** ```python def display_event(message...
import sched import time def display_event(message: str): """ This function prints the current time and the provided message. Args: message (str): Message to be displayed. """ print(f"{time.time()}: {message}") def schedule_tasks(scheduler: sched.scheduler, tasks: list): """ S...
import sched import time from io import StringIO import sys from solution import display_event, schedule_tasks def test_display_event(): original_stdout = sys.stdout sys.stdout = StringIO() try: display_event("Test Message") output = sys.stdout.getvalue().strip() assert "Test Messa...
[ { "docstring": "This function prints the current time and the provided message.\n\nArgs:\n message (str): Message to be displayed.", "function_declaration": "def display_event(message):", "function_name": "display_event", "parameter_list": "(message)" }, { "docstring": "Schedules multiple...
[ 1, 0, 1, 1, 0, 1, 1, 0, 0 ]
5
medium
0.556
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sched\nimport time\n\ndef display_event(message: str):\n \"\"\"\n Print the current time and the provided message.\n \n Args:\n message (str):...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00041996", "row_id": 41996, "seed_ids": "[180]" }
0.593497
Docs: Python310_41996
I
[ "display_event", "schedule_tasks" ]
2
[ [ "schedule_tasks", "display_event" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cf0779dfa25ecc0f16673cae8f3b8d9869cd1c7e
84b4b0db993d500c06ddbfa6c8c0abb61ba2cc40
v1.0
instruct
Docs
Docs: Python310_42040_I
## Coding Assessment Question ### Objective Implement a Python function that uses the `concurrent.futures` module to perform concurrent execution of multiple tasks. The function will process a list of integers, where each integer will be squared. The task involves ensuring that the results are collected and returned c...
import concurrent.futures def square_number(n): return n * n def process_numbers_concurrently(numbers: list, use_threads: bool = True) -> list: """ Processes a list of integers, where each integer is squared. Uses either ThreadPoolExecutor or ProcessPoolExecutor from concurrent.futures. Args: ...
from solution import process_numbers_concurrently def test_process_numbers_concurrently_with_threads(): numbers = [1, 2, 3, 4, 5] result = process_numbers_concurrently(numbers, use_threads=True) assert result == [1, 4, 9, 16, 25] def test_process_numbers_concurrently_with_processes(): numbers = [1, 2,...
[ { "docstring": null, "function_declaration": "def square_number(n):", "function_name": "square_number", "parameter_list": "(n)" }, { "docstring": "Processes a list of integers, where each integer is squared.\nUses either ThreadPoolExecutor or ProcessPoolExecutor from concurrent.futures.\n\nA...
[ 1, 0, 0, 0, 0, 0, 1, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\n\ndef square_number(n):\n return n * n\n\ndef process_numbers_concurrently(numbers: list, use...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00042040", "row_id": 42040, "seed_ids": "[224]" }
0.639037
Docs: Python310_42040
I
[ "square_number", "process_numbers_concurrently" ]
2
[ [ "process_numbers_concurrently", "square_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
570aad5daf841f3b860f78ff593920efc4ceb55d
7e1e17a2ccb029812d77fcd689b719fe0fc54c83
v1.0
instruct
Docs
Docs: Python310_42047_I
### Custom Codec Implementation and Utilization **Objective:** You are tasked with implementing a custom codec and using it to encode and decode text, demonstrating your understanding of the codec-related functions in Python. **Instructions:** 1. **Implement a Custom Codec:** - Write a function `register_custom_...
import codecs class ReverseCodec(codecs.Codec): def encode(self, input, errors='strict'): return input[::-1], len(input) def decode(self, input, errors='strict'): return input[::-1], len(input) def reverse_search_function(encoding): if encoding == 'reverse_codec': return codecs.Co...
from solution import register_custom_codec, encode_text, decode_text def test_register_custom_codec(): register_custom_codec() assert codecs.lookup('reverse_codec') is not None def test_encode_text(): register_custom_codec() assert encode_text("hello") == "olleh" assert encode_text("world") == "dl...
[]
[ 0, 1, 1, 0, 1, 0, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import codecs\n\ndef reverse_encode(input, errors='strict'):\n return (input[::-1], len(input))\n\ndef reverse_decode(input, errors='strict'):\n return (input[::-...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00042047", "row_id": 42047, "seed_ids": "[47]" }
0.625125
Docs: Python310_42047
I
[ "reverse_search_function", "register_custom_codec", "encode_text", "decode_text" ]
4
[ [ "register_custom_codec", "reverse_search_function" ] ]
1
[]
false
[ "ReverseCodec" ]
true
pytest
true
[]
true
986cfe5dfde6194c297c0d950187b2f5253a0244
4dccb458a03ad4f2d169a66ffef3cfdf89fc5af3
v1.0
instruct
Docs
Docs: Python310_42058_I
#### Objective: To assess your understanding of Python's cryptographic services, specifically the `hashlib` and `hmac` modules, you will implement a secure password storage and verification system. This system should include functionality for hashing passwords using HMAC (Keyed-Hash Message Authentication Code) and ver...
import hmac import hashlib import secrets def generate_salt(): """ Generates a random 16-byte hexadecimal salt. Returns: str: A random 16-byte hexadecimal string. """ return secrets.token_hex(16) def hash_password(password, salt, key): """ Generates a HMAC hash of the given pa...
from solution import generate_salt, hash_password, verify_password def test_generate_salt_length(): salt = generate_salt() assert len(salt) == 32 # 16 bytes * 2 (hex representation) def test_generate_salt_uniqueness(): salt1 = generate_salt() salt2 = generate_salt() assert salt1 != salt2 # Salts...
[ { "docstring": "Generates a random 16-byte hexadecimal salt.\n\nReturns:\n str: A random 16-byte hexadecimal string.", "function_declaration": "def generate_salt():", "function_name": "generate_salt", "parameter_list": "()" }, { "docstring": "Generates a HMAC hash of the given password us...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import secrets\nimport hmac\nimport hashlib\n\ndef generate_salt():\n \"\"\"\n Generates a random 16-byte hexadecimal string.\n \"\"\"\n return secrets.toke...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00042058", "row_id": 42058, "seed_ids": "[394]" }
0.758264
Docs: Python310_42058
I
[ "generate_salt", "hash_password", "verify_password" ]
3
[ [ "verify_password", "hash_password" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4a7185322d73569a0b1073fca00da04e095d4aa8
874b210030119425d9ec5e713b3d78ae180a27f5
v1.0
instruct
Docs
Docs: Pytorch_42061_I
**Question: Implement a Custom Flexible Attention Mechanism with Dynamic Blocks** In this task, you are required to implement a custom attention mechanism using PyTorch. Your task is to create a flexible attention mechanism that leverages dynamic blocks and mask utility functions provided by the `torch.nn.attention.fl...
import torch import torch.nn.functional as F def create_block_mask(tensor, block_shape): """ Function to create a dynamic block mask for the attention mechanism. Params: - tensor (torch.Tensor): Tensor to create a block mask for. - block_shape (tuple): Shape of the block (block_height, block_width...
import torch from solution import custom_flexible_attention def test_custom_flexible_attention_output_shape(): batch_size = 2 seq_len = 10 dim = 4 block_shape = (2, 2) query = torch.randn(batch_size, seq_len, dim) key = torch.randn(batch_size, seq_len, dim) value = torch.randn(batch_size, ...
[ { "docstring": "Function to create a dynamic block mask for the attention mechanism.\n\nParams:\n- tensor (torch.Tensor): Tensor to create a block mask for.\n- block_shape (tuple): Shape of the block (block_height, block_width).\n\nReturns:\n- mask (torch.Tensor): Block mask.", "function_declaration": "def ...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn.functional as F\n\ndef create_block_mask(seq_len, block_shape):\n \"\"\"\n Creates a block mask for attention mechanism.\n \n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00042061", "row_id": 42061, "seed_ids": "[0]" }
0.410151
Docs: Pytorch_42061
I
[ "create_block_mask", "custom_flexible_attention" ]
2
[ [ "custom_flexible_attention", "create_block_mask" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
ca1dced3729b6202c8f74c44ee923c5ebc0fe9ee
d052e4f4510c8c1a3e1cb6927117c9cf56e4f1c5
v1.0
instruct
Docs
Docs: Pytorch_42103_I
You are tasked with designing an asynchronous pipeline using PyTorch's `torch.futures.Future` to process a batch of data in parallel. Your pipeline consists of several stages, each performing a different computation asynchronously. You will need to collect the results from all stages and return the aggregated output. ...
import torch from torch.futures import Future from typing import List def add_one(x: int) -> Future: future = Future() future.set_result(x + 1) return future def square(x: int) -> Future: future = Future() future.set_result(x * x) return future def sqrt(x: int) -> Future: future = Future(...
import pytest from solution import process_pipeline def test_process_pipeline_basic(): data = [1, 2, 3, 4] result = process_pipeline(data) expected = [torch.sqrt(torch.tensor(4)), torch.sqrt(torch.tensor(9)), torch.sqrt(torch.tensor(16)), torch.sqrt(torch.tensor(25))] assert result == [e.item() for e i...
[ { "docstring": null, "function_declaration": "def add_one(x):", "function_name": "add_one", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def square(x):", "function_name": "square", "parameter_list": "(x)" }, { "docstring": null, "function_d...
[ 1, 0, 0, 0, 0, 1, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.futures import Future\nfrom typing import List\nimport math\n\ndef async_transform_stage1(data: List[int]) -> List[Future]:\n futures = []\n...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00042103", "row_id": 42103, "seed_ids": "[53]" }
0.49786
Docs: Pytorch_42103
I
[ "add_one", "square", "sqrt", "process_pipeline" ]
4
[ [ "process_pipeline", "add_one" ], [ "process_pipeline", "sqrt" ], [ "process_pipeline", "square" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
7f2439df44978e339f386c64226f73b9efcc331a
0fc92b000895084c46928a79530d42e3a1d03d0a
v1.0
instruct
Docs
Docs: Python310_42138_I
### Question: Concurrent Web Scraper You are tasked with implementing a concurrent web scraper using Python's `concurrent.futures` module. The goal is to fetch the contents of multiple web pages concurrently and process the data efficiently. Here is the detailed specification: #### Function Signature ```python def fe...
import urllib.request import urllib.error from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List, Dict, Union def fetch_url(url: str, timeout: int) -> Dict[str, Union[str, int]]: """ Fetches the contents of the URL and returns a dictionary containing status and content length. ...
import pytest from solution import fetch_urls def test_fetch_urls_success(): urls = ["http://www.example.com"] result = fetch_urls(urls, timeout=10) assert "http://www.example.com" in result assert result["http://www.example.com"]["status"] == 200 assert isinstance(result["http://www.example.com"][...
[ { "docstring": "Fetches the contents of the URL and returns a dictionary containing status and content length.\n\nArgs:\nurl: str - The URL to fetch.\ntimeout: int - The timeout value for each URL fetch operation.\n\nReturns:\nDict[str, Union[str, int]] - A dictionary with 'status' and 'content_length' keys.", ...
[ 0, 1, 1, 1, 0, 1, 0, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Dict, Union\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nimport urllib.request\nimport urllib.error\n\ndef fetch_url(url: ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00042138", "row_id": 42138, "seed_ids": "[347]" }
0.58428
Docs: Python310_42138
I
[ "fetch_url", "fetch_urls" ]
2
[ [ "fetch_urls", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a8079c1c87cdc51ac90223f9f8f38058d404cf37
84d8ac55271ac64b77b9042133426fe1158b60ac
v1.0
instruct
Docs
Docs: Python310_42143_I
### Advanced Asynchronous Execution With `concurrent.futures` You are tasked with designing a multi-threaded job processing system using the `concurrent.futures` module in Python. The system will process a list of tasks and return the results once all tasks are completed. #### Requirements 1. Create a function `proce...
import time from concurrent.futures import ThreadPoolExecutor, as_completed def process_task(task_id, duration): """ Simulates task processing by sleeping for `duration` seconds. Returns a message indicating the task completion. """ time.sleep(duration) return f"Task {task_id} completed in {dur...
from solution import process_task, manage_tasks def test_process_task(): # Test process_task with various durations assert process_task(1, 1) == "Task 1 completed in 1 seconds" assert process_task(2, 3) == "Task 2 completed in 3 seconds" assert process_task(3, 2) == "Task 3 completed in 2 seconds" def...
[ { "docstring": "Simulates task processing by sleeping for `duration` seconds.\nReturns a message indicating the task completion.", "function_declaration": "def process_task(task_id, duration):", "function_name": "process_task", "parameter_list": "(task_id, duration)" }, { "docstring": "Manag...
[ 1, 1, 1, 1, 1, 0, 0, 1, 0, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef process_task(task_id, duration):\n \"\"\"\n Simulates task processing by sleep...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00042143", "row_id": 42143, "seed_ids": "[347]" }
0.738055
Docs: Python310_42143
I
[ "process_task", "manage_tasks" ]
2
[ [ "manage_tasks", "process_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
20d7aa3f6cd841517892048da8cbaf44f1e269bb
f793114fe1b2951f34491032478383d1d00aa4cb
v1.0
instruct
Docs
Docs: Python310_42168_I
<|Analysis Begin|> The given documentation is about `asyncio.queues` from the Python standard library. - **Classes Provided:** - `asyncio.Queue`: A first-in, first-out (FIFO) queue. - Methods: `empty()`, `full()`, `get()`, `get_nowait()`, `join()`, `put()`, `put_nowait()`, `qsize()`, `task_done()`. - `asyncio...
import asyncio import random async def handler(name: str, queue: asyncio.Queue): while True: try: ticket_number = await queue.get() await asyncio.sleep(random.uniform(0.1, 0.5)) queue.task_done() print(f'{name} processed ticket #{ticket_number}') exce...
import asyncio from solution import handler, booking_simulator async def test_handler(): queue = asyncio.Queue() for i in range(5): await queue.put(i+1) handler_task = asyncio.create_task(handler('test-handler', queue)) await queue.join() handler_task.cancel() await asyncio.gather(...
[]
[ 1, 1, 1, 0, 1, 1, 0, 0, 1 ]
6
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\n\nasync def handler(name: str, queue: asyncio.Queue):\n while True:\n ticket_number = await queue.get()\n await asyncio....
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00042168", "row_id": 42168, "seed_ids": "[111]" }
0.470228
Docs: Python310_42168
I
[ "handler", "booking_simulator" ]
2
[ [ "booking_simulator", "handler" ] ]
1
[]
false
[]
false
pytest
true
[]
true
70c012a3ce8fb744d8799fc7ad08d031086c0549
1bb90b4b4bfa2e5ae15b29b6bfc66767af130ccc
v1.0
instruct
Docs
Docs: Python310_42244_I
### Advanced Python Exception Handling You are tasked with implementing a small module that simulates a file processing system with several potential error conditions. This will test your ability to handle a variety of exceptions properly and ensure your code is robust and informative in the face of errors. #### Requ...
class FileFormatError(Exception): """Raised when a file has an incorrect format.""" pass class ProcessingError(Exception): """Raised for general processing errors.""" pass class CriticalError(ProcessingError): """Raised when a critical error occurs.""" pass def process_file(file_name: str) ->...
import pytest from solution import FileFormatError, ProcessingError, CriticalError, process_file, safe_process def test_process_file_bad_format(): with pytest.raises(FileFormatError): process_file("bad_format.txt") def test_process_file_critical_issue(): with pytest.raises(CriticalError): proc...
[]
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class FileFormatError(Exception):\n \"\"\"Exception raised for errors in the file format.\"\"\"\n pass\n\nclass ProcessingError(Exception):\n \"\"\"Exception r...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00042244", "row_id": 42244, "seed_ids": "[256]" }
0.571236
Docs: Python310_42244
I
[ "process_file", "safe_process" ]
2
[ [ "safe_process", "process_file" ] ]
1
[]
false
[ "FileFormatError", "ProcessingError", "CriticalError" ]
true
pytest
true
[]
true
4c8b3d1d77965d4fe617baf11cf9c3ec7fdfc654
10ec489195e6dc12294d9ba6e2cbd29eba45c5e8
v1.0
instruct
Docs
Docs: Scikit_42256_I
**Objective**: Implement a classification task using `sklearn.neighbors` and compare the performance of different nearest neighbor algorithms. **Problem Statement**: You are provided with a dataset that contains labeled points in a 2D space. Your task is to implement a nearest neighbor classifier using two different ...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.neighbors import KDTree, BallTree from sklearn.metrics import accuracy_score import time def load_and_preprocess_data(filepath): data = pd.read_csv(filepath) X = data[['x1', 'x2']].values y = data['label'].values retu...
import pytest from solution import evaluate_knn def mock_read_csv(filepath): data_content = { 'x1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'x2': [1, 2, 1, 2, 1, 2, 1, 2, 1, 2], 'label': [1, 0, 1, 0, 1, 0, 1, 0, 1, 0] } return pd.DataFrame.from_dict(data_content) @pytest.fixture def patch...
[ { "docstring": null, "function_declaration": "def load_and_preprocess_data(filepath):", "function_name": "load_and_preprocess_data", "parameter_list": "(filepath)" }, { "docstring": null, "function_declaration": "def knn_kdtree(X_train, y_train, X_test, k=3):", "function_name": "knn_...
[ 0, 0, 1, 1, 0, 1, 1, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_scor...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00042256", "row_id": 42256, "seed_ids": "[52]" }
0.604442
Docs: Scikit_42256
I
[ "load_and_preprocess_data", "knn_kdtree", "knn_balltree", "evaluate_knn" ]
4
[ [ "evaluate_knn", "knn_balltree" ], [ "evaluate_knn", "knn_kdtree" ], [ "evaluate_knn", "load_and_preprocess_data" ] ]
3
[]
false
[]
false
pytest
true
[ "pandas", "sklearn" ]
false
f575766e5130502bf3fbd507f1d356b7560c0a77
00a87ff52dc0b3746752b4d38d8d1a7d0c1266b7
v1.0
instruct
Docs
Docs: Python310_42309_I
### Asynchronous Programming with Coroutines In this assessment, you are required to demonstrate your understanding of Python's async and await functionality by creating an asynchronous function and handling coroutines. #### Problem Statement You are tasked to implement a simplified version of an asynchronous web sc...
import asyncio from typing import List async def fetch_page_content(url: str) -> str: """ Simulates fetching the content of a web page. Args: url (str): The URL of the web page. Returns: str: Simulated content of the web page. """ await asyncio.sleep(1) return f"Content of...
import asyncio from solution import fetch_page_content, fetch_all_contents def test_fetch_page_content(): result = asyncio.run(fetch_page_content("http://example.com/page1")) assert result == "Content of http://example.com/page1" def test_fetch_all_contents(): urls = [ "http://example.com/page1", ...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List\n\nasync def fetch_page_content(url: str) -> str:\n \"\"\"\n Simulates fetching the content of a web page.\n :param url...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00042309", "row_id": 42309, "seed_ids": "[8]" }
0.599817
Docs: Python310_42309
I
[ "fetch_page_content", "fetch_all_contents" ]
2
[ [ "fetch_all_contents", "fetch_page_content" ] ]
1
[]
false
[]
false
pytest
true
[]
true
44df959fef3312d62c6560f732c4d7a63ce223ec
7799b2c9b93abec024c62d7b9494cc60a0abde45
v1.0
instruct
Docs
Docs: Python310_42320_I
**Objective:** Demonstrate understanding of advanced usage of the `sys` module for profiling and debugging a Python program. --- #### Problem Statement You are tasked with implementing a Python function that uses the `sys` module to profile the execution of a script and collect debugging information when an unhandle...
import sys import traceback def initialize_profiler(profile_data): """ Initialize the system profiler to count function calls. """ def profiler(frame, event, arg): if event == 'call': function_name = frame.f_code.co_name if function_name in profile_data: ...
import sys import os from solution import initialize_profiler, exception_handler, setup_system_hooks, run_script def test_initialize_profiler(): profile_data = {} initialize_profiler(profile_data) def sample_function(): return "Called" sample_function() sample_function() assert profil...
[ { "docstring": "Initialize the system profiler to count function calls.", "function_declaration": "def initialize_profiler(profile_data):", "function_name": "initialize_profiler", "parameter_list": "(profile_data)" }, { "docstring": "Log unhandled exceptions detailing type, value, and traceb...
[ 0, 0, 0, 0, 1, 1, 0, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\nimport traceback\n\ndef initialize_profiler(profile_data):\n def profiler(frame, event, arg):\n if event == 'call':\n function_name = f...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00042320", "row_id": 42320, "seed_ids": "[348]" }
0.498773
Docs: Python310_42320
I
[ "initialize_profiler", "exception_handler", "setup_system_hooks", "run_script" ]
4
[ [ "setup_system_hooks", "initialize_profiler" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fa208247b0242aa4720f8881e42c95afc4f6628f
f4cce017511f5e961a04baa1f1c8b3ca4a95cea6
v1.0
instruct
Docs
Docs: Python310_42327_I
## Coding Assessment Question ### Objective Implement a Python program to efficiently calculate the sum of squares of a list of numbers using asynchronous execution with `ProcessPoolExecutor` from the "concurrent.futures" module. The solution should demonstrate the student's ability to use the `ProcessPoolExecutor`, h...
from concurrent.futures import ProcessPoolExecutor from typing import List def square(n: int) -> int: return n * n def sum_of_squares(numbers: List[int]) -> int: if not numbers: return 0 with ProcessPoolExecutor() as executor: results = executor.map(square, numbers) return su...
from solution import sum_of_squares def test_sum_of_squares_empty_list(): assert sum_of_squares([]) == 0 def test_sum_of_squares_single_element(): assert sum_of_squares([5]) == 25 def test_sum_of_squares_positive_elements(): assert sum_of_squares([1, 2, 3, 4, 5]) == 55 def test_sum_of_squares_negative_e...
[ { "docstring": null, "function_declaration": "def square(n):", "function_name": "square", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def sum_of_squares(numbers):", "function_name": "sum_of_squares", "parameter_list": "(numbers)" } ]
[ 1, 0, 0, 0, 1, 1, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ProcessPoolExecutor\nfrom typing import List\n\ndef square(n: int) -> int:\n return n * n\n\ndef sum_of_squares(numbers: List[int]) ->...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00042327", "row_id": 42327, "seed_ids": "[347]" }
0.712498
Docs: Python310_42327
I
[ "square", "sum_of_squares" ]
2
[ [ "sum_of_squares", "square" ] ]
1
[]
false
[]
false
pytest
true
[]
true
22cd9defbf057ffe5483dc323f97b9f61aa8e91e
15652006bee0a9284828c1f38e78d2d250b01345
v1.0
instruct
Docs
Docs: Scikit_42390_I
### Question: Implement Custom Kernel Function and Compare with Predefined Kernels #### Objective: Write a Python function to implement a custom kernel function and compare its performance on a sample dataset with predefined kernels provided by scikit-learn. Demonstrate your understanding of how to create and use cust...
import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.metrics import accuracy_score from sklearn.metrics.pairwise import polynomial_kernel, rbf_kernel def custom_kernel(X, Y, gamma1=0.1, gamma2=0.1, c0=1, d=3): ...
from solution import custom_kernel, evaluate_kernels import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split def test_custom_kernel(): X, y = make_classification(n_samples=100, n_features=20, random_state=42) # Basic test to check the shape ...
[ { "docstring": "Custom kernel combining polynomial and RBF kernels.\n\nParameters:\nX, Y : array-like of shape (n_samples_X, n_features), (n_samples_Y, n_features)\ngamma1 : float, default=0.1\ngamma2 : float, default=0.1\nc0 : float, default=1\nd : int, default=3\n\nReturns:\nK : array-like of shape (n_samples...
[ 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.me...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00042390", "row_id": 42390, "seed_ids": "[38]" }
0.516808
Docs: Scikit_42390
I
[ "custom_kernel", "evaluate_kernels" ]
2
[ [ "evaluate_kernels", "custom_kernel" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
fc993ceaaaefa6be87af032d55cdacd5a257ebff
cf9d89d0f407eed06c28bb2b151a561b7802ee3a
v1.0
instruct
Docs
Docs: Python310_42396_I
**Question:** You have been hired by a company to develop a simplified web scraper using `asyncio`. This web scraper needs to fetch data from multiple URLs concurrently and process each webpage to extract the title. You are required to implement this web scraper efficiently, ensuring that all asynchronous tasks are ha...
import asyncio import requests from concurrent.futures import ThreadPoolExecutor from bs4 import BeautifulSoup import logging logging.basicConfig(level=logging.DEBUG) # Enable asyncio debug mode asyncio.get_event_loop().set_debug(True) def fetch_title_sync(url): """ Synchronous function to fetch the title fr...
import asyncio from solution import fetch_title, fetch_all_titles def test_fetch_title(monkeypatch): class MockResponse: def __init__(self, text): self.text = text self.status_code = 200 def raise_for_status(self): pass def mock_get(url): if url...
[ { "docstring": "Synchronous function to fetch the title from a single URL.", "function_declaration": "def fetch_title_sync(url):", "function_name": "fetch_title_sync", "parameter_list": "(url)" } ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport requests\nfrom concurrent.futures import ThreadPoolExecutor\nfrom bs4 import BeautifulSoup\nimport logging\n\nlogging.basicConfig(level=logging.D...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00042396", "row_id": 42396, "seed_ids": "[200]" }
0.645825
Docs: Python310_42396
I
[ "fetch_title_sync", "fetch_title", "fetch_all_titles", "main" ]
4
[ [ "fetch_all_titles", "fetch_title" ], [ "fetch_title", "fetch_title_sync" ] ]
2
[]
false
[]
false
pytest
true
[ "bs4", "requests" ]
false
c4ef342fee8604e49053f32f9a697b936e0c7ccd
2962686a14a44cfbbe0611a6a5f359d479ce61c5
v1.0
instruct
Docs
Docs: Pytorch_42419_I
### PyTorch Coding Assessment Question **Objective**: This task is focused on your ability to manipulate module parameters in PyTorch, particularly during the conversion process. You will be required to implement PyTorch functions and demonstrate an understanding of module parameter management. ### Problem Statement ...
import torch.nn as nn from torch.__future__ import set_overwrite_module_params_on_conversion, set_swap_module_params_on_conversion def toggle_overwrite_module_parameters(value: bool): set_overwrite_module_params_on_conversion(value) def toggle_swap_module_parameters(value: bool): set_swap_module_params_on_con...
from solution import ( toggle_overwrite_module_parameters, toggle_swap_module_parameters, apply_conversion_flags_and_convert, convert_model ) import torch.nn as nn class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.fc = nn.Linear(10, 10) ...
[ { "docstring": null, "function_declaration": "def toggle_overwrite_module_parameters(value):", "function_name": "toggle_overwrite_module_parameters", "parameter_list": "(value)" }, { "docstring": null, "function_declaration": "def toggle_swap_module_parameters(value):", "function_nam...
[ 1, 0, 0, 1, 1, 0, 1, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch.nn as nn\nfrom torch.__future__ import set_overwrite_module_params_on_conversion, \\\n set_swap_module_params_on_conversion\n\nde...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00042419", "row_id": 42419, "seed_ids": "[47]" }
0.462852
Docs: Pytorch_42419
I
[ "toggle_overwrite_module_parameters", "toggle_swap_module_parameters", "apply_conversion_flags_and_convert", "convert_model" ]
4
[ [ "convert_model", "apply_conversion_flags_and_convert" ], [ "convert_model", "toggle_overwrite_module_parameters" ], [ "convert_model", "toggle_swap_module_parameters" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
d3c215f3cdd210f386c21a0e39a0f5bdbb930f19
5e3587693462b68c9c3fc3f08d92407133ca3740
v1.0
instruct
Docs
Docs: Python310_42420_I
### Question: Parallel Sum Calculation using `concurrent.futures` **Objective:** Write a function that uses the `concurrent.futures` module to compute the sum of squares of a list of integers in parallel. #### Function Signature ```python def parallel_sum_of_squares(numbers: List[int], num_workers: int) -> int: p...
from typing import List import concurrent.futures def sum_of_squares(numbers: List[int]) -> int: return sum(x ** 2 for x in numbers) def parallel_sum_of_squares(numbers: List[int], num_workers: int) -> int: chunk_size = (len(numbers) + num_workers - 1) // num_workers sublists = [numbers[i:i + chunk_size] ...
from solution import parallel_sum_of_squares def test_parallel_sum_of_squares_basic(): assert parallel_sum_of_squares([1, 2, 3, 4], 2) == 30 def test_parallel_sum_of_squares_one_worker(): assert parallel_sum_of_squares([1, 2, 3, 4], 1) == 30 def test_parallel_sum_of_squares_large_input(): assert parallel...
[ { "docstring": null, "function_declaration": "def sum_of_squares(numbers):", "function_name": "sum_of_squares", "parameter_list": "(numbers)" }, { "docstring": null, "function_declaration": "def parallel_sum_of_squares(numbers, num_workers):", "function_name": "parallel_sum_of_square...
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ThreadPoolExecutor\nfrom typing import List\n\ndef parallel_sum_of_squares(numbers: List[int], num_workers: int) -> int:\n def sum_of_...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00042420", "row_id": 42420, "seed_ids": "[224]" }
0.595065
Docs: Python310_42420
I
[ "sum_of_squares", "parallel_sum_of_squares" ]
2
[ [ "parallel_sum_of_squares", "sum_of_squares" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f4cc932af570fad875c18d9f60e0d254b72d1067
7c645990f4c03d23f8bbc47c5d35b95ed2e1157f
v1.0
instruct
Docs
Docs: Python310_42441_I
You are tasked with developing a resource management system for handling both synchronous and asynchronous resources using the `contextlib` module. Your goal is to ensure that resources are properly managed and cleaned up at the end of their usage, even when errors occur during processing. ### Part 1: Synchronous Reso...
import asyncio import contextlib # Part 1: Synchronous Resource Management @contextlib.contextmanager def sync_resource_manager(): print("Resource acquired") try: yield "resource" finally: print("Resource released") def use_synchronous_resource(): with sync_resource_manager() as resour...
from solution import use_synchronous_resource, use_asynchronous_resource, manage_multiple_resources, manage_multiple_async_resources def test_use_synchronous_resource(capfd): use_synchronous_resource() captured = capfd.readouterr() assert captured.out == "Resource acquired\nUsing resource\nResource release...
[ { "docstring": null, "function_declaration": "def sync_resource_manager():", "function_name": "sync_resource_manager", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def use_synchronous_resource():", "function_name": "use_synchronous_resource", "parameter...
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextlib\n\n# Part 1: Synchronous Resource Management\n@contextlib.contextmanager\ndef sync_resource_manager():\n print(\"Resource acquired\...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00042441", "row_id": 42441, "seed_ids": "[177]" }
0.389458
Docs: Python310_42441
I
[ "sync_resource_manager", "use_synchronous_resource", "async_resource_manager", "use_asynchronous_resource", "manage_multiple_resources", "manage_multiple_async_resources" ]
6
[ [ "manage_multiple_async_resources", "async_resource_manager" ], [ "manage_multiple_resources", "sync_resource_manager" ], [ "use_asynchronous_resource", "async_resource_manager" ], [ "use_synchronous_resource", "sync_resource_manager" ] ]
4
[]
false
[]
false
pytest
true
[]
true
74be43ac701825654a9fd59f2cd3b979afc7091b
843ca3e0953efe2fc0fb084a2dc6a669b2d18757
v1.0
instruct
Docs
Docs: Python310_42491_I
### Asynchronous File Processing and Network Communication **Objective:** Implement an asynchronous system that reads data from multiple files concurrently, processes the data, and sends the processed data to a server over a network. **Requirements:** 1. **Reading Files:** - Read data from multiple files concur...
import asyncio from asyncio import Lock async def read_file(file_path, file_lock, queue): async with file_lock: try: async with aiofiles.open(file_path, mode='r') as f: async for line in f: num = int(line.strip()) await queue.put(num + 1) ...
import pytest import asyncio from solution import process_and_send # Dummy server to receive incoming data async def dummy_server(reader, writer): received_data = [] while True: data = await reader.readline() if not data: break received_data.append(int(data.decode().strip())...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def read_file(file_path):\n async with aiofiles.open(file_path, 'r') as file:\n lines = await file.readlines()\n return [int(li...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00042491", "row_id": 42491, "seed_ids": "[360]" }
0.502204
Docs: Python310_42491
I
[ "read_file", "send_to_server", "process_and_send" ]
3
[ [ "process_and_send", "read_file" ], [ "process_and_send", "send_to_server" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ee7f3fe6eeb2b198cda415b9f3b041624f085ebc
05d76c8dcecaa38a88e61df070907d5c3d716cd2
v1.0
instruct
Docs
Docs: Python310_42492_I
### Asynchronous Web Scraper with asyncio #### Objective Design a Python function using the `asyncio` library to fetch data concurrently from multiple URLs, process the content, and store the results. #### Problem Statement You need to implement a function `async_web_scraper(urls: List[str]) -> Dict[str, int]` that t...
from typing import List, Dict import aiohttp import asyncio from collections import defaultdict async def fetch_content(url: str, session: aiohttp.ClientSession) -> str: try: async with session.get(url) as response: return await response.text() except Exception as e: print(f'Error f...
import pytest import asyncio from solution import async_web_scraper # Mock aiohttp for testing purposes class MockResponse: def __init__(self, text): self._text = text async def text(self): return self._text def release(self): pass class MockSession: def __init__(self...
[]
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import aiohttp\nimport asyncio\nfrom typing import List, Dict\n\nasync def fetch(url: str, session: aiohttp.ClientSession) -> str:\n \"\"\"\n Fetch the content of...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00042492", "row_id": 42492, "seed_ids": "[270]" }
0.628963
Docs: Python310_42492
I
[ "fetch_content", "process_url", "async_web_scraper" ]
3
[ [ "async_web_scraper", "process_url" ], [ "process_url", "fetch_content" ] ]
2
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
7155ac53f2d8f544b36ff9b846b3427c53b8aca4
54173da7d8848f8349dbb4c61dcb9c3ab72d054d
v1.0
instruct
Docs
Docs: Python310_42499_I
#### Task: You are tasked with processing a large list of text files to count the occurrences of a specific keyword in each file, and then aggregate the results. To achieve efficient processing and leverage multi-core CPUs, you will use the `concurrent.futures` module with `ThreadPoolExecutor`. #### Function Signature...
from typing import List import concurrent.futures def count_keyword_in_file(file_path: str, keyword: str) -> int: """ Counts the number of occurrences of the keyword in the file specified by file_path. Parameters: file_path (str): The path to the file where the keyword will be counted. keyword...
import pytest from solution import keyword_occurrence_counter def test_keyword_occurrence_counter(): # Setup file_list = ['file1.txt', 'file2.txt', 'file3.txt'] keyword = 'test' # Creating temporary files for testing with open('file1.txt', 'w', encoding='utf-8') as f: f.write('This is ...
[ { "docstring": "Counts the number of occurrences of the keyword in the file specified by file_path.\n\nParameters:\nfile_path (str): The path to the file where the keyword will be counted.\nkeyword (str): The keyword to count in the file.\n\nReturns:\nint: The number of occurrences of the keyword in the file.",...
[ 1, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport concurrent.futures\n\ndef count_keyword_in_file(file_path: str, keyword: str) -> int:\n \"\"\"\n This helper function counts the k...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00042499", "row_id": 42499, "seed_ids": "[224]" }
0.694165
Docs: Python310_42499
I
[ "count_keyword_in_file", "keyword_occurrence_counter" ]
2
[ [ "keyword_occurrence_counter", "count_keyword_in_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ec86886491028c8547bcf82bd1b9d546d9a830a5
63261d4f0cefcd4dc57ad5a9d861a1dc2b158d2e
v1.0
instruct
Docs
Docs: Python310_42577_I
**Coding Assessment Question:** You are required to implement a Python function `download_and_process_data(urls: List[str], timeout: int, max_workers: int) -> Dict[str, Any]` using the `concurrent.futures` module. This function should fetch data from multiple URLs using parallel tasks and process it. ### Function Sp...
import concurrent.futures import requests from typing import List, Dict, Any def fetch_url(url: str, timeout: int) -> Any: try: response = requests.get(url, timeout=timeout) response.raise_for_status() return response.content except Exception as e: return str(e) def download_an...
from solution import download_and_process_data def test_download_and_process_data_success_case(): urls = [ 'http://httpbin.org/get', 'http://httpbin.org/delay/1', 'http://httpbin.org/uuid' ] result = download_and_process_data(urls, timeout=5, max_workers=3) for url in urls: ...
[ { "docstring": null, "function_declaration": "def fetch_url(url, timeout):", "function_name": "fetch_url", "parameter_list": "(url, timeout)" }, { "docstring": null, "function_declaration": "def download_and_process_data(urls, timeout, max_workers):", "function_name": "download_and_p...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import concurrent.futures\nimport requests\nfrom typing import List, Dict, Any\n\ndef fetch_url(url: str, timeout: int) -> Any:\n try:\n response = requests.g...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00042577", "row_id": 42577, "seed_ids": "[347]" }
0.543027
Docs: Python310_42577
I
[ "fetch_url", "download_and_process_data" ]
2
[ [ "download_and_process_data", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
0869adb3b3fff3b70cd2f4ec55b80635edb5e090
dcf273a30b77c26212fb0b27d82fc332596c92f3
v1.0
instruct
Docs
Docs: Python310_42627_I
### Advanced Python Programming Assignment You are tasked with enhancing a command-line interface (CLI) Python application by incorporating features from the `readline` module. Your solution should demonstrate the use of various functionalities of the `readline` module to improve the experience of the CLI application....
import readline import os import atexit # Define available commands for the custom completer COMMANDS = ['help', 'exit', 'load', 'save', 'list'] def completer(text, state): options = [cmd for cmd in COMMANDS if cmd.startswith(text)] if state < len(options): return options[state] else: retu...
import os import readline from pytest import fixture; @fixture(autouse=True) def prepare_history_file(): histfile = os.path.join(os.path.expanduser("~"), ".cli_history") if os.path.exists(histfile): os.remove(histfile) yield if os.path.exists(histfile): os.remove(histfile) def test_his...
[ { "docstring": null, "function_declaration": "def completer(text, state):", "function_name": "completer", "parameter_list": "(text, state)" }, { "docstring": null, "function_declaration": "def load_history():", "function_name": "load_history", "parameter_list": "()" }, { ...
[ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport readline\n\nHISTORY_FILE = os.path.expanduser(\"~/.cli_history\")\nCOMMANDS = ['help', 'exit', 'load', 'save', 'list']\nHISTORY_LENGTH = 500\n\ndef co...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00042627", "row_id": 42627, "seed_ids": "[362]" }
0.481048
Docs: Python310_42627
I
[ "completer", "load_history", "save_history", "run_cli" ]
4
[ [ "run_cli", "completer" ], [ "run_cli", "load_history" ], [ "run_cli", "save_history" ] ]
3
[]
false
[]
false
pytest
true
[]
true
1954c9fef748446dd6429a2a9d4fc173619f973e
997e82c801b00122d54b4ad30da99aeb87bc1380
v1.0
instruct
Docs
Docs: Python310_42706_I
### Resource Management and Usage Monitoring You are required to manage and monitor system resources using Python's `resource` module. This will involve limiting resource usage by processes and retrieving detailed resource consumption data. #### Problem Statement 1. **Resource Limiting**: Write a function `limit_cpu...
import resource def limit_cpu_time(seconds): """Limits the CPU time for the current process to `seconds` seconds.""" try: resource.setrlimit(resource.RLIMIT_CPU, (seconds, seconds)) except resource.error as e: print(f"Error setting CPU limit: {str(e)}") def get_process_usage(detail=False):...
import pytest import time from solution import limit_cpu_time, get_process_usage, monitor_cpu_limited_task def test_limit_cpu_time(): try: limit_cpu_time(1) assert True # If no exception, test passes except Exception: assert False # If there is an exception, test fails def test_get_p...
[ { "docstring": "Limits the CPU time for the current process to `seconds` seconds.", "function_declaration": "def limit_cpu_time(seconds):", "function_name": "limit_cpu_time", "parameter_list": "(seconds)" }, { "docstring": "Retrieves the resource usage statistics for the current process.\n\n...
[ 1, 1, 1, 1, 1, 1, 0, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import resource\n\ndef limit_cpu_time(seconds):\n \"\"\"Limits the CPU time for the current process to `seconds` seconds.\"\"\"\n try:\n resource.setrlimit...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00042706", "row_id": 42706, "seed_ids": "[312]" }
0.668155
Docs: Python310_42706
I
[ "limit_cpu_time", "get_process_usage", "monitor_cpu_limited_task" ]
3
[ [ "monitor_cpu_limited_task", "get_process_usage" ], [ "monitor_cpu_limited_task", "limit_cpu_time" ] ]
2
[]
false
[]
false
pytest
true
[]
true
29f519ff12968cb14bfd4f33be367c0397d078c6
46772a152d36a88bc47328fe037cd01871004231
v1.0
instruct
Docs
Docs: Python310_42727_I
**Question: Implementing an Asynchronous Task Scheduler** You are requested to implement an asynchronous task scheduler using Python's asyncio module. The task scheduler should be able to perform the following: 1. **Run multiple asynchronous tasks concurrently.** 2. **Distribute tasks among worker coroutines using di...
import asyncio from asyncio import Queue, PriorityQueue, LifoQueue from typing import List, Coroutine, Any class Task: def __init__(self, priority, coro): self.priority = priority self.coro = coro def __lt__(self, other): return self.priority < other.priority async def worker(queue, r...
import asyncio import pytest from solution import schedule_tasks async def sample_task(duration: int, result: str) -> str: await asyncio.sleep(duration) return result def create_tasks(): return [ sample_task(3, "Task1"), sample_task(2, "Task2"), sample_task(1, "Task3") ] @pyte...
[]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Coroutine, Any\nfrom asyncio import Queue, PriorityQueue, LifoQueue\n\nasync def worker(queue: Queue, results: List[Any], timeo...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00042727", "row_id": 42727, "seed_ids": "[360]" }
0.596178
Docs: Python310_42727
I
[ "worker", "schedule_tasks" ]
2
[ [ "schedule_tasks", "worker" ] ]
1
[]
false
[ "Task" ]
true
pytest
true
[]
true
6c7c2fc523b0b6c063e889f980ea3e850a1378cf
d204144c7db4e2541e11eec2f2aedc88775aca14
v1.0
instruct
Docs
Docs: Python310_42752_I
**Objective**: Implement a function to simulate a server that processes client requests using the `asyncio` event loop in Python. ### Problem Statement You are tasked with creating a server that can handle multiple client requests asynchronously using the `asyncio` package. Your server should: 1. Accept client conne...
import asyncio async def handle_client(reader, writer): try: data = await reader.read(100) message = data.decode().strip() numbers = list(map(int, message.split(','))) result = sum(numbers) response = str(result) writer.write(response.encode()) await...
import asyncio import socket import pytest from solution import async_server @pytest.fixture def event_loop(): loop = asyncio.new_event_loop() yield loop loop.close() async def send_data(host, port, data): reader, writer = await asyncio.open_connection(host, port) writer.write(data.encode()) a...
[]
[ 0, 1, 0, 1, 1, 1, 1, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n try:\n data = await reader.read(100)\n message = data.decode()\n numbers = list(map...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00042752", "row_id": 42752, "seed_ids": "[267]" }
0.631625
Docs: Python310_42752
I
[ "handle_client", "async_server" ]
2
[ [ "async_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1fe90927747041ef99c90d617742c23039f0b9ab
bd3488f584cdcf9ac5df0f7e59eb98261ac52ce4
v1.0
instruct
Docs
Docs: Python310_42768_I
#### Title: Parallel Matrix Multiplication using `concurrent.futures` **Objective**: Demonstrate comprehension of asynchronous execution, thread management, and exception handling using the `concurrent.futures` module in Python. **Problem Statement**: Parallelize the computation of matrix multiplication using `Threa...
from concurrent.futures import ThreadPoolExecutor from typing import List def compute_element(A: List[List[int]], B: List[List[int]], row: int, col: int) -> int: # Helper function to compute the value of a single element in the result matrix (row, col) return sum(A[row][k] * B[k][col] for k in range(len(B))) ...
from solution import parallel_matrix_multiply def test_small_matrix_multiplication(): A = [ [1, 2, 3], [4, 5, 6] ] B = [ [7, 8], [9, 10], [11, 12] ] expected = [ [58, 64], [139, 154] ] assert parallel_matrix_multiply(A, B) == expected ...
[ { "docstring": null, "function_declaration": "def compute_element(A, B, row, col):", "function_name": "compute_element", "parameter_list": "(A, B, row, col)" }, { "docstring": "Multiplies two matrices A and B using parallel computation.", "function_declaration": "def parallel_matrix_mult...
[ 0, 1, 0, 0, 1, 1, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List\n\ndef compute_element(A: List[List[int]], B: List[List[int]], i: int, j: int) ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00042768", "row_id": 42768, "seed_ids": "[347]" }
0.500829
Docs: Python310_42768
I
[ "compute_element", "parallel_matrix_multiply" ]
2
[ [ "parallel_matrix_multiply", "compute_element" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0550557d5a095cde8e198ae0d7ac7e04a4eb04ad
47ebe9bd15d8031e7567665bc0b922c9ac70de21
v1.0
instruct
Docs
Docs: Python310_42818_I
### Python Coding Assessment: Custom Byte-Compilation Function The `compileall` module in Python provides various utility functions to compile Python source files into bytecode. This task will assess your understanding of Python file handling, recursion, and multiprocessing by asking you to implement a simplified vers...
import os import re import py_compile from multiprocessing import Pool def _compile_file(file, force, optimization_level): try: py_compile.compile(file, cfile=None, dfile=None, doraise=not force, optimize=optimization_level) return True except py_compile.PyCompileError: return False de...
import os import tempfile import shutil import pytest from solution import custom_compile_dir @pytest.fixture def setup_test_environment(): base_dir = tempfile.mkdtemp() sub_dir = os.path.join(base_dir, "sub") os.makedirs(sub_dir) # Create some .py files py_files = [ os.path.join(base_...
[ { "docstring": null, "function_declaration": "def _compile_file(file, force, optimization_level):", "function_name": "_compile_file", "parameter_list": "(file, force, optimization_level)" }, { "docstring": null, "function_declaration": "def _should_exclude(file, excluded_patterns):", ...
[ 0, 0, 0, 1, 0, 0, 0, 1, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport re\nimport py_compile\nfrom pathlib import Path\nfrom multiprocessing import Pool\n\ndef should_exclude(file_path, patterns):\n if patterns is None...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00042818", "row_id": 42818, "seed_ids": "[369]" }
0.545604
Docs: Python310_42818
I
[ "_compile_file", "_should_exclude", "custom_compile_dir" ]
3
[ [ "custom_compile_dir", "_compile_file" ], [ "custom_compile_dir", "_should_exclude" ] ]
2
[]
false
[]
false
pytest
true
[]
true
69ccfbc83e45d457838e83a90928c67400865ad1
848a16d17ae3103859e2a28e721ca90f618975a2
v1.0
instruct
Docs
Docs: Python310_42829_I
**Objective**: Implement a pair of functions that demonstrate the compression and decompression of data using Python's `zlib` library, along with checksum verification to ensure data integrity. #### Problem Statement Implement the following functions: 1. `compress_data(data: bytes, level: int = -1) -> bytes`: - T...
import zlib def compress_data(data: bytes, level: int = -1) -> bytes: """ Compress the input bytes data using zlib with the specified compression level. :param data: Input data in bytes to be compressed. :param level: Compression level, with -1 being the default. :return: Compressed data in bytes. ...
import pytest from solution import compress_data, decompress_data, checksum_verification def test_compress_decompress(): original = b'This is a test string for compression and decompression.' compressed = compress_data(original, level=6) decompressed = decompress_data(compressed) assert decompress...
[ { "docstring": "Compress the input bytes data using zlib with the specified compression level.\n:param data: Input data in bytes to be compressed.\n:param level: Compression level, with -1 being the default.\n:return: Compressed data in bytes.", "function_declaration": "def compress_data(data, level=-1):", ...
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import zlib\n\ndef compress_data(data: bytes, level: int = -1) -> bytes:\n \"\"\"\n Compress the given data using zlib with the specified compression level.\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00042829", "row_id": 42829, "seed_ids": "[299]" }
0.572557
Docs: Python310_42829
I
[ "compress_data", "decompress_data", "checksum_verification" ]
3
[ [ "checksum_verification", "decompress_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cf6b6d994078e084af019531afba6553a7a8b1aa
b5b132925614565e9b4d79a10d6e4f8992fbbde3
v1.0
instruct
Docs
Docs: Python310_42833_I
**Complex Event-Driven Application using Asyncio** ### Problem Statement You are required to design and implement a simplified event-driven application using Python's `asyncio` module. This application simulates a basic server-client model where multiple clients send requests to the server concurrently, and the serv...
import asyncio from asyncio import StreamReader, StreamWriter from typing import Tuple async def handle_client_request(reader: StreamReader, writer: StreamWriter, delay: int): """Handles client request by introducing a simulated processing delay. Args: reader (StreamReader): The reader stream for ...
import asyncio import pytest from solution import start_server, simulate_client_request @pytest.mark.asyncio async def test_server_response(): server_task = asyncio.create_task(start_server('127.0.0.1', 8888, 1)) await asyncio.sleep(1) response = await simulate_client_request('127.0.0.1', 8888, 'Hello...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom asyncio import StreamReader, StreamWriter\nfrom typing import Tuple\n\nasync def handle_client_request(reader: StreamReader, writer: StreamWriter, ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00042833", "row_id": 42833, "seed_ids": "[360]" }
0.561617
Docs: Python310_42833
I
[ "handle_client_request", "start_server", "simulate_client_request" ]
3
[ [ "start_server", "handle_client_request" ] ]
1
[]
false
[]
false
pytest
true
[]
true
77097dda9dd6a67ccc05f8a16dfc640b7d93189a
9ef533f618be0f65da1c23ced1332954e98ccf7e
v1.0
instruct
Docs
Docs: Python310_42845_I
**Question: Implementing a Mock of Python Cell Objects** In Python, cell objects are a crucial part of closures, allowing variables to be referenced by multiple scopes. Your task is to implement a mock version of these cell objects in pure Python. This will help you understand the underlying mechanism of how closures ...
class Cell: """ Mock implementation of Python cell objects. """ def __init__(self, value): self._value = value def get(self): """ Returns the value contained in the cell. """ return self._value def set(self, value): """ Sets a new value t...
from solution import Cell, cell_check, cell_new, cell_get, cell_set def test_cell_creation(): c = cell_new(10) assert cell_get(c) == 10 def test_cell_set(): c = cell_new(10) cell_set(c, 20) assert cell_get(c) == 20 def test_cell_check(): c = cell_new(10) assert cell_check(c) is True a...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Cell:\n def __init__(self, value):\n self.value = value\n \n def get(self):\n return self.value\n \n def set(self, value):\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00042845", "row_id": 42845, "seed_ids": "[38]" }
0.412884
Docs: Python310_42845
I
[ "cell_check", "cell_new", "cell_get", "cell_set" ]
4
[ [ "cell_get", "cell_check" ], [ "cell_set", "cell_check" ] ]
2
[]
false
[ "Cell" ]
true
pytest
true
[]
true
fc997e3f85a798bfcfee4814a794beb49daab11a
cae3c533ce03aa3a7d153fb2fb6efe2e8329e913
v1.0
instruct
Docs
Docs: Pytorch_42965_I
### Distributed Checkpointing in PyTorch **Objective:** Implement a coding solution to save and load a distributed model's state using PyTorch's Distributed Checkpoint (DCP) functionality. This task will assess your understanding of distributed model parallelism, state dictionary management, and asynchronous operatio...
import torch import torch.distributed.checkpoint as dcp import os def get_model_state_dict(model: torch.nn.Module): """ Returns the state dict of the model ensuring it always gets the state dict of the base model if wrapped in DataParallel or DistributedDataParallel """ if isinstance(model, (torch...
import torch import torch.nn as nn import torch.optim as optim import os import shutil import pytest from solution import save_distributed_checkpoint, load_distributed_checkpoint # Dummy model and optimizer for testing class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() ...
[ { "docstring": "Returns the state dict of the model ensuring it always gets the \nstate dict of the base model if wrapped in DataParallel or DistributedDataParallel", "function_declaration": "def get_model_state_dict(model):", "function_name": "get_model_state_dict", "parameter_list": "(model)" },...
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.distributed as dist\nimport torch.distributed.checkpoint as dcp\n\ndef get_model_state_dict(model: torch.nn.Module) -> dict:\n \"\"\"\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00042965", "row_id": 42965, "seed_ids": "[30]" }
0.442257
Docs: Pytorch_42965
I
[ "get_model_state_dict", "get_optimizer_state_dict", "save_distributed_checkpoint", "load_distributed_checkpoint" ]
4
[ [ "save_distributed_checkpoint", "get_model_state_dict" ], [ "save_distributed_checkpoint", "get_optimizer_state_dict" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
dc153ea7a21a72fe56d9f8fb3ad8c1a7f25a9421
94f014bb72d1f86c33fe8229adf62d595f3f6e81
v1.0
instruct
Docs
Docs: Pytorch_42967_I
**Coding Challenge: Pure Functions and Transformations with PyTorch** **Objective:** Demonstrate your understanding of transformations in `torch.func` by implementing a pure function and applying various `torch.func` transformations while complying with described constraints. **Problem Statement:** You need to imple...
import torch from torch.func import grad, vmap def sum_of_squares(x: torch.Tensor) -> torch.Tensor: """ Computes the sum of squares of all elements in the tensor `x`. """ return torch.sum(x ** 2) def gradient_of_sum_of_squares(x: torch.Tensor) -> torch.Tensor: """ Calculates the gradient of th...
import pytest import torch from solution import sum_of_squares, gradient_of_sum_of_squares, vectorized_sum_of_squares, modified_sum_of_squares def test_sum_of_squares(): x = torch.tensor([1.0, 2.0, 3.0]) assert sum_of_squares(x).item() == 14.0 def test_gradient_of_sum_of_squares(): x = torch.tensor([1.0, ...
[ { "docstring": "Computes the sum of squares of all elements in the tensor `x`.", "function_declaration": "def sum_of_squares(x):", "function_name": "sum_of_squares", "parameter_list": "(x)" }, { "docstring": "Calculates the gradient of the sum_of_squares function.", "function_declaration...
[ 1, 0, 0, 0, 0, 0, 1, 0, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.func import grad, vmap\n\ndef sum_of_squares(x: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Computes the sum of the squares of all elements...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00042967", "row_id": 42967, "seed_ids": "[136]" }
0.560105
Docs: Pytorch_42967
I
[ "sum_of_squares", "gradient_of_sum_of_squares", "vectorized_sum_of_squares", "modified_sum_of_squares" ]
4
[ [ "gradient_of_sum_of_squares", "sum_of_squares" ], [ "vectorized_sum_of_squares", "sum_of_squares" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
c2d85646b3a8cf013ddbc7800afc74260fe5eb78
a514957e797dc82f6eb4353925c532f34dd1d0c5
v1.0
instruct
Docs
Docs: Python310_42997_I
### Multi-threaded Temperature Logger As part of a climate monitoring system, you need to implement a temperature logger that records temperature readings from different sensors concurrently. Each sensor runs in its own thread and writes temperature data to a shared log file. To ensure that the log file is not corrupt...
import random import _thread import time def log_temperature(sensor_id, log_file, lock): """ Simulate a sensor reading and log it to the log file in a thread-safe manner. """ temperature = round(random.uniform(-30.0, 50.0), 2) with lock: log_file.write(f"Sensor {sensor_id}: {temperature}\n"...
import os import time from solution import start_logging def test_logging_creates_file(): log_filename = 'test_temperature_log.txt' sensor_count = 5 if os.path.exists(log_filename): os.remove(log_filename) start_logging(sensor_count, log_filename) time.sleep(1.5) # Wait for...
[ { "docstring": "Simulate a sensor reading and log it to the log file in a thread-safe manner.", "function_declaration": "def log_temperature(sensor_id, log_file, lock):", "function_name": "log_temperature", "parameter_list": "(sensor_id, log_file, lock)" }, { "docstring": "Start multiple sen...
[ 1, 0, 0, 1, 0, 1, 0, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport _thread\nimport time\n\ndef log_temperature(sensor_id, log_file, lock):\n \"\"\"\n Logs the temperature reading from a sensor to a log file ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00042997", "row_id": 42997, "seed_ids": "[223]" }
0.465827
Docs: Python310_42997
I
[ "log_temperature", "start_logging" ]
2
[ [ "start_logging", "log_temperature" ] ]
1
[]
false
[]
false
pytest
true
[]
true
54a798cbfae0b484206ac4da09fdce4804a57f29
9dad075c36d3d5d2059c83ac33a09b000732804c
v1.0
instruct
Docs
Docs: Python310_43027_I
**Objective**: Demonstrate the effective use of the `contextvars` module, especially in the context of asynchronous programming. #### Problem Statement You are tasked with developing a logging system for an asynchronous web server. The logging system should record the IP address and port of the client making requests...
from contextvars import ContextVar import asyncio # Define the context variable client_addr_var = ContextVar('client_addr') def log_client_info(): """ Log the client address using the context variable. """ client_addr = client_addr_var.get() print(f"Client Address: {client_addr[0]}:{client_addr[1]...
import pytest from contextvars import ContextVar import asyncio from unittest.mock import patch # Redefine the context variable locally for test isolation client_addr_var = ContextVar('client_addr') # Re-implement the functions in local scope for testing def log_client_info(): client_addr = client_addr_var.get() ...
[ { "docstring": "Log the client address using the context variable.", "function_declaration": "def log_client_info():", "function_name": "log_client_info", "parameter_list": "()" } ]
[ 0, 0, 0, 1, 1, 1, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from contextvars import ContextVar\nimport asyncio\n\n# Define the context variable\nclient_addr_var = ContextVar('client_addr', default=None)\n\ndef log_client_info():...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00043027", "row_id": 43027, "seed_ids": "[392]" }
0.601066
Docs: Python310_43027
I
[ "log_client_info", "handle_request", "main" ]
3
[ [ "handle_request", "log_client_info" ] ]
1
[]
false
[]
false
pytest
false
[]
true
33231e8b3aaf95063355c53d8f3c00673edb42bf
f7ce9b40c063202053d94b59de1ddde0ff47b961
v1.0
instruct
Docs
Docs: Scikit_43068_I
**Out-of-Core Learning with scikit-learn** As a data scientist, you are tasked with building an out-of-core learning system to classify text data that is too large to fit into memory. You need to implement a system that reads and processes the data in mini-batches, extracts features using the hashing trick, and increm...
import pandas as pd import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier def stream_data(file_path, batch_size): """ Generator function to read data from a large CSV file in mini-batches. Args: file_path (str): The path to the ...
import os import pytest from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from solution import stream_data, train_incremental_model # Mock data creation for testing purposes file_path = 'test_large_text_data.csv' mock_data = { 'text': ['sample text data'] ...
[ { "docstring": "Generator function to read data from a large CSV file in mini-batches.\n\nArgs:\nfile_path (str): The path to the CSV file.\nbatch_size (int): The number of examples in each batch.\n\nYields:\nTuple[np.array, np.array]: Batches of features and labels.", "function_declaration": "def stream_da...
[ 0, 1, 1, 0, 1, 0, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\n\ndef stream_dat...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00043068", "row_id": 43068, "seed_ids": "[63]" }
0.474675
Docs: Scikit_43068
I
[ "stream_data", "train_incremental_model" ]
2
[ [ "train_incremental_model", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "pandas", "sklearn" ]
false
cf33e73bb438401f2c2b68dac45e56a37f9afd50
76ffba87a734109e9e32409cf8029cebabebeca6
v1.0
instruct
Docs
Docs: Pytorch_43090_I
Fine-Grained Control of TorchDynamo Tracing **Objective**: Implement a portion of a PyTorch model using the TorchDynamo fine-grained tracing control APIs to manage parts of the model that may not be compatible with default tracing behavior. #### Background You are provided with a simple PyTorch model that has one fun...
import torch # Placeholder function to simulate the effect of torch.compiler.disable (actual tracing) def torch_compile_disable(func): def wrapper(*args, **kwargs): # Directly call the function without any tracing return func(*args, **kwargs) return wrapper # Define the functions as described ...
import torch from solution import fn, compiled_fn def test_fn(): x = torch.tensor(5) result = compiled_fn(x) expected = (5 + 1 + 2) + (5 * 3) # Equivalent to a_fn(5) + b_fn(5) assert result.item() == expected def test_a_fn_disabled(): x = torch.tensor(5) result_a = a_fn(x) assert result_a...
[ { "docstring": null, "function_declaration": "def torch_compile_disable(func):", "function_name": "torch_compile_disable", "parameter_list": "(func)" }, { "docstring": null, "function_declaration": "def affected_fn(x):", "function_name": "affected_fn", "parameter_list": "(x)" }...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torchdynamo\n\ndef aa_fn(x):\n return x + 1\n\n# Apply torchdynamo.disable on a_fn\n@torchdynamo.disable\ndef a_fn(x):\n return aa_fn(x) + 2\...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00043090", "row_id": 43090, "seed_ids": "[87]" }
0.457285
Docs: Pytorch_43090
I
[ "torch_compile_disable", "affected_fn", "a_fn", "b_fn", "fn", "mock_compile" ]
6
[ [ "a_fn", "affected_fn" ], [ "fn", "a_fn" ], [ "fn", "b_fn" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
7b3e59e3b0e3668277285654e4f00100d99ab489
a5087896a91ab67d76f576adb53b7adadf001d7c
v1.0
instruct
Docs
Docs: Python310_43121_I
### Python Coding Assessment Question #### Objective Implement a class and methods to simulate basic behaviors of Python's cell objects. This will test your understanding of variable scoping, references, and closures. #### Task Create a Python class `Cell` which mimics the behavior of Python's internal cell objects. ...
class Cell: def __init__(self, obj): """ Initializes the cell with the given object. """ self._obj = obj def get(self): """ Returns the current value stored in the cell. """ return self._obj def set(self, obj): """ Sets the ce...
from solution import Cell, make_closure def test_cell_initialization(): cell = Cell(5) assert cell.get() == 5 def test_cell_set_and_get(): cell = Cell(5) cell.set(10) assert cell.get() == 10 def test_closure_incrementor(): cell = Cell(10) def incrementor(cell): current_val = ...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Cell:\n def __init__(self, obj=None):\n self._obj = obj\n\n def get(self):\n return self._obj\n\n def set(self, obj):\n self._obj = ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00043121", "row_id": 43121, "seed_ids": "[38]" }
0.526029
Docs: Python310_43121
I
[ "make_closure", "test_closure" ]
2
[ [ "test_closure", "make_closure" ] ]
1
[]
false
[ "Cell" ]
true
pytest
true
[]
true
f838d7c847f2dea37cfd0405dc7d4e6ffa737200
d7905d3832444856825e06812b14f06d16a95f49
v1.0
instruct
Docs
Docs: Python310_43148_I
### Advanced Programming Question: Concurrent URL Fetcher with asyncio Using the information provided in the documentation about asyncio, design and implement a Python function called `fetch_all_urls` that concurrently fetches content from multiple URLs. #### Function Signature ```python import asyncio import aiohttp...
import asyncio import aiohttp async def fetch_url(session, url): try: async with session.get(url) as response: response.raise_for_status() return url, await response.text() except Exception as e: return url, str(e) async def fetch_all_urls(url_list: list, max_concurrent...
import asyncio import pytest from solution import fetch_all_urls async def mock_server(request): return web.Response(text="Test response") def test_fetch_all_urls_with_valid_urls(): url_list = [ 'https://httpbin.org/get', 'https://jsonplaceholder.typicode.com/posts/1' ] max_concurrent_...
[]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\n\nasync def fetch_url(session, url):\n try:\n async with session.get(url) as response:\n response.raise_for_status(...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00043148", "row_id": 43148, "seed_ids": "[270]" }
0.551609
Docs: Python310_43148
I
[ "fetch_url", "fetch_all_urls" ]
2
[ [ "fetch_all_urls", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
4f2d43fcda24d0207e0c2a84bd4757d4499ec173
e85128f4ea2e36d670aa2eaac183e579b8b55e7f
v1.0
instruct
Docs
Docs: Python310_43162_I
### Complex Number Operations in Python #### Objective You are tasked with implementing a set of functions to perform arithmetic operations on complex numbers in Python. You will use both C structure representations and Python object representations to demonstrate your understanding of the underlying mechanisms. ####...
class Py_complex: def __init__(self, real, imag): self.real = real self.imag = imag def from_pycomplex_to_py_complex(py_complex_obj): """ Converts a Python complex object to a Py_complex C structure. """ return Py_complex(py_complex_obj.real, py_complex_obj.imag) def from_py_comple...
from solution import Py_complex, complex_sum, complex_diff, complex_prod, complex_quot from solution import from_pycomplex_to_py_complex, from_py_complex_to_pycomplex def test_complex_sum(): c1 = Py_complex(1.0, 2.0) c2 = Py_complex(3.0, 4.0) result = complex_sum(c1, c2) expected = Py_complex(4.0, 6.0)...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Py_complex:\n def __init__(self, real=0.0, imag=0.0):\n self.real = real\n self.imag = imag\n\ndef from_pycomplex_to_py_complex(py_complex_obj):\...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00043162", "row_id": 43162, "seed_ids": "[1]" }
0.599658
Docs: Python310_43162
I
[ "from_pycomplex_to_py_complex", "from_py_complex_to_pycomplex", "complex_sum", "complex_diff", "complex_prod", "complex_quot" ]
6
[ [ "complex_diff", "from_py_complex_to_pycomplex" ], [ "complex_diff", "from_pycomplex_to_py_complex" ], [ "complex_prod", "from_py_complex_to_pycomplex" ], [ "complex_prod", "from_pycomplex_to_py_complex" ], [ "complex_quot", "from_py_complex_to_pycomplex" ]...
8
[]
false
[ "Py_complex" ]
true
pytest
true
[]
true
293b819105329e4918673e60f225b5348b734eac
57c90d16dcc2a5222f3b38746daf77d6c5ae0d35
v1.0
instruct
Docs
Docs: Python310_43224_I
### Advanced Python Context Management #### Context You are tasked with managing multiple resource operations with different life cycles that need to be cleaned up properly. Specifically, you have operations that require opening multiple files, acquiring and releasing a network resource, and conditionally executing a...
import contextlib class network_resource: def __enter__(self): print("Opening network resource") return self def __exit__(self, exc_type, exc_val, exc_tb): print("Releasing network resource") def log_event(message): print(message) def manage_resources(filenames): with context...
import pytest from solution import manage_resources, network_resource def test_manage_resources_no_files(tmp_path): filenames = [] manage_resources(filenames) def test_manage_resources_with_files(tmp_path): file1 = tmp_path / "test1.txt" file1.write_text("This is a test file.\nAnother line.\n") fi...
[]
[ 1, 1, 1, 1, 1, 1, 0, 1, 0, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import contextlib\nfrom typing import List\n\nclass network_resource:\n def __enter__(self):\n print(\"Opening network resource\")\n return self\n\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00043224", "row_id": 43224, "seed_ids": "[177]" }
0.534594
Docs: Python310_43224
I
[ "log_event", "manage_resources" ]
2
[ [ "manage_resources", "log_event" ] ]
1
[]
false
[ "network_resource" ]
true
pytest
true
[]
true
94fd5e084571687543f4479a009c205c696c8b87
408423cb2e5f50c7853fe3a9c81d522574e5c810
v1.0
instruct
Docs
Docs: Python310_43226_I
### Python 310 Coding Assessment Question #### Objective: To assess your understanding of asynchronous programming in Python using coroutines. #### Problem Statement: You are tasked with implementing a Python module that utilizes coroutines to process data concurrently. In this exercise, you will create an asynchrono...
import asyncio from typing import List async def fetch_data(source: str) -> str: delay = len(source) * 0.1 # Example delay: 0.1 seconds per character in source await asyncio.sleep(delay) return f"Data from {source}" async def aggregate_data(sources: List[str]) -> List[str]: tasks = [fetch_data(source...
import asyncio import pytest from solution import fetch_data, aggregate_data @pytest.mark.asyncio async def test_fetch_data(): result = await fetch_data("source1") assert result == "Data from source1" @pytest.mark.asyncio async def test_aggregate_data(): sources = ["source1", "source2", "source3"] res...
[]
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List\n\nasync def fetch_data(source: str) -> str:\n delay = len(source) * 0.1 # Example delay: 0.1 seconds per character in sourc...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00043226", "row_id": 43226, "seed_ids": "[8]" }
0.59346
Docs: Python310_43226
I
[ "fetch_data", "aggregate_data" ]
2
[ [ "aggregate_data", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
68d165205c64f1830ba0dbcb5ea24a452de3c3c4
0bb719ec72d0b93ce27c45ba16bbe3bdc74aa120
v1.0
instruct
Docs
Docs: Python310_43260_I
**CGI Form Processing and Error Handling** In this coding assessment, you will create a CGI script that processes user input from an HTML form, handles various possible input cases, and outputs the results in a structured HTML format. Your script should demonstrate proficiency with the `cgi` module, and handle potenti...
import cgi import cgitb cgitb.enable() def generate_html_response(username, age, hobbies, error_message=None): print("Content-Type: text/html\n") print("<html>") print("<head><title>Form Response</title></head>") print("<body>") if error_message: print(f"<h1>Error</h1><p>{error_messag...
import pytest from solution import process_form, generate_html_response from io import StringIO import sys def test_process_form_valid_data(monkeypatch): form_data = "username=JaneDoe&age=25&hobbies=Reading&hobbies=Swimming" monkeypatch.setattr(sys, "stdin", StringIO(form_data)) def dummy_print(*args, **k...
[ { "docstring": null, "function_declaration": "def generate_html_response(username, age, hobbies, error_message=None):", "function_name": "generate_html_response", "parameter_list": "(username, age, hobbies, error_message=None)" }, { "docstring": null, "function_declaration": "def process...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cgi\nimport cgitb\n\ncgitb.enable() # Enable error reporting\n\ndef process_form():\n form = cgi.FieldStorage()\n\n # Extract form fields\n username = ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00043260", "row_id": 43260, "seed_ids": "[183]" }
0.457415
Docs: Python310_43260
I
[ "generate_html_response", "process_form" ]
2
[ [ "process_form", "generate_html_response" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0e4fb48a8a16085d3b8ee92909f931f28724be8e
d763d3a95d2d205f7a10bc1b5d08c78d8bc8b549
v1.0
instruct
Docs
Docs: Python310_43262_I
You are tasked with implementing a function to parse and validate email headers according to RFC 5322 standards. The function will need to handle various error conditions using the appropriate exception classes from the `email.errors` module. #### Function Signature ```python def validate_email_headers(headers: List[...
import re from email.errors import HeaderParseError, FirstHeaderLineIsContinuationDefect, MalformedHeaderDefect, InvalidDateDefect from typing import List def validate_email_headers(headers: List[str]) -> List[str]: errors = [] # Define a basic regex for header parsing header_pattern = re.compile(r'^[...
from solution import validate_email_headers def test_validate_email_headers_no_errors(): headers = [ "From: example@example.com", "To: user@example.com", "Date: Fri, 21 Nov 1997 09:55:06 -0600", "Subject: Test email" ] assert validate_email_headers(headers) == [] def test_v...
[ { "docstring": null, "function_declaration": "def validate_email_headers(headers):", "function_name": "validate_email_headers", "parameter_list": "(headers)" }, { "docstring": null, "function_declaration": "def validate_date(date_str):", "function_name": "validate_date", "paramet...
[ 0, 0, 1, 0, 0, 0, 1, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nfrom email.errors import HeaderParseError, FirstHeaderLineIsContinuationDefect, MalformedHeaderDefect, InvalidDateDefect\nfrom typing import List\n\ndef vali...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00043262", "row_id": 43262, "seed_ids": "[232]" }
0.594439
Docs: Python310_43262
I
[ "validate_email_headers", "validate_date" ]
2
[ [ "validate_email_headers", "validate_date" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3c3d01d98b9dbc3e3b5f88ffa8bcb086f9bcad53
abc7cf704775b21adb8f59807be4301fb81ae16a
v1.0
instruct
Docs
Docs: Python310_43355_I
**Title:** Asynchronous Task Processing with Priority Queue **Problem Statement:** You are tasked with implementing an asynchronous task scheduler using `asyncio.PriorityQueue`. The scheduler will manage a set of tasks with varying priorities and ensure that higher priority tasks are processed before lower priority o...
import asyncio from typing import List, Tuple import time async def worker(queue: asyncio.PriorityQueue): while True: priority, duration = await queue.get() await asyncio.sleep(duration) queue.task_done() async def task_scheduler(tasks: List[Tuple[int, float]]): queue = asyncio.Priorit...
import asyncio import time from solution import task_scheduler def test_task_scheduler(): tasks = [(1, 2.5), (3, 1.0), (2, 3.0), (4, 0.5)] asyncio.run(task_scheduler(tasks)) def test_task_scheduler_with_no_tasks(): tasks = [] asyncio.run(task_scheduler(tasks)) def test_task_scheduler_with_equal_prior...
[]
[ 1, 1, 1, 1, 0, 1, 0, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\nimport time\n\nasync def worker(name: str, queue: asyncio.PriorityQueue):\n while True:\n priority, duration =...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00043355", "row_id": 43355, "seed_ids": "[111]" }
0.602348
Docs: Python310_43355
I
[ "worker", "task_scheduler" ]
2
[ [ "task_scheduler", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dcd70534aa7915311487a2e9781ebd4299c38b77
aea6a7869a5aaf07b3d6ebc5a6d01d43cbc0bc61
v1.0
instruct
Docs
Docs: Python310_43405_I
#### Objective Design a concurrent system that processes text files in parallel and aggregates word counts across multiple files. #### Task You will implement two functions: `count_words_in_file` and `aggregate_word_counts`. 1. **`count_words_in_file(file_path: str) -> Dict[str, int]`** - This function accepts a ...
import re from collections import defaultdict, Counter from concurrent.futures import ThreadPoolExecutor from typing import Dict, List def count_words_in_file(file_path: str) -> Dict[str, int]: word_count = defaultdict(int) try: with open(file_path, 'r') as file: for line in file: ...
import pytest from solution import count_words_in_file, aggregate_word_counts def test_count_words_in_file(tmp_path): text = "Hello world! Hello Python." file_path = tmp_path / "file1.txt" with open(file_path, "w") as f: f.write(text) expected = {'hello': 2, 'world': 1, 'python': 1} assert ...
[ { "docstring": null, "function_declaration": "def count_words_in_file(file_path):", "function_name": "count_words_in_file", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def aggregate_word_counts(file_paths):", "function_name": "aggregate_word_count...
[ 1, 1, 0, 1, 1, 0, 1, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nfrom collections import defaultdict\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import Dict, List\n\ndef count_words_in_file(file_path: s...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00043405", "row_id": 43405, "seed_ids": "[206]" }
0.69159
Docs: Python310_43405
I
[ "count_words_in_file", "aggregate_word_counts" ]
2
[ [ "aggregate_word_counts", "count_words_in_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
02eb4e97fab4b3f8cc21b43a92aad4552f1c3d38
b61931a70a85d2b6e66a0cfe2f12bb69c40b5acd
v1.0
instruct
Docs
Docs: Python310_43517_I
### Turtle Graphics Challenge In this challenge, you will create a simulation using the turtle graphics module. The objective is to simulate a simple drawing application that allows for the drawing of shapes based on user inputs. #### Objectives: 1. **Create a Function to Draw Shapes** - Implement a function `draw...
import turtle def draw_shape(turtle_obj, shape, size, color='black'): """ Draws a specified shape with the given size and color. Parameters: turtle_obj (Turtle): The turtle object. shape (str): The shape to draw ('square', 'triangle', 'circle'). size (int): The size of the shape. color...
from unittest.mock import MagicMock, patch import turtle @patch('turtle.Turtle') def test_draw_shape_square(mock_turtle): turtle_obj = mock_turtle() draw_shape(turtle_obj, 'square', 100) assert turtle_obj.forward.call_count == 4 assert turtle_obj.right.call_count == 4 @patch('turtle.Turtle') def test_...
[ { "docstring": "Draws a specified shape with the given size and color.\n\nParameters:\nturtle_obj (Turtle): The turtle object.\nshape (str): The shape to draw ('square', 'triangle', 'circle').\nsize (int): The size of the shape.\ncolor (str): The color of the shape.", "function_declaration": "def draw_shape...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import turtle\n\ndef draw_shape(turtle_obj, shape, size, color='black'):\n \"\"\"\n Draws a shape with the given turtle object.\n \n Parameters:\n - turt...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00043517", "row_id": 43517, "seed_ids": "[179]" }
0.724391
Docs: Python310_43517
I
[ "draw_shape", "move_up", "move_down", "move_left", "move_right", "run_drawing_app" ]
6
[ [ "run_drawing_app", "draw_shape" ], [ "run_drawing_app", "move_down" ], [ "run_drawing_app", "move_left" ], [ "run_drawing_app", "move_right" ], [ "run_drawing_app", "move_up" ] ]
5
[]
false
[]
false
pytest
false
[]
true
9c8b7c66528c3487a1a42908519668210cd3e7e0
37dde0a9c1b2a19bb40edef49c76096ae91fcd29
v1.0
instruct
Docs
Docs: Scikit_43557_I
LDA and QDA Classifiers Implementation and Evaluation #### Context You are provided with a dataset containing several features and a target label representing different classes. Your task is to utilize the Linear Discriminant Analysis (LDA) and Quadratic Discriminant Analysis (QDA) classifiers from scikit-learn to ana...
import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis from sklearn.metrics import accuracy_score def load_and_split_data(): # Load the Iris dataset and split ...
import pytest from solution import load_and_split_data, evaluate_lda_solver, evaluate_qda def test_load_and_split_data(): X_train, X_test, y_train, y_test = load_and_split_data() assert X_train.shape == (120, 4) assert X_test.shape == (30, 4) assert len(y_train) == 120 assert len(y_test) == 30 def...
[ { "docstring": null, "function_declaration": "def load_and_split_data():", "function_name": "load_and_split_data", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def evaluate_lda_solver(solver, shrinkage=None):", "function_name": "evaluate_lda_solver", "p...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.discriminant_analysis import LinearDiscri...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00043557", "row_id": 43557, "seed_ids": "[46]" }
0.45287
Docs: Scikit_43557
I
[ "load_and_split_data", "evaluate_lda_solver", "evaluate_qda", "main" ]
4
[ [ "evaluate_lda_solver", "load_and_split_data" ], [ "evaluate_qda", "load_and_split_data" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
54ea8df7df1b3d1e32d7e7956edbe67e81ff15ca
29d4d914a4e7ad8c250af72e7aedf74bf73acfc4
v1.0
instruct
Docs
Docs: Python310_43560_I
### Advanced Date and Time Calculation Task **Problem Statement:** You have been given a CSV file named `events.csv` which contains log data of various events. Each row in the CSV file contains an event ID, a timestamp, and the event's duration in seconds. Your task is to process this data and generate an output CSV ...
import csv from datetime import datetime, timedelta import pytz def parse_duration(seconds): """Convert duration in seconds to 'H hours, M minutes, S seconds'.""" hours, remainder = divmod(seconds, 3600) minutes, seconds = divmod(remainder, 60) duration_str = f"{hours} hours, {minutes} minutes, {second...
import csv import os from solution import process_event_logs def setup_module(module): # Setup a sample events.csv data = [ ['event_id', 'timestamp', 'duration'], ['1', '2023-04-05T14:30:00Z', '3600'], ['2', '2023-04-05T15:00:00Z', '5400'], ] with open('events.csv', 'w', newline...
[ { "docstring": "Convert duration in seconds to 'H hours, M minutes, S seconds'.", "function_declaration": "def parse_duration(seconds):", "function_name": "parse_duration", "parameter_list": "(seconds)" }, { "docstring": null, "function_declaration": "def process_event_logs(time_zone):",...
[ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\nfrom datetime import datetime, timedelta\nimport pytz\n\ndef process_event_logs(time_zone: str) -> None:\n # Define the timezone\n target_timezone = p...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00043560", "row_id": 43560, "seed_ids": "[219]" }
0.617776
Docs: Python310_43560
I
[ "parse_duration", "process_event_logs" ]
2
[ [ "process_event_logs", "parse_duration" ] ]
1
[]
false
[]
false
pytest
true
[ "pytz" ]
false
1287d4a112e9321cb83228a697fa6337c43da588
38cf90108c9eb8cf9ca7dbfa729517bacb0cffb6
v1.0
instruct
Docs
Docs: Python310_43566_I
#### Objective Create a simple WSGI application using the `wsgiref` package and implement utilities for environment manipulation and validation. #### Problem Statement Write a WSGI application that serves a "Hello World" message and logs the request URI and headers. Implement a function to manipulate the WSGI environm...
from wsgiref.simple_server import make_server from wsgiref.util import request_uri, shift_path_info, setup_testing_defaults from wsgiref.validate import validator def manipulate_environment(environ): # Manipulate the environment by shifting PATH_INFO to SCRIPT_NAME shifted_path = shift_path_info(environ) p...
import pytest from wsgiref.validate import validator from wsgiref.util import setup_testing_defaults from solution import manipulate_environment, hello_app def test_manipulate_environment(): environ = { 'SCRIPT_NAME': '/app', 'PATH_INFO': '/test/path' } setup_testing_defaults(environ) o...
[ { "docstring": null, "function_declaration": "def manipulate_environment(environ):", "function_name": "manipulate_environment", "parameter_list": "(environ)" }, { "docstring": null, "function_declaration": "def hello_app(environ, start_response):", "function_name": "hello_app", "...
[ 1, 0, 1, 0, 1, 0, 0, 1, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from wsgiref.simple_server import make_server\nfrom wsgiref.util import request_uri, shift_path_info, setup_testing_defaults\nfrom wsgiref.validate import validator\n\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043566", "row_id": 43566, "seed_ids": "[210]" }
0.484105
Docs: Python310_43566
I
[ "manipulate_environment", "hello_app" ]
2
[ [ "hello_app", "manipulate_environment" ] ]
1
[]
false
[]
false
pytest
true
[]
true
74a453c3b63342e499706c7299d35ae6419c5aca
bf178fd1f816bdf52d4c7b7e5cf296fba1d8a212
v1.0
instruct
Docs
Docs: Python310_43591_I
### Question: Multi-Stage Task Execution using `asyncio` **Objective**: Implement a Python function that simulates a multi-stage task execution system using the `asyncio` module. **Problem Statement**: You need to design a system that performs the following tasks concurrently: 1. Fetching data from multiple sources. ...
import asyncio import aiohttp import logging from typing import List, Callable # Configure logging logging.basicConfig(level=logging.ERROR) logger = logging.getLogger(__name__) async def fetch_data(session, url): """ Fetch data from a single URL. """ try: async with session.get(url, timeout=10...
import pytest import asyncio from unittest.mock import patch, AsyncMock # Assuming previous solution code is accessible and imported here from solution import multi_stage_task, fetch_data, example_process_data, example_save_data @pytest.mark.asyncio async def test_multi_stage_task(): # Mock URLs sources = ["h...
[]
[ 0, 1, 1, 1, 1, 1, 1, 0, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nimport logging\n\nasync def fetch_data(session, url):\n try:\n async with session.get(url) as response:\n response....
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00043591", "row_id": 43591, "seed_ids": "[360]" }
0.52075
Docs: Python310_43591
I
[ "fetch_data", "multi_stage_task", "example_process_data", "example_save_data" ]
4
[ [ "multi_stage_task", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
c96b2f81227f9e76cc9ba3a50ebf9ed766c53e55
fdd36597926fc51a6a53757f95b7006cd3dec6c4
v1.0
instruct
Docs
Docs: Pytorch_43677_I
#### Objective: Your task is to demonstrate your understanding of the PyTorch compiler functionality by optimizing a given neural network model using the `torch.compiler` module. You will need to write functions that compile the model, handle its execution, and optimize it based on the compiler features provided in the...
import torch import torch.nn as nn import torch.optim as optim import time class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.fc1 = nn.Linear(784, 128) self.relu = nn.ReLU() self.fc2 = nn.Linear(128, 10) def forward(self, x): ...
import pytest import torch from solution import SimpleModel, compile_model, optimize_model, execute_and_measure def test_compile_model(): model = SimpleModel() compiled_model = compile_model(model) assert compiled_model is not None def test_optimize_model(): model = SimpleModel() compiled_model = ...
[]
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport time\n\nclass SimpleModel(nn.Module):\n def __init__(self):\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00043677", "row_id": 43677, "seed_ids": "[88]" }
0.55609
Docs: Pytorch_43677
I
[ "compile_model", "optimize_model", "execute_and_measure" ]
3
[ [ "execute_and_measure", "compile_model" ], [ "execute_and_measure", "optimize_model" ] ]
2
[]
false
[ "SimpleModel" ]
true
pytest
true
[ "torch" ]
false
9aa0db9d82ca24c32d2fef7a14d08fd56c8a85b4
39a8f26e6d96a36d28c3844fb767d496cd900436
v1.0
instruct
Docs
Docs: Python310_43713_I
**Objective**: Evaluate the student's understanding of function implementation, pattern matching (new in Python 3.10), and exception handling. ### Problem Statement You are required to implement a Python function named `process_data` that takes a list of dictionaries as input. Each dictionary represents a record of a...
def process_electronics(details: str) -> str: return f"Processed Electronics: {details}" def process_clothing(details: str) -> str: return f"Processed Clothing: {details}" def process_data(data: list[dict]) -> dict: result = {} for record in data: try: category = record["categ...
from solution import process_data, process_electronics, process_clothing def test_process_electronics(): assert process_electronics("Smartphone with 4GB RAM") == "Processed Electronics: Smartphone with 4GB RAM" def test_process_clothing(): assert process_clothing("Cotton t-shirt, size L") == "Processed Clothi...
[ { "docstring": null, "function_declaration": "def process_electronics(details):", "function_name": "process_electronics", "parameter_list": "(details)" }, { "docstring": null, "function_declaration": "def process_clothing(details):", "function_name": "process_clothing", "paramete...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def process_electronics(details: str) -> str:\n return f\"Processed Electronics: {details}\"\n\ndef process_clothing(details: str) -> str:\n return f\"Processed C...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00043713", "row_id": 43713, "seed_ids": "[96]" }
0.594395
Docs: Python310_43713
I
[ "process_electronics", "process_clothing", "process_data" ]
3
[ [ "process_data", "process_clothing" ], [ "process_data", "process_electronics" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
3c3c2220c43aac938790a03e2f290a05b2bd4cb2
f8b17605bc9dde58badfbbd31f7ffbf3a2e16ffc
v1.0
instruct
Docs
Docs: Python310_43742_I
**Programming Task: Implement an Asynchronous Data Pipeline Using asyncio Futures** ### Objective You are required to implement an asynchronous data processing pipeline using asyncio.Future objects. The pipeline consists of three stages: 1. **Data Fetching**: Simulate fetching data asynchronously. 2. **Data Processing...
import asyncio async def fetch_data(data_id: int) -> asyncio.Future: """ Simulate fetching data asynchronously by sleeping for 0.5 seconds and then setting a result with a specific format. """ await asyncio.sleep(0.5) future = asyncio.Future() future.set_result(f"data_{data_id}") return fut...
import asyncio import pytest from solution import fetch_data, process_data, aggregate_results, execute_pipeline @pytest.mark.asyncio async def test_fetch_data(): result = await fetch_data(1) assert result.result() == "data_1" @pytest.mark.asyncio async def test_process_data(): fetch_future = await fetch_d...
[]
[ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def fetch_data(data_id: int) -> asyncio.Future:\n future = asyncio.Future()\n await asyncio.sleep(0.5)\n future.set_result(f\"data_{dat...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00043742", "row_id": 43742, "seed_ids": "[113]" }
0.385775
Docs: Python310_43742
I
[ "fetch_data", "process_data", "aggregate_results", "execute_pipeline" ]
4
[ [ "execute_pipeline", "aggregate_results" ], [ "execute_pipeline", "fetch_data" ], [ "execute_pipeline", "process_data" ] ]
3
[ "process_data" ]
false
[]
false
pytest
true
[]
true
263d3b09ae96ce911efe8ca8298855ebe962c943
e5e3229ddbbd003396519276f9d62bd168f7e26f
v1.0
instruct
Docs
Docs: Python310_43777_I
#### Objective Implement a simple text editor using the `curses` library in Python. Your editor should support basic operations such as text input, cursor movement, and saving the content to a file. #### Requirements **Function:** `text_editor` **Input:** - The function does not take any inputs directly. **Output:...
import curses def text_editor(stdscr): curses.curs_set(1) # Show cursor stdscr.clear() text = [[]] cursor_y, cursor_x = 0, 0 while True: stdscr.clear() for i, line in enumerate(text): stdscr.addstr(i, 0, ''.join(line)) stdscr.move(cursor_y, cursor_x) st...
import pytest import os def test_save_file(): text = [['H','e','l','l','o'], ['W','o','r','l','d']] save_to_file(text) with open('output.txt', 'r') as f: lines = f.readlines() assert lines == ['Hello\n', 'World\n'] def test_save_empty_file(): text = [[]] save_to_file(text) with ope...
[ { "docstring": null, "function_declaration": "def text_editor(stdscr):", "function_name": "text_editor", "parameter_list": "(stdscr)" }, { "docstring": null, "function_declaration": "def save_to_file(text):", "function_name": "save_to_file", "parameter_list": "(text)" } ]
[ 1, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import curses\n\ndef text_editor(stdscr):\n curses.curs_set(1) # Show cursor\n stdscr.clear()\n text = [[]]\n cursor_y, cursor_x = 0, 0\n\n while True:\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00043777", "row_id": 43777, "seed_ids": "[294]" }
0.417589
Docs: Python310_43777
I
[ "text_editor", "save_to_file" ]
2
[ [ "text_editor", "save_to_file" ] ]
1
[]
false
[]
false
pytest
false
[]
true
d95a5a1eb88d42fc3d36f5e8eee1e96b7988c7c3
abbf4ee746797c4d84ffb7aca83f5ffb1363d4ce
v1.0
instruct
Docs
Docs: Python310_43802_I
### Asyncio Advanced Application You are tasked with implementing a small application that demonstrates your understanding of the asyncio package, including proper handling of asynchronous tasks, debugging practices, and managing concurrency. **Requirements:** 1. **Data Fetching Coroutine:** Implement an asynchro...
import asyncio import concurrent.futures import logging from typing import List # Set up logging configuration. logging.basicConfig(level=logging.WARNING) # Debug mode for asyncio. asyncio.get_event_loop().set_debug(True) async def fetch_data(id: int) -> int: if id == 0: raise RuntimeError("Simulated fet...
import asyncio import logging import pytest from solution import fetch_data, process_data, main @pytest.mark.asyncio async def test_fetch_data(): assert await fetch_data(1) == 1 assert await fetch_data(2) == 4 assert await fetch_data(3) == 9 with pytest.raises(RuntimeError, match="Simulated fetch ...
[ { "docstring": null, "function_declaration": "def main(n):", "function_name": "main", "parameter_list": "(n)" } ]
[ 1, 0, 1, 1, 0, 1, 0, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport concurrent.futures\nimport logging\nfrom typing import List\n\n# Set up logging configuration.\nlogging.basicConfig(level=logging.WARNING)\n\n# D...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00043802", "row_id": 43802, "seed_ids": "[200]" }
0.491819
Docs: Python310_43802
I
[ "fetch_data", "process_data", "fetch_data_with_handling", "main" ]
4
[ [ "fetch_data_with_handling", "fetch_data" ], [ "process_data", "fetch_data_with_handling" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
c7207d25552e2b185c7ca2d60a215b3e342142f9
944c898d680ce6ccd37cd5f3dc965fe55c28f393
v1.0
instruct
Docs
Docs: Python310_43889_I
**Question: Platform-Specific Asyncio Implementation** You are tasked with implementing an asynchronous TCP server in Python 3.10 using the asyncio package. Your server should handle client connections and process data sent by clients asynchronously. However, you must account for platform-specific constraints, particu...
import asyncio import platform async def start_server(host: str, port: int): server = await asyncio.start_server(handle_client, host, port) async with server: await server.serve_forever() async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): data = await reader.read(...
# We'll create a custom test fixture to run the server in the background. # Please note that testing asyncio network code often requires a bit more # setup and teardown procedure. import asyncio import pytest import socket import aiohttp from solution import start_server, handle_client @pytest.fixture async def serv...
[]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\n\nasync def start_server(host: str, port: int):\n \"\"\"\n Starts an asynchronous TCP server that listens on the specified host a...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00043889", "row_id": 43889, "seed_ids": "[370]" }
0.552642
Docs: Python310_43889
I
[ "start_server", "handle_client" ]
2
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
085acd9284b4c4d093ed470cce27c4e278276837
2c2ed78afae8f55736b9c592441f945dfe96348d
v1.0
instruct
Docs
Docs: Pytorch_43903_I
#### Objective You are required to demonstrate your understanding of asynchronous execution using PyTorch's `torch.futures` package by designing a function that processes a list of data items concurrently. #### Task Implement a function named `process_data_concurrently` that processes a list of data items in parallel ...
import torch from typing import List def async_square(n: int) -> torch.futures.Future: """ Asynchronously computes the square of a number. """ future = torch.futures.Future() future.set_result(n ** 2) return future def process_data_concurrently(data: List[int]) -> List[int]: """ Proces...
from solution import process_data_concurrently def test_process_data_concurrently(): assert process_data_concurrently([1, 2, 3, 4]) == [1, 4, 9, 16] assert process_data_concurrently([0, 5, 10, 15]) == [0, 25, 100, 225] assert process_data_concurrently([10**6]) == [10**12] assert process_data_concurrent...
[ { "docstring": "Asynchronously computes the square of a number.", "function_declaration": "def async_square(n):", "function_name": "async_square", "parameter_list": "(n)" }, { "docstring": "Process a list of data items concurrently using torch.futures.Future.\nEach integer in the list is squ...
[ 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.futures import Future\nfrom typing import List\n\ndef process_data_concurrently(data: List[int]) -> List[int]:\n \"\"\"\n Processes a lis...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00043903", "row_id": 43903, "seed_ids": "[53]" }
0.48874
Docs: Pytorch_43903
I
[ "async_square", "process_data_concurrently" ]
2
[ [ "process_data_concurrently", "async_square" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
7140ad4a4d4e91ce0fa49869b82d58ddd0fc26fb
f28dadfd7b16a0b18916631fad5dccc892b94006