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_47307_I | **Coding Assessment Question: Tracing Function Execution and Generating Coverage Report**
### Objective
Demonstrate your comprehension of the `trace` module by writing Python code that traces the execution of a given function, analyzes the coverage, and generates a detailed report.
### Problem Statement
You are provi... | import sys
import trace
def process_data(data):
processed_data = []
for num in data:
if num % 2 == 0:
processed_data.append(num * 2)
else:
processed_data.append(num + 1)
return processed_data
def trace_process_data(data):
# Create a Trace object
tracer = tra... | import os
from solution import process_data, trace_process_data
def test_process_data_even_numbers():
assert process_data([2, 4, 6]) == [4, 8, 12]
def test_process_data_odd_numbers():
assert process_data([1, 3, 5]) == [2, 4, 6]
def test_process_data_mixed_numbers():
assert process_data([1, 2, 3, 4, 5]) =... | [
{
"docstring": null,
"function_declaration": "def process_data(data):",
"function_name": "process_data",
"parameter_list": "(data)"
},
{
"docstring": null,
"function_declaration": "def trace_process_data(data):",
"function_name": "trace_process_data",
"parameter_list": "(data)"
... | [
0,
0,
1,
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 sys\nimport trace\n\ndef process_data(data):\n processed_data = []\n for num in data:\n if num % 2 == 0:\n processed_data.append(num * 2)... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00047307",
"row_id": 47307,
"seed_ids": "[187]"
} | 0.503666 | Docs: Python310_47307 | I | [
"process_data",
"trace_process_data"
] | 2 | [
[
"trace_process_data",
"process_data"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | d5110821f1cb97b1c3ebbfaf936cd6c6fa885747 | 8628669967d558706c5ab102144aec9e9f071136 | |||
v1.0 | instruct | Docs | Docs: Python310_47329_I | ## Question: Implementing Asynchronous Tasks with asyncio
### Objective
The goal of this question is to assess your understanding and ability to implement asynchronous tasks using asyncio’s concurrent programming capabilities.
### Task
You need to implement a function `fetch_data_concurrently(urls: List[str]) -> List... | from typing import List
import asyncio
import aiohttp
async def fetch(url: str) -> str:
"""
Asynchronously fetches the content from the given URL. If an error occurs, returns an empty string.
"""
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp... | import asyncio
from solution import fetch_data_concurrently
def test_fetch_data_concurrently():
# Testing with some local test URLs
urls = [
'http://example.com', # Valid URL
'https://jsonplaceholder.typicode.com/posts/1', # Valid URL
'https://invalidurl.org' # Inva... | [] | [
1,
1,
1,
0,
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": "from typing import List\nimport asyncio\nimport aiohttp\n\nasync def fetch(url: str) -> str:\n \"\"\"\n Fetches the content from the given URL asynchronously.\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00047329",
"row_id": 47329,
"seed_ids": "[270]"
} | 0.516316 | Docs: Python310_47329 | I | [
"fetch",
"fetch_data_concurrently"
] | 2 | [
[
"fetch_data_concurrently",
"fetch"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | c62f89c4167a04a1741f8120f1b35729aac31ad4 | af25ca2b4672b1474147adb4da652924e8d2424f | |||
v1.0 | instruct | Docs | Docs: Python310_47351_I | **Objective**: Demonstrate your understanding of Python's runtime services, specifically focusing on `dataclasses` and `contextlib`. You will need to create a robust context-driven data management system using these modules.
**Problem Statement**:
You are tasked with implementing a data management system that tracks t... | from dataclasses import dataclass
from contextlib import contextmanager
import time
@dataclass
class Task:
id: int
name: str
start_time: float
end_time: float
status: str
@contextmanager
def TaskManager(task):
try:
task.start_time = time.time()
yield
task.status = 'Succ... | from solution import perform_task, Task
import time
def sample_task(duration):
time.sleep(duration)
def failing_task():
raise ValueError("This task failed")
def test_perform_task_success():
task = perform_task(1, "SleepTask", sample_task, 1)
assert task.id == 1
assert task.name == "SleepTask"
... | [] | [
1,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from dataclasses import dataclass\nfrom contextlib import contextmanager\nimport time\n\n@dataclass\nclass Task:\n id: int\n name: str\n start_time: float\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00047351",
"row_id": 47351,
"seed_ids": "[146]"
} | 0.49524 | Docs: Python310_47351 | I | [
"TaskManager",
"perform_task"
] | 2 | [
[
"perform_task",
"TaskManager"
]
] | 1 | [] | false | [
"Task"
] | true | pytest | true | [] | true | 5c5b5e97737e103c406846e87d442a631d5ce79d | 08d52d8dcaa57c6f929953b00ab81a177314a8cf | |||
v1.0 | instruct | Docs | Docs: Python310_47356_I | **Coding Assessment Question: Advanced Python Initialization**
In this task, you will implement a function that initializes Python with customized configurations using the `PyConfig` and `PyPreConfig` structures. This function will:
1. Preinitialize Python using the isolated configuration.
2. Initialize Python from a... | import sys
import ctypes
# Define placeholders for PyConfig and PyPreConfig analogous to what would be used in the C API.
class PyPreConfig(ctypes.Structure):
_fields_ = [('isolated', ctypes.c_int)]
class PyConfig(ctypes.Structure):
_fields_ = [('isolated', ctypes.c_int)]
# Define placeholder functions to si... | def test_init_custom_python_no_args():
init_custom_python(0, [])
# Possible checks:
# Since this should just initialize with no arguments,
# we could check the initialization status via a global flag if implemented in actual code.
def test_init_custom_python_simple_cmd():
init_custom_python(3, ["pr... | [] | [
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 sys\nfrom _testinternalcapi import _Py_PreInitializeFromPyPreConfig, _Py_InitializeFromPyConfig, PyPreConfig, PyConfig, PyStatus_Exception, Py_ExitStatusExceptio... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00047356",
"row_id": 47356,
"seed_ids": "[15]"
} | 0.516914 | Docs: Python310_47356 | I | [
"PyPreConfig_InitIsolated",
"PyConfig_InitIsolated",
"PyConfig_SetBytesArgv",
"Py_InitializeFromConfig",
"PyConfig_Clear",
"PyPreConfig_Clear",
"PyStatus_Exception",
"Py_ExitStatusException",
"init_custom_python"
] | 9 | [
[
"init_custom_python",
"PyConfig_Clear"
],
[
"init_custom_python",
"PyConfig_InitIsolated"
],
[
"init_custom_python",
"PyConfig_SetBytesArgv"
],
[
"init_custom_python",
"PyPreConfig_Clear"
],
[
"init_custom_python",
"PyPreConfig_InitIsolated"
],
[
"in... | 8 | [] | false | [
"PyPreConfig",
"PyConfig"
] | true | pytest | false | [] | true | 44099eb9629508f143cbf05a7feb6b3c81e76fdd | 2e230bc698d46a3498fbff09b51408682a654043 | |||
v1.0 | instruct | Docs | Docs: Python310_47399_I | #### Objective:
Demonstrate your understanding of concurrent execution in Python using the `concurrent.futures` module.
#### Problem Statement:
You are tasked with designing a function that computes the sum of all prime numbers up to a given number `N` by distributing the workload across multiple threads or processes ... | import concurrent.futures
from math import isqrt
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return Tr... | import pytest
from solution import sum_primes_threadpool, sum_primes_processpool
def test_sum_primes_threadpool_small():
assert sum_primes_threadpool(10, 2) == 17 # 2 + 3 + 5 + 7
def test_sum_primes_processpool_small():
assert sum_primes_processpool(10, 2) == 17 # 2 + 3 + 5 + 7
def test_sum_primes_threadpo... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def sum_primes_in_range(start, end):",
"function_name": "sum_primes_in_range",
"parameter_list": "(start, end)"
... | [
1,
0,
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 concurrent.futures\nfrom math import isqrt\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00047399",
"row_id": 47399,
"seed_ids": "[206]"
} | 0.573938 | Docs: Python310_47399 | I | [
"is_prime",
"sum_primes_in_range",
"sum_primes_threadpool",
"sum_primes_processpool"
] | 4 | [
[
"sum_primes_in_range",
"is_prime"
],
[
"sum_primes_processpool",
"sum_primes_in_range"
],
[
"sum_primes_threadpool",
"sum_primes_in_range"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 4764af903d9d0432743e98521b15163428164560 | 1fb52d2961356a476e1243830d4e389927c29a2d | |||
v1.0 | instruct | Docs | Docs: Python310_47436_I | You are tasked with profiling a piece of Python code to identify performance bottlenecks and optimize its runtime. Given a list of integers, the code performs multiple operations, including sorting, calculating the sum, and finding the max value. Your job is to:
1. Implement a function `perform_operations` which takes... | from typing import List, Tuple
def perform_operations(numbers: List[int]) -> Tuple[List[int], int, int]:
# Perform required operations
sorted_numbers = sorted(numbers)
total_sum = sum(numbers)
max_value = max(numbers)
return sorted_numbers, total_sum, max_value
# Profiling the function
import cPro... | from solution import perform_operations
def test_sorted_list():
assert perform_operations([3, 1, 2])[0] == [1, 2, 3]
def test_sum():
assert perform_operations([3, 1, 2])[1] == 6
def test_max_value():
assert perform_operations([3, 1, 2])[2] == 3
def test_large_list():
import random
numbers = ran... | [
{
"docstring": null,
"function_declaration": "def perform_operations(numbers):",
"function_name": "perform_operations",
"parameter_list": "(numbers)"
},
{
"docstring": null,
"function_declaration": "def profile_code():",
"function_name": "profile_code",
"parameter_list": "()"
}... | [
1,
1,
1,
0,
1,
1,
0,
0,
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, Tuple\n\ndef perform_operations(numbers: List[int]) -> Tuple[List[int], int, int]:\n sorted_numbers = sorted(numbers)\n total_sum = sum(n... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00047436",
"row_id": 47436,
"seed_ids": "[142]"
} | 0.507935 | Docs: Python310_47436 | I | [
"perform_operations",
"profile_code"
] | 2 | [
[
"profile_code",
"perform_operations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3634d5b706ea645bb660f36a03826083d276083e | 53f2e75fd277861ced2d2c70defbfad91d45e797 | |||
v1.0 | instruct | Docs | Docs: Python310_47481_I | Your task is to implement a Python function that takes a directory path as input and performs the following:
1. Lists all the Python files (.py) in the directory and its subdirectories.
2. For each identified Python file, retrieve and print its configuration information using the "sysconfig" module.
3. Inspect and pri... | import os
import sysconfig
import inspect
from dataclasses import dataclass
from contextlib import contextmanager
@dataclass
class PythonFileInfo:
filename: str
size: int
config_info: dict
@contextmanager
def open_file(file_path):
try:
file = open(file_path, 'r')
yield file
except ... | from solution import list_python_files, get_file_info, process_directory, open_file, PythonFileInfo
import os
def create_test_files(test_dir):
os.makedirs(test_dir, exist_ok=True)
file_paths = []
with open(os.path.join(test_dir, 'test1.py'), 'w') as f:
f.write("def test_func(): pass\n")
with o... | [] | [
0,
1,
1,
1,
0,
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 os\nimport sysconfig\nimport inspect\nfrom dataclasses import dataclass\nfrom contextlib import contextmanager\n\n@dataclass\nclass PythonFileInfo:\n filename... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00047481",
"row_id": 47481,
"seed_ids": "[146]"
} | 0.580541 | Docs: Python310_47481 | I | [
"open_file",
"list_python_files",
"get_file_info",
"process_directory"
] | 4 | [
[
"get_file_info",
"open_file"
],
[
"process_directory",
"get_file_info"
],
[
"process_directory",
"list_python_files"
]
] | 3 | [] | false | [
"PythonFileInfo"
] | true | pytest | true | [] | true | 8d43a997aca72af50ba0e897a384215210e9c88c | 59df6bead4f8456c8be0277eb8cfb62dc66297d4 | |||
v1.0 | instruct | Docs | Docs: Python310_47493_I | Context Management in Asynchronous Programming
#### Objective
In this assessment, you are required to demonstrate your understanding of the `contextvars` module in Python. Specifically, you will write a function that makes use of `ContextVar` to manage context-local state in an asynchronous environment.
#### Problem ... | import asyncio
import contextvars
# Create logging_level ContextVar
logging_level = contextvars.ContextVar('logging_level', default="INFO")
def set_logging_level(level: str) -> None:
logging_level.set(level)
def get_logging_level() -> str:
return logging_level.get()
async def process_request(request_id: int... | import asyncio
import pytest
from contextvars import ContextVar
import contextvars
# Import functions from the solution
from solution import set_logging_level, get_logging_level, process_request, logging_level
@pytest.mark.asyncio
async def test_set_get_logging_level():
set_logging_level("DEBUG")
assert get_l... | [
{
"docstring": null,
"function_declaration": "def set_logging_level(level):",
"function_name": "set_logging_level",
"parameter_list": "(level)"
},
{
"docstring": null,
"function_declaration": "def get_logging_level():",
"function_name": "get_logging_level",
"parameter_list": "()"... | [
0,
1,
0,
1,
0,
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": "import asyncio\nimport contextvars\n\n# Create logging_level ContextVar\nlogging_level = contextvars.ContextVar('logging_level', default=\"INFO\")\n\ndef set_logging_le... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00047493",
"row_id": 47493,
"seed_ids": "[392]"
} | 0.518764 | Docs: Python310_47493 | I | [
"set_logging_level",
"get_logging_level",
"process_request",
"main"
] | 4 | [
[
"process_request",
"get_logging_level"
],
[
"process_request",
"set_logging_level"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5135487900cbd65b169b6fd9ce1b1be1803a5832 | 1334168fd4dad445a79ed92c68fe628303b14401 | |||
v1.0 | instruct | Docs | Docs: Python310_47547_I | #### Background
You are a data scientist working with large text files. To save disk space and transfer files more efficiently, you need to compress these files using the `bz2` library provided in Python. You also need to ensure that the compressed files can be decompressed back to their original state without losing ... | import bz2
import os
from typing import List, Dict
def compress_file(input_file: str, output_file: str) -> None:
"""
Compress a text file using bz2.
"""
with open(input_file, 'rb') as f_in, bz2.open(output_file, 'wb', compresslevel=9) as f_out:
for line in f_in:
f_out.write(line)
d... | import os
import pytest
from solution import verify_and_compress_files
@pytest.fixture
def setup_test_files(tmp_path):
"""
Creates a temporary directory with text files for testing.
"""
filenames = ['file1.txt', 'file2.txt', 'file3.txt']
contents = ['Hello World!', 'Goodbye World!', 'Another file w... | [
{
"docstring": "Compress a text file using bz2.",
"function_declaration": "def compress_file(input_file, output_file):",
"function_name": "compress_file",
"parameter_list": "(input_file, output_file)"
},
{
"docstring": "Decompress a bz2 file to a text file.",
"function_declaration": "def... | [
1,
1,
0,
0,
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 bz2\nimport os\nfrom typing import Dict\n\ndef verify_and_compress_files(directory: str) -> Dict[str, bool]:\n result = {}\n \n def compress_file(file_p... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00047547",
"row_id": 47547,
"seed_ids": "[221]"
} | 0.664058 | Docs: Python310_47547 | I | [
"compress_file",
"decompress_file",
"verify_and_compress_files"
] | 3 | [
[
"verify_and_compress_files",
"compress_file"
],
[
"verify_and_compress_files",
"decompress_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | de4fdb14e2bad17af431001b3d2759d506636101 | fa0bbe84a40c3c05297df9331a898532c8646a5a | |||
v1.0 | instruct | Docs | Docs: Python310_47548_I | ### Concurrent Execution in Python Using `concurrent.futures`
#### Objective:
To assess your understanding and ability to implement concurrent task execution in Python using the `concurrent.futures` module.
#### Problem Statement:
You are required to write a Python function to simulate a computational task that calc... | from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from typing import List, Union
def fibonacci(n: int) -> int:
if n <= 1:
return n
a, b = 0, 1
for _ in range(2, n+1):
a, b = b, a + b
return b
def compute_fibonacci_concurrently(numbers: List[int], method: str) -> Li... | from solution import compute_fibonacci_concurrently
def test_fibonacci_thread():
numbers = [0, 1, 2, 3, 4, 5, 10]
expected = [0, 1, 1, 2, 3, 5, 55]
assert compute_fibonacci_concurrently(numbers, 'thread') == expected
def test_fibonacci_process():
numbers = [6, 7, 8, 9, 10]
expected = [8, 13, 2... | [] | [
0,
0,
0,
1,
1,
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": "from typing import List\nimport concurrent.futures\n\ndef fibonacci(n: int) -> int:\n if n == 0: return 0\n elif n == 1: return 1\n a, b = 0, 1\n for _ in r... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00047548",
"row_id": 47548,
"seed_ids": "[206]"
} | 0.604686 | Docs: Python310_47548 | I | [
"fibonacci",
"compute_fibonacci_concurrently"
] | 2 | [
[
"compute_fibonacci_concurrently",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6823fc800cbfd357785669d56af3537316bc7b61 | 50aa14225c1a14e5a5bc1191ddf14110b0594018 | |||
v1.0 | instruct | Docs | Docs: Python310_47560_I | ### Problem: Efficient Data Processing with Caching and Function Dispatch
#### Background
In this task, you are required to implement a function that processes data efficiently using caching for repetitive computations and single-dispatch for handling different types of data structures. You will use functionalities fr... | import functools
@functools.lru_cache(maxsize=128)
def compute_factorial(n: int) -> int:
"""
Compute the factorial of a number using recursion.
Cache the results for efficiency.
:param n: Integer whose factorial is to be computed.
:return: Factorial of the input number.
"""
if n < 2:
... | from solution import process_data
def test_process_data_with_integer():
assert process_data(5) == 120 # 5! = 120
def test_process_data_with_list():
assert process_data([1, 2, 3, 4, 5]) == [1, 2, 6, 24, 120] # Factorials of 1, 2, 3, 4, 5
def test_process_data_with_dict():
assert process_data({'a': 3, 'b... | [
{
"docstring": "Compute the factorial of a number using recursion.\nCache the results for efficiency.\n\n:param n: Integer whose factorial is to be computed.\n:return: Factorial of the input number.",
"function_declaration": "def compute_factorial(n):",
"function_name": "compute_factorial",
"paramet... | [
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": "import functools\n\n@functools.lru_cache(maxsize=128)\ndef compute_factorial(n: int) -> int:\n \"\"\"\n Compute the factorial of a number using recursion.\n Ca... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00047560",
"row_id": 47560,
"seed_ids": "[236]"
} | 0.554321 | Docs: Python310_47560 | I | [
"compute_factorial",
"process_data",
"_",
"_",
"_"
] | 5 | [
[
"_",
"compute_factorial"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 645e9b093833edc894f74065e685d4384cf6bfb1 | 066054489773cb4e096279b2c88c0290dbf55a2a | |||
v1.0 | instruct | Docs | Docs: Pytorch_47566_I | **Objective:**
The goal of this coding assessment is to test your understanding of tensor initialization methods in PyTorch and their application in neural network models.
**Problem Statement:**
You are tasked with designing a neural network for classifying images from the CIFAR-10 dataset. To improve the network's p... | import torch
import torch.nn as nn
import torch.nn.init as init
def custom_weight_init(model):
"""
Initializes the weights of the model's layers using specific initialization strategies:
- Xavier Uniform initialization for convolutional layers.
- Kaiming Normal initialization for fully connected layers... | import torch.nn as nn
from solution import custom_weight_init, define_cnn_model
def test_custom_weight_init():
model = define_cnn_model()
for layer in model.modules():
if isinstance(layer, nn.Conv2d):
assert layer.weight.data.mean().abs() < 0.1, "Xavier Uniform initialization may have ... | [] | [
1,
1,
1,
0,
0,
1,
1,
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 torch\nimport torch.nn as nn\nimport torch.nn.init as init\n\ndef custom_weight_init(model):\n for layer in model.modules():\n if isinstance(layer, nn.... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00047566",
"row_id": 47566,
"seed_ids": "[14]"
} | 0.508024 | Docs: Pytorch_47566 | I | [
"custom_weight_init",
"define_cnn_model"
] | 2 | [
[
"define_cnn_model",
"custom_weight_init"
]
] | 1 | [] | false | [
"SimpleCNN"
] | true | pytest | true | [
"torch"
] | false | 0a35d64a7491ba8c3b6e660e2cc60a97c997ab1c | 1fcb1bf267a59059d6fd612a5a8a7d71086e97a1 | |||
v1.0 | instruct | Docs | Docs: Python310_47572_I | You are tasked with building a simple yet efficient web scraping application that can concurrently fetch data from a list of URLs. Your goal is to evaluate the performance difference between using `threading` and `multiprocessing` for concurrent execution.
#### Requirements
1. **Fetch function**: Implement a function... | import requests
import threading
import multiprocessing
from queue import Queue
from typing import List, Dict
import time
# Fetch function to get the HTML content of a URL
def fetch(url: str) -> str:
try:
response = requests.get(url)
response.raise_for_status()
return response.text
exce... | from solution import fetch, thread_scraper, process_scraper
def test_fetch_valid_url():
content = fetch("https://www.example.com")
assert content is not None
assert "<title>Example Domain</title>" in content
def test_fetch_invalid_url():
content = fetch("https://www.nonexistentwebsite.com")
assert... | [
{
"docstring": null,
"function_declaration": "def fetch(url):",
"function_name": "fetch",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def thread_scraper(urls):",
"function_name": "thread_scraper",
"parameter_list": "(urls)"
},
{
"docstring":... | [
0,
1,
1,
1,
1,
0,
1,
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 requests\nfrom typing import List, Dict\nimport threading\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nimport time\n\ndef fetch(url: ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00047572",
"row_id": 47572,
"seed_ids": "[206]"
} | 0.523397 | Docs: Python310_47572 | I | [
"fetch",
"thread_scraper",
"process_worker",
"process_scraper"
] | 4 | [
[
"process_scraper",
"process_worker"
],
[
"process_worker",
"fetch"
],
[
"thread_scraper",
"fetch"
]
] | 3 | [] | false | [] | false | pytest | true | [
"requests"
] | false | b31f4c1017a0d82141375db18e3c92b7c0542d31 | 9d589d98b04398fbb302c02498a0b20e949dbf23 | |||
v1.0 | instruct | Docs | Docs: Python310_47573_I | #### Objective:
Demonstrate the ability to handle Python module imports, loading, and reloading using the `importlib` module, which supersedes the deprecated `imp` module.
#### Problem Statement:
The `imp` module is deprecated, and you are required to write a Python program that effectively replaces its functionality... | import importlib
import sys
from types import ModuleType
from typing import Optional
def import_module(module_name: str) -> ModuleType:
"""
Imports and returns the specified module. If the module is already imported,
returns the existing module from sys.modules.
"""
if module_name in sys.modules:
... | import os
import importlib
import sys
from solution import import_module, reload_module, cache_bytecode, source_from_cache
def test_import_module_existing():
assert import_module('os') == os
def test_import_module_new():
module_name = 'math'
if module_name in sys.modules:
del sys.modules[module_na... | [
{
"docstring": "Imports and returns the specified module. If the module is already imported,\nreturns the existing module from sys.modules.",
"function_declaration": "def import_module(module_name):",
"function_name": "import_module",
"parameter_list": "(module_name)"
},
{
"docstring": "Relo... | [
0,
1,
0,
0,
1,
1,
1,
0,
1
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import importlib\nimport sys\nimport importlib.util\nfrom importlib import abc\nfrom types import ModuleType\n\ndef import_module(module_name: str) -> ModuleType:\n ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00047573",
"row_id": 47573,
"seed_ids": "[276]"
} | 0.531641 | Docs: Python310_47573 | I | [
"import_module",
"reload_module",
"cache_bytecode",
"source_from_cache"
] | 4 | [
[
"reload_module",
"import_module"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b8e20f37c468e9bd26c26dd2bf06c39021e5a61f | 730977641f6208a5d0d3d584db16412f00cfd29d | |||
v1.0 | instruct | Docs | Docs: Python310_47594_I | **Objective:** Utilize Python's `cProfile` and `pstats` modules to identify performance bottlenecks in code and optimize it.
**Task:** You will be given a function `calculate_primes` which calculates prime numbers up to a given limit. Your tasks are:
1. Profile the given function using `cProfile` to gather performance... | def calculate_primes(limit):
"""
Original function to calculate prime numbers up to a specified limit.
"""
primes = []
for num in range(2, limit + 1):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
... | from solution import calculate_primes, optimized_calculate_primes
def test_calculate_primes_small_limit():
assert calculate_primes(10) == [2, 3, 5, 7]
def test_optimized_calculate_primes_small_limit():
assert optimized_calculate_primes(10) == [2, 3, 5, 7]
def test_calculate_primes_larger_limit():
primes_... | [
{
"docstring": "Original function to calculate prime numbers up to a specified limit.",
"function_declaration": "def calculate_primes(limit):",
"function_name": "calculate_primes",
"parameter_list": "(limit)"
},
{
"docstring": "Profiles the original function to calculate primes up to 10000\n... | [
1,
1,
0,
0,
0,
0,
1,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_primes(limit):\n \"\"\"\n Original function to calculate prime numbers up to a given limit.\n \"\"\"\n primes = []\n for num in range(2, li... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00047594",
"row_id": 47594,
"seed_ids": "[142]"
} | 0.526806 | Docs: Python310_47594 | I | [
"calculate_primes",
"run_profiling",
"analyze_profiling_results",
"optimized_calculate_primes",
"compare_performance"
] | 5 | [
[
"compare_performance",
"analyze_profiling_results"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 831b57632bbbbf9086078a8c51112383937f9f70 | 32fe3aef8fbf723d558d93fe21463cb6325e78d3 | |||
v1.0 | instruct | Docs | Docs: Python310_47615_I | **Objective:** Demonstrate your understanding of Python's `asyncio` library by implementing asynchronous functions and handling concurrent tasks.
**Problem Statement:**
You are tasked with implementing an asynchronous program that fetches data from multiple sources concurrently, processes each piece of data, and then... | import asyncio
import random
from typing import List
async def fetch_data(index: int) -> str:
# Simulate network latency
await asyncio.sleep(random.uniform(0.1, 1.0))
return f"data-{index}"
async def fetch_all_data(count: int) -> List[str]:
tasks = [fetch_data(i) for i in range(count)]
results = a... | import asyncio
from solution import fetch_data, fetch_all_data
def test_fetch_data_format():
# Since fetch_data is async, we need to run it in an event loop
async def run_test():
result = await fetch_data(1)
assert result == "data-1"
asyncio.run(run_test())
def test_fetch_all_data_cou... | [] | [
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\nimport random\nfrom typing import List\n\nasync def fetch_data(index: int) -> str:\n # Simulate network latency\n await asyncio.sleep(random.unifo... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00047615",
"row_id": 47615,
"seed_ids": "[270]"
} | 0.559706 | Docs: Python310_47615 | I | [
"fetch_data",
"fetch_all_data"
] | 2 | [
[
"fetch_all_data",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5883d74d6e819e6cfe71ba4ced89d00dad3843e9 | d1aca3eab8f2c712f980b2e9098d69e00749bad1 | |||
v1.0 | instruct | Docs | Docs: Python310_47702_I | ### Unique Coding Challenge for Python310 Understanding
#### Task
You are required to implement a function called `analyze_numbers` that takes in a list of integers and performs the following tasks:
1. Filters out the prime numbers from the list.
2. Categorizes the remaining numbers into 'even' and 'odd'.
3. Returns... | def is_prime(n: int) -> bool:
"""
Returns True if n is a prime number, else False.
"""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def analyze_numbers(numbers):
"""
Analyzes a list of integers returning ... | from solution import analyze_numbers, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(20) == False
assert is_prime(1) == False
assert is_prime(0) == False
def test_analyze_numbers_wi... | [
{
"docstring": "Returns True if n is a prime number, else False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Analyzes a list of integers returning a dictionary with prime, even and odd numbers.",
"function_declarat... | [
0,
0,
0,
1,
1,
0,
1,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00047702",
"row_id": 47702,
"seed_ids": "[426]"
} | 0.683585 | Docs: Python310_47702 | I | [
"is_prime",
"analyze_numbers"
] | 2 | [
[
"analyze_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2f351ffe700a44eca71058158c4b56fdab6e43f7 | 4fb65b83f56f3b6b700d6f255becaa9c8594cdb6 | |||
v1.0 | instruct | Docs | Docs: Python310_47716_I | **Objective**: Implement a task scheduler using `asyncio.Queue` that schedules tasks based on their priority and processes them concurrently with a given number of worker coroutines.
**Problem Statement**:
You are to design a task scheduler that manages tasks with varying priorities. Tasks should be processed by worke... | import asyncio
from typing import List, Tuple
async def worker(name, queue):
while True:
priority, task_id, duration = await queue.get()
await asyncio.sleep(duration)
print(f"Task {task_id} completed after {duration:.2f} seconds")
queue.task_done()
async def task_scheduler(tasks: L... | import asyncio
import pytest
from solution import task_scheduler
@pytest.mark.asyncio
async def test_simple_case():
tasks = [
(1, 101, 2.5),
(2, 102, 1.0),
(0, 103, 3.0),
(1, 104, 1.5)
]
num_workers = 2
await task_scheduler(tasks, num_workers)
@pytest.mark.asyncio
async... | [] | [
0,
0,
1,
1,
1,
1,
1,
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 asyncio\nfrom typing import List, Tuple\n\nasync def worker(name, queue):\n while True:\n priority, task_id, duration = await queue.get()\n awai... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00047716",
"row_id": 47716,
"seed_ids": "[111]"
} | 0.643795 | Docs: Python310_47716 | I | [
"worker",
"task_scheduler"
] | 2 | [
[
"task_scheduler",
"worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 572d6d391b93644e8d4a8c9e7717e9616294ebe2 | a2f183f02725b7fd57e7de37226a16454a81158b | |||
v1.0 | instruct | Docs | Docs: Python310_47741_I | ### Question: Prime Number Computation using multiprocessing
You are to implement a Python program to find all prime numbers within a given range using process-based parallelism with the `multiprocessing` module.
#### Requirements
1. **Function `is_prime(n)`**:
- **Input**: An integer `n`.
- **Output**: `Tru... | import math
from multiprocessing import Pool
def is_prime(n):
"""
Returns True if n is a prime number, otherwise False.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n... | from solution import is_prime, find_primes_in_range
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(29) == True
assert is_prime(30) == False
assert is_prime(1) == False
assert is_prime(0) =... | [
{
"docstring": "Returns True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of prime numbers in the range [start, end] using the specified number of worker processes... | [
0,
1,
0,
1,
0,
0,
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": "import multiprocessing\nimport math\n\ndef is_prime(n):\n \"\"\"\n Check if the number n is a prime number.\n A prime number is a positive integer greater than... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00047741",
"row_id": 47741,
"seed_ids": "[338]"
} | 0.609253 | Docs: Python310_47741 | I | [
"is_prime",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0664b4e9ebb8f52581b2f995204b02dad5de97e6 | 5deb7ed78ee3b2b68b3e6a2ab01c1c2efb69e826 | |||
v1.0 | instruct | Docs | Docs: Python310_47888_I | ### Question: Advanced Function Manipulation with functools
You are required to create a solution for a fictional data processing application. The problem involves implementing a class and a standalone function using the `functools` module to enhance performance and maintainability. Here are the specifics:
#### Part ... | from functools import cached_property, lru_cache, singledispatch, partial
import time
import math
class DataProcessor:
def __init__(self, data):
self._data = data
@cached_property
def mean(self):
return sum(self._data) / len(self._data)
@cached_property
def stdev(self):
me... | from solution import DataProcessor, expensive_computation, quick_computation, partial_computation, process
import pytest
def test_data_processor_mean():
dp = DataProcessor([1, 2, 3, 4, 5])
assert dp.mean == 3.0
def test_data_processor_stdev():
dp = DataProcessor([1, 2, 3, 4, 5])
assert math.isclose(dp... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import cached_property, lru_cache, singledispatch, partial\nimport time\nimport math\n\nclass DataProcessor:\n def __init__(self, data):\n self... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00047888",
"row_id": 47888,
"seed_ids": "[236]"
} | 0.538225 | Docs: Python310_47888 | I | [
"expensive_computation",
"quick_computation",
"process",
"_",
"_",
"_"
] | 6 | [
[
"quick_computation",
"expensive_computation"
]
] | 1 | [] | false | [
"DataProcessor"
] | true | pytest | true | [] | true | 78931bdfc4fbd7323d77d7d9ece749c7bd3e202d | eec45bc427177027f513a672415555eb276c6146 | |||
v1.0 | instruct | Docs | Docs: Python310_47914_I | ### Asynchronous Task Management Across Platforms
Due to the differences in how different platforms handle asynchronous I/O, particularly with Python's `asyncio` module, it is essential to write code that adapts to these variations. This task requires you to implement an asynchronous function that works correctly on b... | import asyncio
import platform
import selectors
async def echo_client(message):
reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
writer.write(message.encode())
await writer.drain()
data = await reader.read(100)
print(f'Received: {data.decode()}')
writer.close()
await writer... | import asyncio
import pytest
import platform
from unittest.mock import patch
from solution import platform_aware_network_operation
@pytest.mark.asyncio
async def test_platform_aware_network_operation_windows():
with patch('platform.system', return_value='Windows'), \
patch('asyncio.ProactorEventLoop') as... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport platform\nimport selectors\n\nasync def echo_client(message):\n try:\n reader, writer = await asyncio.open_connection('127.0.0.1', 8888... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00047914",
"row_id": 47914,
"seed_ids": "[370]"
} | 0.454009 | Docs: Python310_47914 | I | [
"echo_client",
"platform_aware_network_operation"
] | 2 | [
[
"platform_aware_network_operation",
"echo_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b012bdd5c3e7a95c60b7dc425bfb872fdd6e702f | 55961c2f988727102e8a962391ebd3b262b27774 | |||
v1.0 | instruct | Docs | Docs: Python310_47915_I | You have been provided with documentation on how to use the `asyncio` package's streaming capabilities to handle network connections in Python. Using this knowledge, you are tasked with implementing a mini chat server and client using asyncio streams.
### Part 1: Chat Server
Your first task is to implement the chat s... | import asyncio
active_clients = []
async def broadcast_message(message, writer):
for client in active_clients:
if client != writer:
client.write(message)
await client.drain()
async def handle_client(reader, writer):
try:
active_clients.append(writer)
while True... | import asyncio
import pytest
import functools
from solution import start_chat_server, start_chat_client
HOST = '127.0.0.1'
PORT = 8888
@pytest.fixture
def event_loop():
loop = asyncio.new_event_loop()
yield loop
loop.close()
def run_server(loop):
loop.run_until_complete(start_chat_server(HOST, PORT))... | [] | [
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 asyncio\n\nactive_clients = []\n\nasync def broadcast_message(message, writer):\n for client in active_clients:\n if client != writer:\n cli... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00047915",
"row_id": 47915,
"seed_ids": "[182]"
} | 0.555862 | Docs: Python310_47915 | I | [
"broadcast_message",
"handle_client",
"start_chat_server",
"send_message",
"receive_message",
"start_chat_client"
] | 6 | [
[
"handle_client",
"broadcast_message"
],
[
"start_chat_client",
"receive_message"
],
[
"start_chat_client",
"send_message"
],
[
"start_chat_server",
"handle_client"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 29a758c13f1d29faf5286c0b6e5f3461e68ca41c | 64552e4fdf985e74fd9f8b8131adc26cc6d9a595 | |||
v1.0 | instruct | Docs | Docs: Python310_48128_I | ### Text Editor Using `curses`
You are required to implement a basic text editor in Python using the `curses` module. The text editor should support the following functionalities:
1. **Create a text window** that users can type into.
2. **Handle basic cursor movements** using arrow keys.
3. **Support text insertion a... | import curses
def initialize_screen():
"""
This function initializes the curses screen and returns the stdscr object.
"""
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(True)
return stdscr
def edit_text(stdscr):
"""
This function allows text editing ins... | import pytest
from solution import save_to_file
def test_edit_text_save_to_file_creates_file():
contents = ["Hello World", "This is a test"]
save_to_file(contents)
with open("text_content.txt", "r") as f:
data = f.read()
assert data == "Hello World\nThis is a test"
def test_edit_text_... | [
{
"docstring": "This function initializes the curses screen and returns the stdscr object.",
"function_declaration": "def initialize_screen():",
"function_name": "initialize_screen",
"parameter_list": "()"
},
{
"docstring": "This function allows text editing inside the curses window, handlin... | [
0,
1,
0,
0,
1,
0,
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 curses\n\ndef initialize_screen():\n \"\"\"\n This function initializes the curses screen and returns the stdscr object.\n \"\"\"\n stdscr = curses.i... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048128",
"row_id": 48128,
"seed_ids": "[294]"
} | 0.453709 | Docs: Python310_48128 | I | [
"initialize_screen",
"edit_text",
"save_to_file",
"main"
] | 4 | [
[
"edit_text",
"save_to_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cb2fa4786d678871f07bbf11016197d05f457f9e | 4a86e5ace0ece768a317e9eec268ea04ebe36bf9 | |||
v1.0 | instruct | Docs | Docs: Python310_48152_I | You are tasked with simulating a restaurant order processing system using `asyncio` queues. The system should handle orders with different priorities.
#### Task:
1. Implement an asynchronous function `process_order` that simulates processing an order.
2. Implement an asynchronous function `restaurant_system` that hand... | import asyncio
from typing import List, Tuple
async def process_order(order: Tuple[int, int]) -> None:
priority, order_id = order
await asyncio.sleep(priority * 0.1)
print(f"Order {order_id} with priority {priority} is being processed.")
async def worker(name: str, queue: asyncio.PriorityQueue) -> None:
... | from solution import process_order, restaurant_system
import asyncio
async def test_process_order():
order = (1, 'order1')
await process_order(order)
async def test_restaurant_system():
orders = [(1, 'order1'), (3, 'order3'), (2, 'order2'), (1, 'order4')]
await restaurant_system(orders)
async def... | [] | [
1,
1,
1,
1,
1,
1,
0,
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, Tuple\n\nasync def process_order(order: Tuple[int, int]) -> None:\n priority, order_id = order\n await asyncio.sleep(prio... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00048152",
"row_id": 48152,
"seed_ids": "[111]"
} | 0.494763 | Docs: Python310_48152 | I | [
"process_order",
"worker",
"restaurant_system"
] | 3 | [
[
"restaurant_system",
"worker"
],
[
"worker",
"process_order"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 81688ef3a1dba6d387bded261807bfbdd0de4117 | ebe0137ed2c4c034527d1cef018cde9cf9363744 | |||
v1.0 | instruct | Docs | Docs: Python310_48163_I | ### Assessing Multiprocessing in Python
**Objective:**
Design a function that utilizes the `multiprocessing` package to calculate the factorial of multiple numbers concurrently. You need to demonstrate your understanding of creating and managing processes, handling shared resources, and collecting results from multip... | from multiprocessing import Pool
from math import factorial
def factorial_worker(n):
return n, factorial(n)
def calculate_factorials(nums):
with Pool() as pool:
results = pool.map(factorial_worker, nums)
return dict(results) | from solution import calculate_factorials
def test_single_element():
assert calculate_factorials([5]) == {5: 120}
def test_multiple_elements():
assert calculate_factorials([0, 1, 5, 7]) == {0: 1, 1: 1, 5: 120, 7: 5040}
def test_zero():
assert calculate_factorials([0]) == {0: 1}
def test_large_input(... | [
{
"docstring": null,
"function_declaration": "def factorial_worker(n):",
"function_name": "factorial_worker",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def calculate_factorials(nums):",
"function_name": "calculate_factorials",
"parameter_list": "(nu... | [
0,
1,
0,
1,
1,
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 multiprocessing\nfrom math import factorial\n\ndef calculate_factorials(nums):\n \"\"\"\n Calculate the factorials of a list of non-negative integers concu... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00048163",
"row_id": 48163,
"seed_ids": "[338]"
} | 0.881534 | Docs: Python310_48163 | I | [
"factorial_worker",
"calculate_factorials"
] | 2 | [
[
"calculate_factorials",
"factorial_worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fd8c136691d7d28ad92cc7010dbb0aa6d50dfa55 | 9d94b75d848ebd21e08e86c75115c9b4337c58db | |||
v1.0 | instruct | Docs | Docs: Python310_48198_I | **Problem Statement: Task Manager Simulator**
You are required to implement a task manager simulator using Python's `asyncio` library. The task manager should be able to schedule multiple asynchronous tasks, compute results concurrently, manage timeouts, and ensure the proper handling of cancellations. The purpose of ... | import asyncio
from typing import List, Tuple, Dict, Any
async def simulated_task(delay: int, task_name: str) -> str:
await asyncio.sleep(delay)
return task_name
async def task_wrapper(delay: int, task_name: str):
try:
result = await asyncio.wait_for(simulated_task(delay, task_name), timeout=5)
... | import asyncio
import pytest
from solution import task_manager
@pytest.mark.asyncio
async def test_task_manager_all_success():
tasks = [(1, "task_1"), (2, "task_2"), (1, "task_3")]
expected_output = {
"results": ["task_1", "task_3", "task_2"],
"exceptions": [],
"order_of_completion": ["... | [] | [
0,
1,
1,
1,
0,
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 asyncio\nfrom typing import List, Tuple, Dict, Any\n\nasync def task_function(delay: int, task_name: str) -> str:\n await asyncio.sleep(delay)\n return f\"... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00048198",
"row_id": 48198,
"seed_ids": "[317]"
} | 0.587778 | Docs: Python310_48198 | I | [
"simulated_task",
"task_wrapper",
"task_manager"
] | 3 | [
[
"task_manager",
"task_wrapper"
],
[
"task_wrapper",
"simulated_task"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 308b85ece994b9cbcb3fd363987baa242aad2f5d | 4a92817280f5a8de876e9b1aa47b139abfce87a2 | |||
v1.0 | instruct | Docs | Docs: Python310_48212_I | ### Advanced Context Manager with Contextlib
#### Objective
Design a context manager that ensures resources are acquired and released correctly, even when exceptions occur, demonstrating your understanding of the `contextlib` module.
#### Requirements
1. **Function Implementation**:
- Create a context manager usi... | from contextlib import contextmanager
# Mock functions for demonstration
def open_database_connection():
print("Database connection opened")
return "db_connection"
def close_database_connection(conn):
print(f"Database connection {conn} closed")
def log_exception(exc):
print(f"Exception Logged: {exc}"... | from solution import manage_database_connection, open_database_connection, close_database_connection, log_exception
def test_normal_operation():
"""
Test that the context manager opens and closes the connection normally without exceptions.
"""
try:
with manage_database_connection() as conn:
... | [
{
"docstring": null,
"function_declaration": "def open_database_connection():",
"function_name": "open_database_connection",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def close_database_connection(conn):",
"function_name": "close_database_connection",
... | [
1,
0,
1,
0,
0,
1,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from contextlib import contextmanager\n\n# Mock functions for demonstration\ndef open_database_connection():\n print(\"Database connection opened\")\n return \"db... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00048212",
"row_id": 48212,
"seed_ids": "[177]"
} | 0.379007 | Docs: Python310_48212 | I | [
"open_database_connection",
"close_database_connection",
"log_exception",
"manage_database_connection"
] | 4 | [
[
"manage_database_connection",
"close_database_connection"
],
[
"manage_database_connection",
"log_exception"
],
[
"manage_database_connection",
"open_database_connection"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | c2d85c72f591d2afa22d0ab594ef22e2f97345d2 | c154d9785dab0fa05fd4e97ed9209ce2ed136f05 | |||
v1.0 | instruct | Docs | Docs: Python310_48220_I | You are required to implement a simple asynchronous chat server and client using the `asyncio` and `socket` modules. The communication between the server and clients should be secured using the `ssl` module.
#### Server Requirements:
1. The server should listen on a specified IP address and port.
2. The server should ... | import asyncio
import ssl
clients = []
async def handle_client(reader, writer):
global clients
addr = writer.get_extra_info('peername')
clients.append(writer)
print(f"New connection from {addr}")
try:
while True:
data = await reader.read(100)
if not data:
... | import asyncio
import ssl
import tempfile
from solution import start_server, start_client
async def run_test_server_and_client():
ip = '127.0.0.1'
port = 8888
# Generate a temporary SSL certificate and key for testing
certfile = tempfile.NamedTemporaryFile(delete=False)
keyfile = tempfile.NamedTe... | [] | [
1,
1,
1,
0,
0,
0,
1,
1,
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 ssl\n\nclients = set()\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n clients.add(writer)\n pr... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048220",
"row_id": 48220,
"seed_ids": "[151]"
} | 0.563672 | Docs: Python310_48220 | I | [
"handle_client",
"start_server",
"start_client"
] | 3 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4b22e2c49f5a4a23d12d6345cf6e73ee88863c13 | 0d9e6fb9d98d981687c5a57e7d70710cf690f3e1 | |||
v1.0 | instruct | Docs | Docs: Python310_48311_I | #### Objective
The goal is to implement a solution that uses both `ThreadPoolExecutor` and `ProcessPoolExecutor` to manage heterogeneous tasks concurrently. You will need to ensure that the code handles exceptions gracefully and efficiently manages resources.
#### Description
You are given two types of tasks: I/O-boun... | import concurrent.futures
import urllib.request
import math
def fetch_url(url, timeout=60):
"""
Fetches the content from the given URL and returns its length.
Parameters:
- url (str): The URL to fetch.
- timeout (int): The timeout for the URL fetch operation.
Returns:
- int: The l... | import pytest
from solution import fetch_url, is_prime, execute_tasks
def test_fetch_url():
url = 'https://www.example.com'
length = fetch_url(url)
assert length > 0 # Assume example.com returns some content
def test_is_prime():
assert is_prime(2) is True
assert is_prime(3) is True
assert is_... | [
{
"docstring": "Fetches the content from the given URL and returns its length.\n\nParameters:\n- url (str): The URL to fetch.\n- timeout (int): The timeout for the URL fetch operation.\n\nReturns:\n- int: The length of the content fetched from the URL.",
"function_declaration": "def fetch_url(url, timeout=6... | [
0,
0,
0,
1,
1,
1,
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 concurrent.futures\nimport urllib.request\nimport math\n\ndef fetch_url(url, timeout=60):\n try:\n with urllib.request.urlopen(url, timeout=timeout) as... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00048311",
"row_id": 48311,
"seed_ids": "[347]"
} | 0.579107 | Docs: Python310_48311 | I | [
"fetch_url",
"is_prime",
"execute_tasks"
] | 3 | [
[
"execute_tasks",
"fetch_url"
],
[
"execute_tasks",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7413c814796b21771f4328ca1324e2b928106fc8 | 9dc305107cd7d5311adb096c27f0954268731ce1 | |||
v1.0 | instruct | Docs | Docs: Python310_48425_I | ### Question
You are tasked with securing the authentication process for an online service by implementing a function that creates hashed and salted cookies for users. The cookies should securely embed the user's ID and an expiration timestamp. Additionally, you should provide a function to verify these cookies.
Use ... | import hashlib
import hmac
import time
def create_cookie(user_id: str, expires_at: int, secret_key: bytes, salt: bytes, personalization: bytes) -> str:
"""
Generates a hex-encoded cookie with BLAKE2b hash.
"""
payload = f"{user_id}:{expires_at}".encode('utf-8')
h = hashlib.blake2b(key=secret_key, s... | import time
from solution import create_cookie, verify_cookie
# Define constant test data
USER_ID = "test_user"
SECRET_KEY = b'secret_key_for_testing'
SALT = b'salt_for_testing'
PERSONALIZATION = b'app_specific'
def test_create_and_verify_cookie():
expires_at = int(time.time()) + 60 # cookie valid for 60 seconds... | [
{
"docstring": "Generates a hex-encoded cookie with BLAKE2b hash.",
"function_declaration": "def create_cookie(user_id, expires_at, secret_key, salt, personalization):",
"function_name": "create_cookie",
"parameter_list": "(user_id, expires_at, secret_key, salt, personalization)"
},
{
"docst... | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\nimport hmac\nimport time\n\ndef create_cookie(user_id: str, expires_at: int, secret_key: bytes, salt: bytes, personalization: bytes) -> str:\n \"\"\"... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00048425",
"row_id": 48425,
"seed_ids": "[225]"
} | 0.58092 | Docs: Python310_48425 | I | [
"create_cookie",
"verify_cookie"
] | 2 | [
[
"verify_cookie",
"create_cookie"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d560c931a4dd9e49605b2468d14cea75292dbe70 | a1238198f346f09571bc1505e9a1c1bb15119e92 | |||
v1.0 | instruct | Docs | Docs: Python310_48439_I | ### Codec Registration and Manipulation in Python
In this task, you are required to demonstrate your understanding of codec registration and encoding/decoding in Python by implementing a custom encoding and an error handling mechanism.
#### Requirements
1. **Register a Custom Codec:**
- Implement and register a n... | import codecs
class VowelNumberEncoder:
def __init__(self):
self.vowel_map = {'a': '1', 'e': '2', 'i': '3', 'o': '4', 'u': '5'}
def encode(self, input, errors='strict'):
result = ''.join([self.vowel_map.get(char, char) for char in input])
return (result.encode(), len(input))
... | import pytest
from solution import (
register_vowelnumber_codec,
register_hex_replacement_error_handler,
encode_with_vowelnumber,
decode_with_vowelnumber,
hex_replacement_error_handler
)
def test_vowelnumber_codec_encoding():
register_vowelnumber_codec()
original_text = "hello world"
en... | [] | [
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 codecs\n\nclass VowelNumberEncoder:\n def __init__(self):\n self.vowel_map = {'a': '1', 'e': '2', 'i': '3', 'o': '4', 'u': '5'}\n\n def encode(self,... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048439",
"row_id": 48439,
"seed_ids": "[47]"
} | 0.682592 | Docs: Python310_48439 | I | [
"register_vowelnumber_codec",
"encode_with_vowelnumber",
"decode_with_vowelnumber",
"hex_replacement_error_handler",
"register_hex_replacement_error_handler"
] | 5 | [
[
"register_hex_replacement_error_handler",
"hex_replacement_error_handler"
]
] | 1 | [] | false | [
"VowelNumberEncoder"
] | true | pytest | true | [] | true | 5b1679e59d9089622e9e4763eb5cc506889116f6 | 71797569cdecb1e4ac473dafac737782d9ee9641 | |||
v1.0 | instruct | Docs | Docs: Python310_48443_I | **Title: Implement a CGI Script to Process User Data and File Uploads**
#### Objective:
You are tasked with creating a CGI script in Python that processes user-submitted form data and handles file uploads. Your script should validate the form data, ensure secure handling of file uploads, and return a formatted HTML re... | #!/usr/bin/env python3
import cgi
import cgitb
import re
# Enable CGI traceback for debugging
cgitb.enable()
def validate_email(email):
"""
Validate the email format using regex.
"""
return re.match(r'^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$', email)
def handle_file_upload(fileitem):
"""... | import pytest
from solution import validate_email, handle_file_upload
from io import BytesIO
def test_validate_email():
assert validate_email("test@example.com")
assert not validate_email("bad-email")
assert not validate_email("missingAtsign.com")
assert not validate_email("@missingUsername.com")
def ... | [
{
"docstring": "Validate the email format using regex.",
"function_declaration": "def validate_email(email):",
"function_name": "validate_email",
"parameter_list": "(email)"
},
{
"docstring": "Check the file type and size for the uploaded profile picture.",
"function_declaration": "def h... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "#!/usr/bin/env python3\n\nimport cgi\nimport cgitb\nimport re\n\n# Enable CGI traceback for debugging\ncgitb.enable()\n\ndef validate_email(email):\n \"\"\"Validate ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00048443",
"row_id": 48443,
"seed_ids": "[183]"
} | 0.551183 | Docs: Python310_48443 | I | [
"validate_email",
"handle_file_upload",
"application"
] | 3 | [
[
"application",
"handle_file_upload"
],
[
"application",
"validate_email"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b3c6b6e2218d37390a6a829cc7adf3fe92fc3366 | ecafed35ac131e932fb1e33c5ad366bac3c7162e | |||
v1.0 | instruct | Docs | Docs: Python310_48470_I | **Objective:** Demonstrate your understanding of the asyncio subprocess API in Python 3.10.
---
**Question:**
You are tasked with creating a command-line utility that launches multiple shell commands in parallel, captures their outputs, and aggregates the results. Each command should be executed as a subprocess usi... | from typing import List, Tuple
import asyncio
async def run_command(cmd: str) -> Tuple[str, str]:
"""
Executes a single shell command and captures its stdout and stderr outputs.
:param cmd: The shell command to execute.
:return: A tuple containing the stdout and stderr outputs of the command.
... | import asyncio
from solution import run_commands
def test_single_command():
commands = ['echo Hello']
stdout_list, stderr_list = asyncio.run(run_commands(commands))
assert stdout_list == ['Hello\n']
assert stderr_list == ['']
def test_multiple_commands():
commands = ['echo Hello', 'echo World']
... | [] | [
0,
0,
1,
1,
0,
0,
1,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport asyncio\n\nasync def run_command(cmd: str) -> Tuple[str, str]:\n process = await asyncio.create_subprocess_shell(\n cmd... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048470",
"row_id": 48470,
"seed_ids": "[264]"
} | 0.764697 | Docs: Python310_48470 | I | [
"run_command",
"run_commands"
] | 2 | [
[
"run_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 53e843cbcb4f360ecda43d2023f9d09e0e86d8fa | 390c0ea6444f3bf9a4a52955b7210db499d98a16 | |||
v1.0 | instruct | Docs | Docs: Python310_48552_I | ### Python Profiling Assessment
You are given a large dataset processing function which takes a significant amount of time to execute. Your task is to profile this function using the `cProfile` and `pstats` modules to find performance bottlenecks.
#### Function to be Profiled
```python
def process_data(data):
pr... | import cProfile
import pstats
def process_data(data):
processed_data = []
for record in data:
# Simulate some complex processing
for _ in range(1000):
processed_record = record ** 2
processed_data.append(processed_record)
return processed_data
def profile_processing(dat... | import os
import pytest
from solution import process_data, profile_processing
def test_process_data():
data = [1, 2, 3, 4, 5]
expected_output = [1, 4, 9, 16, 25]
output = process_data(data)
assert output == expected_output
def test_profile_processing():
data = list(range(1, 100))
profile_proce... | [
{
"docstring": null,
"function_declaration": "def process_data(data):",
"function_name": "process_data",
"parameter_list": "(data)"
},
{
"docstring": null,
"function_declaration": "def profile_processing(data):",
"function_name": "profile_processing",
"parameter_list": "(data)"
... | [
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 cProfile\nimport pstats\n\ndef process_data(data):\n processed_data = []\n for record in data:\n # Simulate some complex processing\n for _ i... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00048552",
"row_id": 48552,
"seed_ids": "[142]"
} | 0.524348 | Docs: Python310_48552 | I | [
"process_data",
"profile_processing"
] | 2 | [
[
"profile_processing",
"process_data"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 03749c0ac645326520ecd3de60fe1660acc7b79f | 3aefc1aa2e2b4cc02d481c94906cfc740cdcd175 | |||
v1.0 | instruct | Docs | Docs: Python310_48560_I | **Problem Statement:**
You are tasked with creating a system to encode and decode text using custom and standard codecs. The following operations must be supported:
1. **Encode and Decode Text**: Using any of the standard codecs provided by the `codecs` module, encode a given string into bytes and decode it back into... | import codecs
# 1. Encode text function
def encode_text(text, encoding):
return codecs.encode(text, encoding, errors='replace')
# 2. Decode text function
def decode_text(encoded_bytes, encoding):
return codecs.decode(encoded_bytes, encoding, errors='replace')
# 3. Caesar Cipher encode
def caesar_encode(text)... | def test_encode_text():
assert encode_text('hello', 'utf-8') == b'hello'
assert encode_text('hello', 'latin-1') == b'hello'
assert encode_text('Café', 'ascii') == b'Caf?'
def test_decode_text():
assert decode_text(b'hello', 'utf-8') == 'hello'
assert decode_text(b'hello', 'latin-1') == 'hello'
... | [
{
"docstring": null,
"function_declaration": "def encode_text(text, encoding):",
"function_name": "encode_text",
"parameter_list": "(text, encoding)"
},
{
"docstring": null,
"function_declaration": "def decode_text(encoded_bytes, encoding):",
"function_name": "decode_text",
"para... | [
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 codecs\n\ndef encode_text(text: str, encoding: str) -> bytes:\n \"\"\"\n Encodes the given text using the specified encoding.\n \"\"\"\n return codec... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00048560",
"row_id": 48560,
"seed_ids": "[211]"
} | 0.555655 | Docs: Python310_48560 | I | [
"encode_text",
"decode_text",
"caesar_encode",
"caesar_decode",
"caesar_codec",
"register_caesar_codec",
"custom_encode",
"custom_error_handler",
"main"
] | 9 | [
[
"register_caesar_codec",
"caesar_codec"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 31bacf5cc867efeeead4d3e3dd5e9c6b6300477a | c2fbdb1be0c572bdaf15e27f7cd4a5a8e281569e | |||
v1.0 | instruct | Docs | Docs: Python310_48575_I | **Problem Statement:**
You are working on a data processing pipeline that requires efficient handling and transformation of a stream of data using functional programming concepts in Python. Your task is to implement a series of functions that will process a list of events. Each event is represented as a dictionary wit... | from functools import reduce
def generate_values(events):
"""
Generator function that yields the value field from each event in the provided list of events.
"""
for event in events:
yield event['value']
def filter_events(events, event_type):
"""
Filters the events, only including those... | from solution import generate_values, filter_events, sum_values, enumerate_events, pipeline
def test_generate_values():
events = [{"id": 1, "type": "click", "value": 3.5}, {"id": 2, "type": "view", "value": 2.0}]
assert list(generate_values(events)) == [3.5, 2.0]
def test_filter_events():
events = [{"id":... | [
{
"docstring": "Generator function that yields the value field from each event in the provided list of events.",
"function_declaration": "def generate_values(events):",
"function_name": "generate_values",
"parameter_list": "(events)"
},
{
"docstring": "Filters the events, only including thos... | [
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": "from functools import reduce\n\ndef generate_values(events):\n \"\"\"\n Generator function that yields the value field from each event in events.\n \"\"\"\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00048575",
"row_id": 48575,
"seed_ids": "[78]"
} | 0.504291 | Docs: Python310_48575 | I | [
"generate_values",
"filter_events",
"sum_values",
"enumerate_events",
"pipeline"
] | 5 | [
[
"pipeline",
"enumerate_events"
],
[
"pipeline",
"filter_events"
],
[
"pipeline",
"generate_values"
],
[
"pipeline",
"sum_values"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 4e1615b34179e8b7215288193d8230311e67859b | de69888ef509e3e393084aef14e30178df1ac4b9 | |||
v1.0 | instruct | Docs | Docs: Python310_48579_I | Managing Virtual Environments and Packages
**Objective**:
Create a script that demonstrates the creation, activation, and management of virtual environments and packages using Python.
**Task**:
Write a Python script that performs the following tasks:
1. **Create a Virtual Environment**:
- Create a virtual enviro... | import os
import subprocess
def execute_command(command):
try:
subprocess.run(command, check=True, shell=True)
except subprocess.CalledProcessError as e:
print(f"An error occurred while executing: {command}\nError: {str(e)}")
def create_virtual_environment(env_name='test-env'):
print(f"Cre... | from solution import create_virtual_environment, generate_requirements
def test_create_virtual_environment():
# Assuming the environment does not already exist
env_name = 'test-env-test'
create_virtual_environment(env_name)
assert os.path.isdir(env_name), f"Virtual environment '{env_name}' should have ... | [
{
"docstring": null,
"function_declaration": "def execute_command(command):",
"function_name": "execute_command",
"parameter_list": "(command)"
},
{
"docstring": null,
"function_declaration": "def create_virtual_environment(env_name='test-env'):",
"function_name": "create_virtual_env... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport subprocess\n\ndef create_virtual_environment(env_name):\n \"\"\"\n Create a virtual environment with the given name.\n \"\"\"\n try:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00048579",
"row_id": 48579,
"seed_ids": "[417]"
} | 0.549416 | Docs: Python310_48579 | I | [
"execute_command",
"create_virtual_environment",
"activate_virtual_environment",
"install_packages",
"generate_requirements",
"upgrade_package",
"list_installed_packages",
"main"
] | 8 | [
[
"create_virtual_environment",
"execute_command"
],
[
"generate_requirements",
"execute_command"
],
[
"install_packages",
"execute_command"
],
[
"upgrade_package",
"execute_command"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | af0b839baccb08ec5de2a8104c237c61f3583fe2 | 6ca26a69174910dddc93e38a0da552497bd32447 | |||
v1.0 | instruct | Docs | Docs: Python310_48589_I | **Context & Objectives:**
You are tasked with improving the efficiency and flexibility of a hypothetical data processing system. Your solution should leverage the `functools` module’s features to optimize and enhance the system.
**Problem Statement:**
You need to implement the following functionalities:
1. A **memoiz... | import functools
from functools import partial, singledispatch
# Part 1: Memoized Factorial
@functools.cache
def memoized_factorial(n):
if n < 2:
return 1
return n * memoized_factorial(n - 1)
# Part 2: Data Cleaner
def data_cleaner(data, strip_whitespace=True, to_lowercase=True, remove_chars=None):
... | from solution import memoized_factorial, default_data_cleaner, process_data, data_cleaner
def test_memoized_factorial():
assert memoized_factorial(0) == 1
assert memoized_factorial(1) == 1
assert memoized_factorial(5) == 120
assert memoized_factorial(6) == 720
def test_data_cleaner():
assert data_... | [
{
"docstring": null,
"function_declaration": "def memoized_factorial(n):",
"function_name": "memoized_factorial",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def data_cleaner(data, strip_whitespace=True, to_lowercase=True, remove_chars=None):",
"function_... | [
0,
0,
0,
0,
0,
1,
1,
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 functools\nfrom functools import partial, singledispatch\n\n# Part 1: Memoized Factorial\n@functools.cache\ndef memoized_factorial(n):\n if n == 0:\n r... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00048589",
"row_id": 48589,
"seed_ids": "[236]"
} | 0.477652 | Docs: Python310_48589 | I | [
"memoized_factorial",
"data_cleaner",
"process_data",
"_",
"_",
"_"
] | 6 | [
[
"_",
"process_data"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 3a52a342fc7fb28c62b6a0f901596eb33e219497 | d2d57681a63e03ac1328ebcdbe61296662e31d9c | |||
v1.0 | instruct | Docs | Docs: Python310_48609_I | #### Objective
Create a CGI script using Python to process a user registration form. The form will collect a username, email address, and password from the user. Your CGI script should perform the following tasks:
1. Validate the form data:
- Ensure that all fields (username, email, password) are provided.
- Ens... | #!/usr/bin/env python3
import cgi
import cgitb
import re
cgitb.enable()
def validate_form_data(username, email, password):
errors = []
if not username:
errors.append("Username is required.")
if not email:
errors.append("Email is required.")
elif not re.match(r"[^@]+@[^@]+\.[^@]+", em... | import re
from solution import validate_form_data
def test_all_fields_valid():
errors = validate_form_data("user123", "user@example.com", "password123")
assert errors == []
def test_missing_username():
errors = validate_form_data("", "user@example.com", "password123")
assert "Username is required." in... | [
{
"docstring": null,
"function_declaration": "def validate_form_data(username, email, password):",
"function_name": "validate_form_data",
"parameter_list": "(username, email, password)"
},
{
"docstring": null,
"function_declaration": "def registration_form():",
"function_name": "regi... | [
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": "#!/usr/bin/env python3\n\nimport cgi\nimport cgitb\nimport re\n\ncgitb.enable()\n\ndef validate_form_data(username, email, password):\n erro... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048609",
"row_id": 48609,
"seed_ids": "[183]"
} | 0.565439 | Docs: Python310_48609 | I | [
"validate_form_data",
"registration_form"
] | 2 | [
[
"registration_form",
"validate_form_data"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2a7e99af29437851f9f836b6059b97a126b27519 | 62c05ad897280614259adfe5d0e0e0c045bebff3 | |||
v1.0 | instruct | Docs | Docs: Python310_48654_I | ### Asynchronous Network Request Aggregator
**Problem Statement:**
You are tasked with designing a asynchronous network request aggregator using the asyncio library. The aim is to fetch data concurrently from multiple URLs and process the collected data asynchronously.
**Function to Implement:**
```python
import as... | import asyncio
import aiohttp
async def fetch_data(session, url):
"""
Fetch data from a given URL using aiohttp session.
Args:
session (aiohttp.ClientSession): The aiohttp session to perform the request.
url (str): The URL to fetch data from.
Returns:
str: The text content of ... | import pytest
import asyncio
from solution import fetch_data, aggregate_requests, process_aggregated_data
@pytest.mark.asyncio
async def test_fetch_data():
async with aiohttp.ClientSession() as session:
url = "https://jsonplaceholder.typicode.com/posts"
response = await fetch_data(session, 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 aiohttp\n\nasync def fetch_data(session, url):\n \"\"\"\n Fetch data from a given URL using aiohttp session.\n\n Args:\n session ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00048654",
"row_id": 48654,
"seed_ids": "[270]"
} | 0.59384 | Docs: Python310_48654 | I | [
"fetch_data",
"aggregate_requests",
"process_aggregated_data"
] | 3 | [
[
"aggregate_requests",
"fetch_data"
],
[
"process_aggregated_data",
"aggregate_requests"
]
] | 2 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 4cc99794e1a452d76f14ac5066fc9a40c9cbda4e | dfab126119f17d7205cbad17a31cb9b41604f516 | |||
v1.0 | instruct | Docs | Docs: Python310_48699_I | **Turtle Graphics Challenge: Draw a Radial Pattern**
### Objective
Write a Python function using the turtle module. This function should create a radial pattern where each spoke of the pattern is a concentric circle. The number of spokes and the number of circles within each spoke should be customizable. The circles s... | import turtle
import math
from turtle import colormode
def hex_to_rgb(hex_color):
"""
Convert hex color to RGB.
"""
hex_color = hex_color.lstrip('#')
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
def interpolate_color(color1, color2, fraction):
"""
Interpolate between two RGB ... | from solution import hex_to_rgb, interpolate_color
def test_hex_to_rgb():
assert hex_to_rgb('#FF0000') == (255, 0, 0)
assert hex_to_rgb('#00FF00') == (0, 255, 0)
assert hex_to_rgb('#0000FF') == (0, 0, 255)
assert hex_to_rgb('#FFFFFF') == (255, 255, 255)
assert hex_to_rgb('#000000') == (0, 0, 0)
de... | [
{
"docstring": "Convert hex color to RGB.",
"function_declaration": "def hex_to_rgb(hex_color):",
"function_name": "hex_to_rgb",
"parameter_list": "(hex_color)"
},
{
"docstring": "Interpolate between two RGB colors.\nfraction is a float between 0 and 1.",
"function_declaration": "def int... | [
1,
0,
0,
1,
0,
0,
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 turtle\nimport math\nfrom turtle import colormode\n\ndef hex_to_rgb(hex_color):\n \"\"\"\n Convert hex color to RGB.\n \"\"\"\n hex_color = hex_color... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00048699",
"row_id": 48699,
"seed_ids": "[296]"
} | 0.563883 | Docs: Python310_48699 | I | [
"hex_to_rgb",
"interpolate_color",
"draw_radial_pattern"
] | 3 | [
[
"draw_radial_pattern",
"hex_to_rgb"
],
[
"draw_radial_pattern",
"interpolate_color"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 824f91c1b99c2762b3900ed58ca516b6702e24c7 | c28db2c58908e17690fe1c35dd85ce7856d3bf34 | |||
v1.0 | instruct | Docs | Docs: Scikit_48769_I | **Title**: Implementing a Text Classification Pipeline with Scikit-learn
**Objective**: Demonstrate the ability to preprocess text data, transform it into numerical features, and apply a machine learning model to classify the data using scikit-learn.
**Problem Statement**:
You are given a dataset containing text doc... | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score
import string
def preprocess_text(text):
"""
Preprocess the input text by removing punctuation and lowercasing.
""... | import pytest
from solution import preprocess_text, build_and_evaluate_pipeline
def test_preprocess_text():
assert preprocess_text("Hello, World!") == "hello world"
assert preprocess_text("It's simple.") == "its simple"
assert preprocess_text("Python-Programming!") == "pythonprogramming"
def test_build_an... | [
{
"docstring": "Preprocess the input text by removing punctuation and lowercasing.",
"function_declaration": "def preprocess_text(text):",
"function_name": "preprocess_text",
"parameter_list": "(text)"
},
{
"docstring": null,
"function_declaration": "def build_and_evaluate_pipeline(train... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.me... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00048769",
"row_id": 48769,
"seed_ids": "[40]"
} | 0.645926 | Docs: Scikit_48769 | I | [
"preprocess_text",
"build_and_evaluate_pipeline"
] | 2 | [
[
"build_and_evaluate_pipeline",
"preprocess_text"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sklearn"
] | false | e18b65b25a8b95562954f1490dde7a61ff25b3f1 | 6cbd6f7285b0e8b261260862fc8a82aade06ee14 | |||
v1.0 | instruct | Docs | Docs: Scikit_48774_I | **Coding Assessment Question:**
**Objective:**
Design and implement an out-of-core learning system using scikit-learn for a text classification problem. The goal is to classify text data from a simulated streaming source using incremental learning.
**Problem Statement:**
You are provided with a dataset of text docum... | from typing import List
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
def stream_data(file_path: str, chunk_size: int):
with open(file_path, 'r') as file:
data = []
labels = []
for line... | import pytest
from solution import stream_data, incremental_text_classifier
def test_stream_data():
file_path = 'test_train_data.txt'
chunk_size = 2
# Create a dummy file with sample data
with open(file_path, 'w') as file:
file.write("This is document 1,1\n")
file.write("This is documen... | [
{
"docstring": null,
"function_declaration": "def stream_data(file_path, chunk_size):",
"function_name": "stream_data",
"parameter_list": "(file_path, chunk_size)"
},
{
"docstring": null,
"function_declaration": "def incremental_text_classifier(file_path, test_data, test_labels):",
"... | [
0,
0,
1,
0,
0,
1,
1,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nfrom typing import List\nimport numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nf... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00048774",
"row_id": 48774,
"seed_ids": "[63]"
} | 0.519556 | Docs: Scikit_48774 | I | [
"stream_data",
"incremental_text_classifier"
] | 2 | [
[
"incremental_text_classifier",
"stream_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sklearn"
] | false | 48007ffcda12061e3a892ec8eaa7b779a20453e1 | 6d61fffa70b7193256bd1e592dbe1eea88f631c6 | |||
v1.0 | instruct | Docs | Docs: Python310_48838_I | ### Advanced Python Expression Evaluation
#### Objective
Write a function `matrix_operations` that takes in a matrix (a list of lists of numbers) and performs various operations to transform it based on given functions. The transformations should include both synchronous and asynchronous generator expressions, and uti... | from typing import List
import asyncio
async def async_row_sums(matrix: List[List[float]]) -> List[float]:
for row in matrix:
await asyncio.sleep(0) # Yield control, simulating an async operation
yield sum(row)
async def matrix_operations(matrix: List[List[float]]) -> List[List[float]]:
# Ste... | import asyncio
import pytest
from solution import matrix_operations
@pytest.mark.asyncio
async def test_matrix_operations_example():
matrix = [
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]
]
expected_result = [
[14.0, 14.0, 14.0],
[77.0, 77.0, 77.0],
[1... | [] | [
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 typing import List\nimport asyncio\n\nasync def matrix_operations(matrix: List[List[float]]) -> List[List[float]]:\n # Step 1: Squaring Elements\n squared_ma... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00048838",
"row_id": 48838,
"seed_ids": "[98]"
} | 0.675569 | Docs: Python310_48838 | I | [
"async_row_sums",
"matrix_operations"
] | 2 | [
[
"matrix_operations",
"async_row_sums"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e9b8e98dc71f7a775a6c016cee3d91f36d49ee28 | d0303f54363ba0c6a5c62f50108058373da7755f | |||
v1.0 | instruct | Docs | Docs: Python310_48860_I | ### Custom Context Manager with ExitStack
**Objective:**
Design and implement a custom context manager using the `contextmanager` decorator from the `contextlib` module. The context manager should handle resource acquisition and release, and you need to leverage `ExitStack` to manage multiple resources effectively.
... | from contextlib import contextmanager, ExitStack
@contextmanager
def managed_file(file_name, mode):
"""
Context manager to open and close a file.
Args:
file_name (str): The name of the file to open.
mode (str): The mode to open the file in (e.g., 'r' for read, 'w' for write).
... | import os
from solution import managed_file, manage_multiple_files
# Helper function to create and populate a test file
def create_test_file(file_name, content):
with open(file_name, 'w') as f:
f.write(content)
def test_managed_file_read():
# Setup: Create a test file
test_file = 'test_read.txt'
... | [
{
"docstring": "Context manager to open and close a file.\n\nArgs:\n file_name (str): The name of the file to open.\n mode (str): The mode to open the file in (e.g., 'r' for read, 'w' for write).\n\nYields:\n file object: The opened file object.",
"function_declaration": "def managed_file(file_name... | [
1,
1,
1,
1,
1,
1,
0,
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 contextlib import contextmanager, ExitStack\n\n@contextmanager\ndef managed_file(file_name, mode):\n file = open(file_name, mode)\n try:\n yield file\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00048860",
"row_id": 48860,
"seed_ids": "[177]"
} | 0.434448 | Docs: Python310_48860 | I | [
"managed_file",
"manage_multiple_files"
] | 2 | [
[
"manage_multiple_files",
"managed_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8fb4a2d1e6a14884deee17a1b287db224c77010d | 375303f238067a928cfa321bc79cdf4ddb973fde | |||
v1.0 | instruct | Docs | Docs: Python310_48954_I | #### Objective
Write an asynchronous Python program using the `asyncio` library. The program should manage multiple coroutines that perform IO-bound tasks concurrently and synchronize their execution using `asyncio` synchronization primitives.
#### Problem Statement
Design an asynchronous program that simulates a scen... | import asyncio
async def fetch_data(lock: asyncio.Lock, worker_id: int):
"""
Simulates fetching data from a server and processing it.
The lock ensures that only one worker fetches data at a time.
"""
async with lock:
await asyncio.sleep(1) # Simulates the fetch delay
data = f"data_... | import asyncio
from solution import run_workers
def test_run_workers_output():
async def test():
# Redirect stdout to capture print output
from io import StringIO
import sys
output = StringIO()
sys.stdout = output
await run_workers(3, 5)
... | [] | [
0,
0,
0,
0,
0,
1,
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": "import asyncio\nfrom typing import List\n\nasync def fetch_data(lock: asyncio.Lock, worker_id: int) -> str:\n async with lock:\n await asyncio.sleep(1) # sim... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00048954",
"row_id": 48954,
"seed_ids": "[270]"
} | 0.593959 | Docs: Python310_48954 | I | [
"fetch_data",
"worker",
"run_workers"
] | 3 | [
[
"run_workers",
"worker"
],
[
"worker",
"fetch_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1feef7eac7f1490cc6bd84b3a79ed5d2536fe6c5 | 0cc17b2e7b12314e71b3e31d04b10ca8c0573bc8 | |||
v1.0 | instruct | Docs | Docs: Scikit_49022_I | #### Objective:
To assess your understanding of implementing, profiling, and optimizing machine learning models using scikit-learn.
#### Task:
You are given a dataset and your task is to create a K-Nearest Neighbors (KNN) classifier. You need to implement the following steps:
1. Load the dataset.
2. Implement a KNN c... | import numpy as np
from sklearn.datasets import load_digits
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from joblib import Parallel, delayed
import time
import cProfile
import pstats
# Load dataset
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train,... | from solution import knn_classifier, profile_before_optimization, profile_after_optimization
def test_knn_classifier():
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
accuracy = knn_classifier(X_train, y_train, X_test, y_test, n... | [
{
"docstring": null,
"function_declaration": "def knn_classifier(X_train, y_train, X_test, y_test, n_neighbors=3):",
"function_name": "knn_classifier",
"parameter_list": "(X_train, y_train, X_test, y_test, n_neighbors=3)"
},
{
"docstring": null,
"function_declaration": "def profile(func)... | [
0,
1,
0,
0,
0,
0,
1,
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 numpy as np\nfrom sklearn.datasets import load_digits\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\n... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00049022",
"row_id": 49022,
"seed_ids": "[11]"
} | 0.567221 | Docs: Scikit_49022 | I | [
"knn_classifier",
"profile",
"profile_before_optimization",
"profile_after_optimization"
] | 4 | [
[
"profile_before_optimization",
"knn_classifier"
]
] | 1 | [] | false | [] | false | pytest | true | [
"joblib",
"numpy",
"sklearn"
] | false | c311a338fb33f4f1597975ed895b3ca8ea2b2b38 | c9694b7406a830d71a91bfb1f5301b355fa28b48 | |||
v1.0 | instruct | Docs | Docs: Pytorch_49081_I | #### Objective
Demonstrate your understanding of the `torch.futures` package by implementing a function that creates and manages multiple asynchronous tasks using `Future` objects.
#### Problem Statement
You are tasked with implementing a function `asynchronous_operations` that performs multiple asynchronous operation... | import torch.futures
from typing import List
import asyncio
async def simulate_complex_computation(value: int) -> int:
await asyncio.sleep(1) # Simulate delay
return value * value
def asynchronous_operations(n: int) -> List[int]:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
a... | from solution import asynchronous_operations
def test_asynchronous_operations_single_task():
result = asynchronous_operations(1)
assert result == [0], f"Expected [0], but got {result}"
def test_asynchronous_operations_multiple_tasks():
result = asynchronous_operations(3)
assert result == [0, 1, 4], f"... | [
{
"docstring": null,
"function_declaration": "def asynchronous_operations(n):",
"function_name": "asynchronous_operations",
"parameter_list": "(n)"
}
] | [
0,
0,
1,
1,
0,
0,
0,
1,
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.futures\nfrom typing import List\nimport asyncio\n\ndef simulate_complex_computation(value: int) -> torch.futures.Future:\n loop = asyncio.get_event_loo... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00049081",
"row_id": 49081,
"seed_ids": "[53]"
} | 0.552234 | Docs: Pytorch_49081 | I | [
"simulate_complex_computation",
"asynchronous_operations"
] | 2 | [
[
"asynchronous_operations",
"simulate_complex_computation"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 95fad0bbccb872505e6683339185ab70170ec1fa | bf02969d2f54b4b7b6667dcaffdd9af705f41cc5 | |||
v1.0 | instruct | Docs | Docs: Python310_49141_I | **Background:**
You are tasked with creating a log processing system. The logs are provided in various formats, and your function needs to be able to handle these formats using Python's pattern matching features. Furthermore, some logs might contain errors, and your function should handle these gracefully using except... | import asyncio
class DummyAsyncContextManager:
async def __aenter__(self):
await asyncio.sleep(0) # Simulate some delay
return self
async def __aexit__(self, exc_type, exc, tb):
await asyncio.sleep(0) # Simulate some delay
async def process_log_entry(log_entry):
try:
mat... | import asyncio
from solution import process_logs
def test_process_logs():
log_entries = [
{'type': 'error', 'content': 'Failed to connect to server'},
('warning', 'Low disk space'),
'User logged in',
{'type': 'info', 'content': 'System rebooted'},
('debug', 'Variable x = 10'... | [] | [
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\n\nclass DummyAsyncContextManager:\n async def __aenter__(self):\n await asyncio.sleep(0.1)\n return self\n\n async def __aexit__(sel... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049141",
"row_id": 49141,
"seed_ids": "[96]"
} | 0.724606 | Docs: Python310_49141 | I | [
"process_log_entry",
"process_logs"
] | 2 | [
[
"process_logs",
"process_log_entry"
]
] | 1 | [] | false | [
"DummyAsyncContextManager"
] | true | pytest | true | [] | true | c7d2a448fd07e10882ae822a45587af50ee9f0b3 | 12ef5b50054601a8dbba8c6590393395a7e62419 | |||
v1.0 | instruct | Docs | Docs: Pytorch_49184_I | ### PyTorch Coding Assessment Question
You are required to demonstrate your understanding of tensor creation, manipulation, and validation using PyTorch. Leverage the `torch.testing` module to create and validate tensors.
#### Task:
1. **Create a function `generate_tensor`**:
- Input: A tuple specifying the shape... | import torch
def generate_tensor(shape):
"""
Generates a tensor of the specified shape with random values.
"""
return torch.randn(shape)
def close_tensors(tensor_a, tensor_b, rtol=1e-05, atol=1e-08):
"""
Checks if two tensors are close within the specified tolerances.
Parameters:
... | from solution import generate_tensor, close_tensors, test_tensor_creation
import torch
def test_generate_tensor():
# Test if the generated tensor has the correct shape
shape = (3, 4)
tensor = generate_tensor(shape)
assert tensor.shape == shape, f"Tensor shape should be {shape}, but got {tensor.shape}"
... | [
{
"docstring": "Generates a tensor of the specified shape with random values.",
"function_declaration": "def generate_tensor(shape):",
"function_name": "generate_tensor",
"parameter_list": "(shape)"
},
{
"docstring": "Checks if two tensors are close within the specified tolerances.\n\nParame... | [
1,
1,
1,
1,
0,
1,
0,
0,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef generate_tensor(shape):\n \"\"\"\n Generates a tensor of the specified shape with random values.\n \"\"\"\n return torch.rand(shape)\n\n... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00049184",
"row_id": 49184,
"seed_ids": "[128]"
} | 0.528322 | Docs: Pytorch_49184 | I | [
"generate_tensor",
"close_tensors",
"test_tensor_creation"
] | 3 | [
[
"test_tensor_creation",
"close_tensors"
],
[
"test_tensor_creation",
"generate_tensor"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 460d9d956d2a9bdf36558ee4e087c37b847d4c28 | 64ede71e1c410a7af9370e413ac6665225b0c6dd | |||
v1.0 | instruct | Docs | Docs: Python310_49196_I | **Concurrency Challenge with asyncio**
**Objective:**
Implement an asynchronous system using the `asyncio` library to manage multiple clients connecting to a server. Each client will send a message, and the server will process these messages concurrently, then return a response to each client.
**Problem Statement:**
... | import asyncio
async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
try:
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} from {addr!r}")
response = f"{message} - pro... | import asyncio
from solution import handle_client, start_server, client
async def test_handle_client():
reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
writer.write(b'Hello Test!')
await writer.drain()
data = await reader.read(100)
assert data.decode() == "Hello Test! - ... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"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: asyncio.StreamReader, writer: asyncio.StreamWriter):\n try:\n data = await reader.read(100)\n message... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00049196",
"row_id": 49196,
"seed_ids": "[270]"
} | 0.572018 | Docs: Python310_49196 | I | [
"handle_client",
"start_server",
"client"
] | 3 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4a3e2fbda9618725aaa34cca92e570d5d635a759 | b809f844800e25001a0cecb43fa440ff5b5b9571 | |||
v1.0 | instruct | Docs | Docs: Python310_49256_I | ### Objective
Design and implement a secure file integrity checker using Python's cryptographic services.
### Problem Statement
You are tasked with creating a Python function that securely computes and verifies the hash of a file's content to detect any unauthorized modifications. Use `hashlib` for hashing the file's ... | import hashlib
import hmac
def generate_file_hash(filepath: str, key: str) -> str:
"""
Generates an HMAC hash of the file's contents using SHA-256.
Args:
- filepath (str): The path to the file.
- key (str): The secret key for HMAC.
Returns:
- str: The hexadecimal HMAC hash of the file's c... | import pytest
from solution import generate_file_hash, verify_file_hash
def create_test_file(filepath, contents):
with open(filepath, 'w') as f:
f.write(contents)
def test_generate_file_hash():
filepath = 'test.txt'
key = 'supersecretkey'
create_test_file(filepath, 'Hello, World!')
ha... | [
{
"docstring": "Generates an HMAC hash of the file's contents using SHA-256.\n\nArgs:\n- filepath (str): The path to the file.\n- key (str): The secret key for HMAC.\n\nReturns:\n- str: The hexadecimal HMAC hash of the file's contents.",
"function_declaration": "def generate_file_hash(filepath, key):",
... | [
1,
1,
0,
0,
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 hashlib\nimport hmac\n\ndef generate_file_hash(filepath: str, key: str) -> str:\n \"\"\"\n Generates an HMAC hash of the file's contents using SHA-256.\n\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00049256",
"row_id": 49256,
"seed_ids": "[394]"
} | 0.704001 | Docs: Python310_49256 | I | [
"generate_file_hash",
"verify_file_hash"
] | 2 | [
[
"verify_file_hash",
"generate_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7e243fd44b2c458ed025f8fd75e390ec573bf2dd | 3db1581c458abef802ff0bd419cd5e818daad850 | |||
v1.0 | instruct | Docs | Docs: Scikit_49257_I | ### Isotonic Regression with scikit-learn
You are given a dataset with 1-dimensional feature data `X` and corresponding target values `y`. Your task is to create an isotonic regression model using `scikit-learn`'s `IsotonicRegression` class and evaluate its performance on both the training data and a set of new test d... | import numpy as np
from sklearn.isotonic import IsotonicRegression
from typing import Union, Dict
def train_isotonic_regression(X_train: np.ndarray, y_train: np.ndarray, increasing: Union[bool, str]) -> IsotonicRegression:
"""
Trains an Isotonic Regression model on the given data with the specified monotonic c... | import pytest
import numpy as np
from solution import train_isotonic_regression, predict_isotonic_regression, evaluate_performance, experiment_with_constraints
def test_train_isotonic_regression():
X_train = np.array([1, 2, 3, 4, 5])
y_train = np.array([1, 4, 3, 8, 10])
model = train_isotonic_regression(X_... | [
{
"docstring": "Trains an Isotonic Regression model on the given data with the specified monotonic constraint.\n\nParameters:\nX_train (numpy.ndarray): 1D array of feature data.\ny_train (numpy.ndarray): 1D array of target values.\nincreasing (bool or str): Monotonic constraint ('True', 'False', or 'auto').\n\n... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.isotonic import IsotonicRegression\nfrom typing import Union, Dict\n\ndef train_isotonic_regression(X_train: np.ndarray, y_train: np.nd... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00049257",
"row_id": 49257,
"seed_ids": "[48]"
} | 0.656945 | Docs: Scikit_49257 | I | [
"train_isotonic_regression",
"predict_isotonic_regression",
"evaluate_performance",
"experiment_with_constraints"
] | 4 | [
[
"experiment_with_constraints",
"predict_isotonic_regression"
],
[
"experiment_with_constraints",
"train_isotonic_regression"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 1090564de81a5ea5136e69b3bae4fb101a9fb238 | f1022ce2acd353a933986356f536a38cdd547722 | |||
v1.0 | instruct | Docs | Docs: Python310_49275_I | **Question: Asynchronous URL Fetcher with Error Detection and Logging**
**Objective**: Implement an asynchronous URL fetcher using Python's asyncio module that fetches a list of URLs concurrently, handles errors robustly, and logs the process efficiently.
### Task
You are required to:
1. **Fetch URLs Concurrently**... | import asyncio
import aiohttp
import logging
from typing import List, Tuple
logging.basicConfig(level=logging.DEBUG)
async def fetch_url(session: aiohttp.ClientSession, url: str) -> Tuple[str, str]:
"""
Fetch the content of the given URL.
Args:
- session: aiohttp ClientSession object for making H... | import asyncio
from solution import fetch_url, fetch_urls, main
import pytest
import aiohttp
def test_fetch_url_success():
async def async_test():
async with aiohttp.ClientSession() as session:
url, response = await fetch_url(session, "https://www.example.com")
assert url == "https:... | [
{
"docstring": "Main function to set up asyncio environment and run the fetch tasks.\n\nArgs:\n- urls: A list of URLs to fetch.",
"function_declaration": "def main(urls):",
"function_name": "main",
"parameter_list": "(urls)"
}
] | [
1,
1,
0,
1,
1,
0,
1,
0,
0,
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 aiohttp\nimport logging\nfrom typing import List, Tuple\n\n# Setup logging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00049275",
"row_id": 49275,
"seed_ids": "[200]"
} | 0.588045 | Docs: Python310_49275 | I | [
"fetch_url",
"fetch_urls",
"main"
] | 3 | [
[
"fetch_urls",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 84d7d7354996e7164aa07b92f8fa7cb91a41971a | 2a20c55a910283ba9e1743c07fe51ec57cf3d16e | |||
v1.0 | instruct | Docs | Docs: Python310_49298_I | ### Compression and Decompression using zlib
You are tasked with designing a system that efficiently stores and retrieves large text documents. The system will compress the documents before storage and decompress them when retrieval is needed. To ensure the integrity of the documents, you will also compute and verify ... | import zlib
def compress_document(data, compression_level=-1):
"""
Compresses the input text document.
Parameters:
- data (str): The text document to be compressed.
- compression_level (int, optional): The level of compression (0-9). Defaults to -1.
Returns:
- bytes: Compressed da... | from solution import compress_document, decompress_document, compute_checksum, verify_checksum
def test_compress_decompress():
original_text = "This is a sample text document that needs to be compressed and decompressed."
compression_level = 6
compressed_data = compress_document(original_text, compres... | [
{
"docstring": "Compresses the input text document.\n\nParameters:\n- data (str): The text document to be compressed.\n- compression_level (int, optional): The level of compression (0-9). Defaults to -1.\n\nReturns:\n- bytes: Compressed data.",
"function_declaration": "def compress_document(data, compressio... | [
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 zlib\n\ndef compress_document(data, compression_level=-1):\n \"\"\"\n Compress the given text using zlib.\n Args:\n - data (str): The text document t... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00049298",
"row_id": 49298,
"seed_ids": "[299]"
} | 0.558358 | Docs: Python310_49298 | I | [
"compress_document",
"decompress_document",
"compute_checksum",
"verify_checksum"
] | 4 | [
[
"verify_checksum",
"compute_checksum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6f26c107a76eb5fc0db88fcc264f66d6f750b711 | 859c655897be9c715b04599fc64b398c491cf283 | |||
v1.0 | instruct | Docs | Docs: Python310_49301_I | Multi-threaded Task Manager
### Objective:
You are required to implement a multi-threaded task manager utilizing the `queue` module. Your solution must demonstrate a comprehensive understanding of various queue types and threading mechanisms in Python.
### Task Description:
Write a Python program that implements thre... | import queue
from threading import Thread, current_thread
import time
import random
class Task:
def __init__(self, task_id, task_type, priority=0):
self.task_id = task_id
self.task_type = task_type
self.priority = priority
def __str__(self):
return f"Task({self.task_id}, {self.... | import pytest
from threading import Thread
from solution import Task, add_task, producer, consumer, fifo_queue, lifo_queue, priority_queue
def test_task_creation():
task = Task(1, "FIFO")
assert task.task_id == 1
assert task.task_type == "FIFO"
assert task.priority == 0
assert str(task) == "Task(1,... | [] | [
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 queue\nfrom threading import Thread, Lock\nimport time\nimport random\n\nclass Task:\n def __init__(self, task_id, task_type, priority=0):\n self.task_... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049301",
"row_id": 49301,
"seed_ids": "[332]"
} | 0.649613 | Docs: Python310_49301 | I | [
"add_task",
"producer",
"consumer",
"start_threads"
] | 4 | [
[
"producer",
"add_task"
]
] | 1 | [] | false | [
"Task"
] | true | pytest | true | [] | true | 887512cd570f8948bc3738455b63006ca0fce31f | b4405a12bc8fe1943057c5155c9c7ebe5b7d961a | |||
v1.0 | instruct | Docs | Docs: Python310_49315_I | ### Secure Communication System
**Objective:**
Your task is to implement a secure communication system using Python's `hashlib` module. This system involves creating, sending, and verifying messages that have been securely hashed and authenticated.
### Requirements:
1. **Functionality:**
- **Message Hashing and... | import hashlib
def sign_message(message: str, secret_key: bytes, personalization: str = "") -> bytes:
"""
Returns a secure hash of the message using the secret key and optional personalization string.
"""
if len(secret_key) < 16:
raise ValueError("Secret key must be at least 16 bytes long.")
... | from solution import sign_message, verify_message
def test_sign_message_valid():
message = "Hello, World!"
key = b'secure_key_123456'
personalization = "test"
hashed = sign_message(message, key, personalization)
assert isinstance(hashed, bytes)
assert len(hashed) == 32
def test_sign_message_sh... | [
{
"docstring": "Returns a secure hash of the message using the secret key and optional personalization string.",
"function_declaration": "def sign_message(message, secret_key, personalization=''):",
"function_name": "sign_message",
"parameter_list": "(message, secret_key, personalization='')"
},
... | [
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 hashlib\n\ndef sign_message(message: str, secret_key: bytes, personalization: str = \"\") -> bytes:\n if len(secret_key) < 16:\n raise ValueError(\"The... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049315",
"row_id": 49315,
"seed_ids": "[394]"
} | 0.746699 | Docs: Python310_49315 | I | [
"sign_message",
"verify_message"
] | 2 | [
[
"verify_message",
"sign_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e87fa9e8eb990bee9efcafb71756cc2aabe27e72 | db9379756fa65f29cb97fba8c851c743d4237388 | |||
v1.0 | instruct | Docs | Docs: Python310_49316_I | **Objective**: Demonstrate your understanding of concurrent execution using the `concurrent.futures` module.
**Problem Statement**:
You are given a list of URLs, and your task is to concurrently download the content of these URLs using both threading and future objects from the `concurrent.futures` module. Implement ... | from typing import List, Dict, Union
import concurrent.futures
import urllib.request
import urllib.error
def download_page(url: str) -> Union[bytes, str]:
try:
with urllib.request.urlopen(url, timeout=10) as response:
return response.read()
except Exception as e:
return f"Error: {st... | from solution import download_pages
def test_download_pages_success():
# Note: This URL should remain accessible for the test to pass.
urls = ["http://www.example.com/"]
results = download_pages(urls, max_workers=3)
assert "http://www.example.com/" in results
assert isinstance(results["http://www.e... | [
{
"docstring": null,
"function_declaration": "def download_page(url):",
"function_name": "download_page",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def download_pages(urls, max_workers):",
"function_name": "download_pages",
"parameter_list": "(url... | [
0,
1,
1,
1,
0,
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": "from typing import List, Dict, Union\nimport concurrent.futures\nimport urllib.request\nimport urllib.error\n\ndef download_pages(urls: List[str], max_workers: int) -> ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049316",
"row_id": 49316,
"seed_ids": "[347]"
} | 0.517037 | Docs: Python310_49316 | I | [
"download_page",
"download_pages"
] | 2 | [
[
"download_pages",
"download_page"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 76bf20406aa78061a6541313b0e6566d916712c7 | 4d7255c9b1162afc79cee03db1b3b5b52420b1db | |||
v1.0 | instruct | Docs | Docs: Python310_49328_I | ### Asynchronous Task Manager using asyncio
You are required to design an asynchronous task manager that can handle multiple tasks concurrently while considering platform-specific limitations discussed in the `asyncio` documentation provided.
#### Task Description
1. Implement an asynchronous function called `fetch_... | import aiohttp
import asyncio
import platform
async def fetch_data(url):
"""
Fetch data from the given URL using asynchronous HTTP request.
Args:
url (str): The URL to fetch data from.
Returns:
str: The text content of the HTTP response.
"""
async with aiohttp.ClientSession() as sessi... | import pytest
from solution import fetch_data, manage_tasks
import asyncio
@pytest.mark.asyncio
async def test_fetch_data():
url = "http://example.com"
response_text = await fetch_data(url)
assert response_text is not None
assert isinstance(response_text, str)
@pytest.mark.asyncio
async def test_manag... | [] | [
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": "import aiohttp\nimport asyncio\n\nasync def fetch_data(url: str) -> str:\n \"\"\"\n Asynchronously fetches data from the given URL using aiohttp.\n \"\"\"\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049328",
"row_id": 49328,
"seed_ids": "[370]"
} | 0.517005 | Docs: Python310_49328 | I | [
"fetch_data",
"manage_tasks"
] | 2 | [
[
"manage_tasks",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | b02de5f3917f34461f4f37fdc2cd2731c0d10ec5 | 94382114cbe81655af36051fc8da5babae024b9d | |||
v1.0 | instruct | Docs | Docs: Pytorch_49388_I | ### Advanced Coding Assessment Question:
Implementing causal attention masking is crucial for sequence models, especially in tasks like language generation where future tokens should not influence current predictions. Using PyTorch, construct a function that integrates causal bias into a provided attention score matri... | import torch
def causal_lower_right(sequence_length):
""" Generates a lower triangular matrix mask for causal attention. """
mask = torch.tril(torch.ones(sequence_length, sequence_length))
return mask
def causal_upper_left(sequence_length):
""" Generates an upper triangular matrix mask for causal atte... | import torch
import pytest
from solution import apply_causal_mask
def test_apply_causal_mask_lower_right():
attention_scores = torch.ones(4, 4)
masked_scores = apply_causal_mask(attention_scores, 'lower_right')
expected_masked_scores = torch.tensor([[1, -1e9, -1e9, -1e9],
... | [
{
"docstring": "Generates a lower triangular matrix mask for causal attention. ",
"function_declaration": "def causal_lower_right(sequence_length):",
"function_name": "causal_lower_right",
"parameter_list": "(sequence_length)"
},
{
"docstring": "Generates an upper triangular matrix mask for ... | [
0,
1,
0,
1,
1,
1,
0,
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\n\ndef causal_lower_right(sequence_length):\n \"\"\"\n Generates a lower-righthand causal mask.\n \"\"\"\n mask = torch.tril(torch.ones(sequenc... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049388",
"row_id": 49388,
"seed_ids": "[31]"
} | 0.448294 | Docs: Pytorch_49388 | I | [
"causal_lower_right",
"causal_upper_left",
"apply_causal_mask"
] | 3 | [
[
"apply_causal_mask",
"causal_lower_right"
],
[
"apply_causal_mask",
"causal_upper_left"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 23424c8cdc3131abcbb7b371c426c7c96faff93e | d107478ef847c08b6940fda925183117a904742a | |||
v1.0 | instruct | Docs | Docs: Pytorch_49396_I | ### Advanced PyTorch Assessment Task: Custom Kernel Performance Analysis
#### Objective
In this assessment, you are required to create and analyze the performance of a custom GPU kernel using PyTorch and TorchInductor. This task will test your ability to implement backend optimizations using PyTorch's advanced profili... | import torch
import torch.cuda.profiler as profiler
def pointwise_kernel(a, b):
"""
Perform element-wise multiplication of two tensors a and b.
"""
return a * b
def benchmark_pointwise_kernel(a, b):
"""
Benchmark the pointwise kernel using torch.cuda.profiler and time measurement.
"""
... | from solution import pointwise_kernel, benchmark_pointwise_kernel
import torch
def test_pointwise_kernel_shape():
a = torch.randn(5, 5).cuda()
b = torch.randn(5, 5).cuda()
result = pointwise_kernel(a, b)
assert result.shape == (5, 5), "Shape mismatch."
def test_pointwise_kernel_values():
a = torch... | [
{
"docstring": "Perform element-wise multiplication of two tensors a and b.",
"function_declaration": "def pointwise_kernel(a, b):",
"function_name": "pointwise_kernel",
"parameter_list": "(a, b)"
},
{
"docstring": "Benchmark the pointwise kernel using torch.cuda.profiler and time measuremen... | [
0,
0,
0,
0,
1,
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\n\ndef pointwise_kernel(a, b):\n \"\"\"\n Element-wise multiplication of two tensors using GPU acceleration.\n \"\"\"\n if a.device.type != 'cu... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00049396",
"row_id": 49396,
"seed_ids": "[15]"
} | 0.437672 | Docs: Pytorch_49396 | I | [
"pointwise_kernel",
"benchmark_pointwise_kernel"
] | 2 | [
[
"benchmark_pointwise_kernel",
"pointwise_kernel"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 7857b8f9e4945e6c8b28cce02efbed746438498b | 650a8a78ca27169df82194963e038989bd29b795 | |||
v1.0 | instruct | Docs | Docs: Scikit_49409_I | ### Semi-Supervised Learning with Scikit-Learn
You are tasked with implementing a semi-supervised learning pipeline to classify data using scikit-learn's `LabelPropagation` model. Your implementation must work with both numeric and categorical data and must be able to handle missing labels in the dataset. Follow the s... | import numpy as np
import pandas as pd
from sklearn.datasets import load_digits
from sklearn.semi_supervised import LabelPropagation
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def prepare_data():
digits = load_dig... | import pytest
from solution import prepare_data, preprocess_data, train_model, evaluate_model, semi_supervised_learning_pipeline
def test_prepare_data():
X, y = prepare_data()
# Check that the length of features matches the length of labels
assert len(X) == len(y)
# Check if some labels are set to -1
... | [
{
"docstring": null,
"function_declaration": "def prepare_data():",
"function_name": "prepare_data",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def preprocess_data(X, y):",
"function_name": "preprocess_data",
"parameter_list": "(X, y)"
},
{
"d... | [
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 numpy as np\nimport pandas as pd\nfrom sklearn.datasets import load_digits\nfrom sklearn.semi_supervised import LabelPropagation\nfrom sklearn.metrics import acc... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049409",
"row_id": 49409,
"seed_ids": "[21]"
} | 0.497863 | Docs: Scikit_49409 | I | [
"prepare_data",
"preprocess_data",
"train_model",
"evaluate_model",
"semi_supervised_learning_pipeline"
] | 5 | [
[
"semi_supervised_learning_pipeline",
"evaluate_model"
],
[
"semi_supervised_learning_pipeline",
"prepare_data"
],
[
"semi_supervised_learning_pipeline",
"preprocess_data"
],
[
"semi_supervised_learning_pipeline",
"train_model"
]
] | 4 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 25fcfd30c2c51a3f230d39b400dd4f8d18cd6079 | 9feb73e67d2fe7748c571049ef50908f2b773ae2 | |||
v1.0 | instruct | Docs | Docs: Scikit_49426_I | ### Objective
Implement custom functions to compute specific distance metrics and kernel functions manually, then validate your implementations using `sklearn.metrics.pairwise` submodule.
### Task
1. Implement the following functions:
- `custom_manhattan_distance(X, Y)`: Compute the Manhattan distance matrix betwe... | import numpy as np
def custom_manhattan_distance(X, Y):
"""
Compute the Manhattan distance matrix between two sets of vectors X and Y.
Parameters:
X (numpy.ndarray): A 2D array of shape (n_samples_X, n_features)
Y (numpy.ndarray): A 2D array of shape (n_samples_Y, n_features)
Returns:
num... | import pytest
import numpy as np
from solution import custom_manhattan_distance, custom_linear_kernel, validate_implementations
def test_custom_manhattan_distance():
X = np.array([[1, 2], [3, 4]])
Y = np.array([[5, 6], [7, 8]])
result = custom_manhattan_distance(X, Y)
expected = np.array([[8, 12],
... | [
{
"docstring": "Compute the Manhattan distance matrix between two sets of vectors X and Y.\n\nParameters:\nX (numpy.ndarray): A 2D array of shape (n_samples_X, n_features)\nY (numpy.ndarray): A 2D array of shape (n_samples_Y, n_features)\n\nReturns:\nnumpy.ndarray: A 2D array of shape (n_samples_X, n_samples_Y)... | [
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 numpy as np\n\ndef custom_manhattan_distance(X, Y):\n \"\"\"\n Compute the Manhattan distance matrix between two sets of vectors X and Y.\n\n Parameters... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049426",
"row_id": 49426,
"seed_ids": "[38]"
} | 0.570257 | Docs: Scikit_49426 | I | [
"custom_manhattan_distance",
"custom_linear_kernel",
"validate_implementations"
] | 3 | [
[
"validate_implementations",
"custom_linear_kernel"
],
[
"validate_implementations",
"custom_manhattan_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 0851423267a1478915d8bd9c0a7a78a885ac15cf | 5c5c47f03e7dc73c8de6734b4659a6691247b63c | |||
v1.0 | instruct | Docs | Docs: Python310_49428_I | #### Objective:
To assess your understanding of asynchronous programming with `asyncio` in Python 3.10, including handling concurrency, thread safety, dealing with blocking code, and implementing robust error handling.
#### Problem Statement:
You are required to implement a small application that simulates a simplifie... | import asyncio
import logging
from typing import List
# Initialize logger
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
class NoSeatsAvailableException(Exception):
def __init__(self, user_id: int, message: str = "No seats available"):
self.user_id = user_id
super().... | import asyncio
import pytest
from solution import book_seat, booking_system, NoSeatsAvailableException
@pytest.mark.asyncio
async def test_booking_system_with_less_than_50_users():
booked_users = await booking_system(30)
assert len(booked_users) == 30
assert booked_users == list(range(30))
@pytest.mark.as... | [] | [
1,
1,
1,
0,
1,
1,
1,
0,
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\nimport logging\nfrom typing import List\n\nclass NoSeatsAvailableException(Exception):\n def __init__(self, user_id: int, message: str = \"No seats a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049428",
"row_id": 49428,
"seed_ids": "[200]"
} | 0.488181 | Docs: Python310_49428 | I | [
"book_seat",
"booking_system"
] | 2 | [
[
"booking_system",
"book_seat"
]
] | 1 | [] | false | [
"NoSeatsAvailableException"
] | true | pytest | true | [] | true | c2aa9e73a8afe2f0f0e84d03c483dca4575ec53d | 985ee6b7ad0f0a90f7963ea4220443c5c379913a | |||
v1.0 | instruct | Docs | Docs: Python310_49519_I | ### Task:
You are tasked with creating a script that spawns subprocesses and communicates with them asynchronously using the `asyncio` module. Your script should be compatible with both Windows and macOS platforms.
Implement a function `run_subprocess_tasks(commands: List[str]) -> None` that takes a list of command s... | import asyncio
import platform
from typing import List
async def run_subprocess_command(command: str):
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
... | import asyncio
from solution import run_subprocess_tasks
def test_run_single_command():
commands = ["echo Hello, World!"]
run_subprocess_tasks(commands)
def test_run_multiple_commands():
commands = ["echo Test 1", "echo Test 2", "echo Test 3"]
run_subprocess_tasks(commands)
def test_run_invalid_comma... | [
{
"docstring": null,
"function_declaration": "def run_subprocess_tasks(commands):",
"function_name": "run_subprocess_tasks",
"parameter_list": "(commands)"
}
] | [
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\nimport platform\nfrom typing import List\n\nasync def run_subprocess_command(command: str):\n process = await asyncio.create_subprocess_shell(\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00049519",
"row_id": 49519,
"seed_ids": "[370]"
} | 0.726152 | Docs: Python310_49519 | I | [
"run_subprocess_command",
"run_subprocess_tasks"
] | 2 | [
[
"run_subprocess_tasks",
"run_subprocess_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9a9c02415eee6be9c83ffec65d83af5957cd1d0c | 94a1280c031e20e386ffa60f5b07a3e7e936203d | |||
v1.0 | instruct | Docs | Docs: Python310_49636_I | You are tasked with creating a Python program that manages a simple to-do list. Your program will read the current list of tasks from a file named `todo.txt` when it starts and automatically save any updates to the list when the program terminates. Additionally, you need to implement cleanup functions that remove cance... | import atexit
tasks = []
def load_tasks(file_name: str) -> list:
try:
with open(file_name, 'r') as file:
return file.read().splitlines()
except FileNotFoundError:
return []
def save_tasks(file_name: str, tasks: list):
with open(file_name, 'w') as file:
file.write('\n'.... | import os
import pytest
from solution import load_tasks, save_tasks, add_task, complete_task, cancel_task, save_all_pending_tasks
@pytest.fixture(autouse=True)
def setup_and_teardown():
# Setup code: create an empty todo.txt before each test
with open('todo.txt', 'w') as file:
file.write('')
y... | [
{
"docstring": null,
"function_declaration": "def load_tasks(file_name):",
"function_name": "load_tasks",
"parameter_list": "(file_name)"
},
{
"docstring": null,
"function_declaration": "def save_tasks(file_name, tasks):",
"function_name": "save_tasks",
"parameter_list": "(file_n... | [
0,
1,
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 atexit\n\ntasks = []\n\ndef load_tasks(file_name: str) -> list:\n \"\"\"\n Loads tasks from the given file and returns them as a list.\n \"\"\"\n try... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00049636",
"row_id": 49636,
"seed_ids": "[278]"
} | 0.543164 | Docs: Python310_49636 | I | [
"load_tasks",
"save_tasks",
"add_task",
"complete_task",
"cancel_task",
"save_all_pending_tasks"
] | 6 | [
[
"save_all_pending_tasks",
"save_tasks"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 632aec30de51db8a953b3c2abf29b85c24b815fd | c562628467896f7d3e0c5ed34890acbb44c984fd | |||
v1.0 | instruct | Docs | Docs: Scikit_49640_I | ### Clustering with K-Means and DBSCAN using Scikit-learn
In this assessment, you are required to perform clustering on a dataset using two different clustering algorithms provided by the Scikit-learn library: K-Means and DBSCAN. You will evaluate the performance of these algorithms based on a set of criteria and metr... | import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans, DBSCAN
from sklearn.metrics import silhouette_score
def generate_dataset():
"""
Generates a synthetic dataset with 1000 samples and 4 centers.
Returns:
X (np.ndarray): The generated samples.
... | from solution import generate_dataset, k_means_clustering, dbscan_clustering
def test_generate_dataset():
X, y = generate_dataset()
assert X.shape == (1000, 2)
assert len(y) == 1000
assert len(set(y)) == 4
def test_k_means_clustering():
X, _ = generate_dataset()
labels, inertia, silhouette = k... | [
{
"docstring": "Generates a synthetic dataset with 1000 samples and 4 centers.\n\nReturns:\n X (np.ndarray): The generated samples.\n y (np.ndarray): The true labels for the samples.",
"function_declaration": "def generate_dataset():",
"function_name": "generate_dataset",
"parameter_list": "()... | [
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 numpy as np\nfrom sklearn.datasets import make_blobs\nfrom sklearn.cluster import KMeans, DBSCAN\nfrom sklearn.metrics import silhouette_score\n\ndef generate_da... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00049640",
"row_id": 49640,
"seed_ids": "[60]"
} | 0.701933 | Docs: Scikit_49640 | I | [
"generate_dataset",
"k_means_clustering",
"dbscan_clustering",
"evaluate_clustering"
] | 4 | [
[
"evaluate_clustering",
"dbscan_clustering"
],
[
"evaluate_clustering",
"generate_dataset"
],
[
"evaluate_clustering",
"k_means_clustering"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 3048b392ec6be91776051cab815573a584805f7f | b676eb62b1b5c611b10bfee0e1336fef3f278374 | |||
v1.0 | instruct | Docs | Docs: Python310_49642_I | #### Objective:
Implementing and working with `ContextVar` and `Context` in the `contextvars` module to handle state management within asynchronous tasks.
#### Problem Statement:
You are tasked with implementing a server that maintains user sessions using context variables. Each session persists data about the client'... | import asyncio
import contextvars
from typing import List
# ContextVar declarations
username_var: contextvars.ContextVar[str] = contextvars.ContextVar('username')
operation_history_var: contextvars.ContextVar[List[str]] = contextvars.ContextVar('operation_history', default=[])
async def handle_session(username: str, ... | import asyncio
from solution import handle_session
def test_handle_session_single_user():
result = asyncio.run(handle_session("alice", ["login", "view_product", "logout"]))
assert result == ["alice:login", "alice:view_product", "alice:logout"]
def test_handle_session_another_single_user():
result = asynci... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
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 contextvars\n\n# ContextVar declarations\nusername_var: contextvars.ContextVar = contextvars.ContextVar('username')\noperation_history_var: conte... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00049642",
"row_id": 49642,
"seed_ids": "[392]"
} | 0.42007 | Docs: Python310_49642 | I | [
"handle_session",
"server"
] | 2 | [
[
"server",
"handle_session"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7fd137083e8aa5cedca02a0fdbcebb7a318bb026 | 3f390e0600342294b6b448472730ac3b1ba8bb4f | |||
v1.0 | instruct | Docs | Docs: Python310_49644_I | ### Question: Concurrent File Processing with Reporting
You are given a set of text files containing numerical data (one number per line). You need to process these files concurrently to compute specific statistics (sum and average of numbers) for each file. Additionally, you want to handle potential exceptions that m... | import concurrent.futures
from typing import List, Dict, Tuple, Union
def process_file(file_path: str) -> Union[Tuple[int, float], str]:
try:
with open(file_path, 'r') as file:
numbers = []
for line in file:
line = line.strip()
try:
... | import pytest
import os
from solution import process_files_concurrently
@pytest.fixture
def setup_files():
file_data = {
'file1.txt': "1\n2\n3\n",
'file2.txt': "4\n5\n",
'file3.txt': "invalid data"
}
for filename, content in file_data.items():
with open(filename, 'w') as f:
... | [
{
"docstring": null,
"function_declaration": "def process_file(file_path):",
"function_name": "process_file",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def process_files_concurrently(file_paths):",
"function_name": "process_files_concurrently",
... | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict, Tuple, Union\nfrom concurrent.futures import ThreadPoolExecutor\nimport os\n\ndef process_file(file_path: str) -> Union[Tuple[int, float]... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049644",
"row_id": 49644,
"seed_ids": "[347]"
} | 0.556754 | Docs: Python310_49644 | I | [
"process_file",
"process_files_concurrently"
] | 2 | [
[
"process_files_concurrently",
"process_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 54fd98b1c8d62884c184de9d7fb2d8f0ea601758 | d9e20cf33200a78ac864869a7b830a18c124aef8 | |||
v1.0 | instruct | Docs | Docs: Scikit_49658_I | **Objective:**
You are given a dataset `data.csv` containing a 2D dataset with numerical attributes. Your task is to implement a function that performs clustering using Gaussian Mixture Models (GMM) and then visualizes the clustering results along with the cluster centers and contour plots of the Gaussian components.
... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture
def gmm_clustering(file_path: str, n_components: int) -> None:
try:
# Load the dataset
data = pd.read_csv(file_path)
# Ensure the data has exactly 2 columns
as... | import os
import pandas as pd
from solution import gmm_clustering
# Helper function to create a temporary CSV file for testing
def create_test_csv(filepath, content):
df = pd.DataFrame(content, columns=["Feature1", "Feature2"])
df.to_csv(filepath, index=False)
return filepath
def test_gmm_clustering_basic... | [
{
"docstring": null,
"function_declaration": "def gmm_clustering(file_path, n_components):",
"function_name": "gmm_clustering",
"parameter_list": "(file_path, n_components)"
},
{
"docstring": "Helper function for plotting Gaussian contours",
"function_declaration": "def plot_gaussian_con... | [
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 pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.mixture import GaussianMixture\nfrom matplotlib.patches import Ellipse\nimport sy... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049658",
"row_id": 49658,
"seed_ids": "[3]"
} | 0.615031 | Docs: Scikit_49658 | I | [
"gmm_clustering",
"plot_gaussian_contour"
] | 2 | [
[
"gmm_clustering",
"plot_gaussian_contour"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"pandas",
"sklearn"
] | false | 833876b51b8d769d234ab9ab3260aec2fb3c7236 | 0f3176f58bfe51a5b784413fc682503617439161 | |||
v1.0 | instruct | Docs | Docs: Scikit_49718_I | #### Objective
Implement and apply the Partial Least Squares Regression (`PLSRegression`) method using scikit-learn to a given dataset. This will demonstrate your understanding of the method's principles, including the concepts of dimensionality reduction, projection, and regression.
#### Problem Statement
You are giv... | import numpy as np
import pandas as pd
from sklearn.cross_decomposition import PLSRegression
from sklearn.metrics import mean_squared_error
def load_data(file_X, file_Y):
X = pd.read_csv(file_X, header=None).values
Y = pd.read_csv(file_Y, header=None).values
return X, Y
def pls_regression(file_X, file_Y, ... | import pytest
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
from solution import pls_regression
# Test data
X_test = np.array([
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]
])
Y_test = np.array([
[1.0, 2.0],
[2.0, 3.0],
[3.0, 4.0]
])
# Save test da... | [
{
"docstring": null,
"function_declaration": "def load_data(file_X, file_Y):",
"function_name": "load_data",
"parameter_list": "(file_X, file_Y)"
},
{
"docstring": "Loads the datasets, applies PLSRegression, and returns MSE and predicted responses.\n\nArgs:\n- file_X (str): Path to the CSV f... | [
0,
1,
1,
1,
0,
0,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport pandas as pd\nfrom sklearn.cross_decomposition import PLSRegression\nfrom sklearn.metrics import mean_squared_error\n\ndef load_data(file_X, ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049718",
"row_id": 49718,
"seed_ids": "[28]"
} | 0.659357 | Docs: Scikit_49718 | I | [
"load_data",
"pls_regression"
] | 2 | [
[
"pls_regression",
"load_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | e9d71ddacfc99fc54c5a1ea8c122030011f22239 | 0f9ae1c8e940584a0971a92dd5ee88d64ea8309d | |||
v1.0 | instruct | Docs | Docs: Python310_49732_I | **Task: Implementing an Audio Echo Program using `ossaudiodev`**
### Description
You are required to implement a Python program that records audio from an input device, applies an echo effect, and plays the modified audio back through an output device using the `ossaudiodev` module.
### Requirements
1. **Recording*... | import ossaudiodev
import struct
import numpy as np
def audio_echo(input_device: str, output_device: str, duration: int) -> None:
"""
Records audio from the input_device for a given duration, applies an echo effect,
and plays it back through the output_device.
Args:
input_device (str): The pa... | import pytest
import numpy as np
from solution import add_echo
def test_add_echo():
sample_rate = 44100 # 44.1 kHz
duration = 1 # 1 second
delay = 0.5 # 0.5 second
attenuation = 0.6
# Generate a short sample of audio (1 second of a sine wave)
t = np.linspace(0, duration, int(sample_rate * d... | [
{
"docstring": "Records audio from the input_device for a given duration, applies an echo effect, \nand plays it back through the output_device.\n\nArgs:\n input_device (str): The path to the input audio device.\n output_device (str): The path to the output audio device.\n duration (int): The duration ... | [
1,
0,
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 ossaudiodev\nimport time\nimport struct\n\ndef audio_echo(input_device: str, output_device: str, duration: int) -> None:\n try:\n # Open input audio de... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00049732",
"row_id": 49732,
"seed_ids": "[127]"
} | 0.49602 | Docs: Python310_49732 | I | [
"audio_echo",
"add_echo"
] | 2 | [
[
"audio_echo",
"add_echo"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | e18863811b1c9b33392c681eedc9c92882fa0b63 | 3cb844d459a18e171b17981952596c434da711aa | |||
v1.0 | instruct | Docs | Docs: Python310_49736_I | **Title:** Advanced Itertools Operations
**Objective:**
Design a function that will process a dataset using various `itertools` functions to achieve a desired result. This will demonstrate your understanding and ability to leverage the power of the `itertools` module to perform efficient data manipulation and computat... | from itertools import compress, accumulate, tee
def pairwise(iterable):
"s -> (s0, s1), (s1, s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def complex_operations(data, selectors):
"""
Perform complex operations using itertools functions.
Args:
data: List ... | from solution import complex_operations
def test_complex_operations_basic():
data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
selectors = [True, False, True, True, False, True, False, True, True, False, True]
expected = [(3, 7), (7, 8), (8, 17), (17, 23), (23, 28), (28, 33)]
assert complex_operations(data, sel... | [
{
"docstring": "s -> (s0, s1), (s1, s2), (s2, s3), ...",
"function_declaration": "def pairwise(iterable):",
"function_name": "pairwise",
"parameter_list": "(iterable)"
},
{
"docstring": "Perform complex operations using itertools functions.\n\nArgs:\ndata: List of integers.\nselectors: List ... | [
1,
1,
1,
0,
1,
0,
1,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import compress, accumulate, tee\nfrom typing import List, Tuple\n\ndef complex_operations(data: List[int], selectors: List[bool]) -> List[Tuple[int, int... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00049736",
"row_id": 49736,
"seed_ids": "[152]"
} | 0.57761 | Docs: Python310_49736 | I | [
"pairwise",
"complex_operations"
] | 2 | [
[
"complex_operations",
"pairwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e9d8c04d4b71c29ace7b6969532c0fd8d63f8909 | e927f577ecd07a72fa19e8dac13d3003c7bcf635 | |||
v1.0 | instruct | Docs | Docs: Python310_49744_I | **Coding Assessment Question**
### Objective
Implement a custom encoding-decoding system using the functions from the provided python310 codec registry and support functions. This task will assess your understanding of the codec registration, encoding, decoding, and error handling.
### Task
1. Implement a function to... | import codecs
class CustomCodec(codecs.Codec):
def encode(self, input, errors='strict'):
return self._transform(input), len(input)
def decode(self, input, errors='strict'):
return self._transform(input), len(input)
def _transform(self, s):
result = []
for char in s... | import pytest
from solution import register_custom_codec, custom_encode, custom_decode
def setup_module(module):
register_custom_codec()
def test_custom_encode_simple():
assert custom_encode('HelloWorld') == 'hELLOwORLD'
def test_custom_encode_with_numbers():
assert custom_encode('HelloWorld123') == 'hEL... | [] | [
0,
1
] | 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 codecs\nimport string\n\n# Function to perform the custom encoding swap\ndef custom_encoder(input_str, errors='strict'):\n encoded = ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049744",
"row_id": 49744,
"seed_ids": "[47]"
} | 0.665173 | Docs: Python310_49744 | I | [
"custom_codec_search",
"register_custom_codec",
"custom_encode",
"custom_decode"
] | 4 | [
[
"register_custom_codec",
"custom_codec_search"
]
] | 1 | [] | false | [
"CustomCodec",
"CustomCodecIncrementalEncoder",
"CustomCodecIncrementalDecoder",
"CustomCodecStreamReader",
"CustomCodecStreamWriter"
] | true | pytest | true | [] | true | 49e4b24cd84bf66a471c66e1ddf5ae65f8ab3d03 | 85ff9c501bc67e61cdd746fcf21a98c2901f5ec5 | |||
v1.0 | instruct | Docs | Docs: Python310_49781_I | **Objective:**
Design a Python function that manages compression and extraction of various file formats using multiple modules provided. The function should demonstrate your understanding of `zlib`, `gzip`, `bz2`, `lzma`, and `zipfile` modules.
**Task:**
You are required to implement a function named `compress_and_e... | import os
import shutil
import zlib
import gzip
import bz2
import lzma
import zipfile
from pathlib import Path
def compress_and_extract(action: str, compression_type: str, source_path: str, destination_path: str, options: dict = None) -> None:
if action not in ["compress", "extract"]:
raise ValueError("Act... | import os
import pytest
import gzip
import shutil
from pathlib import Path
from solution import compress_and_extract
# Helper function to create a test file
def create_test_file(file_path, content):
with open(file_path, 'w') as f:
f.write(content)
def test_compress_extract_gzip(tmp_path):
source_file ... | [
{
"docstring": null,
"function_declaration": "def compress_and_extract(action, compression_type, source_path, destination_path, options=None):",
"function_name": "compress_and_extract",
"parameter_list": "(action, compression_type, source_path, destination_path, options=None)"
},
{
"docstrin... | [
0,
1,
1,
0,
0,
1,
1,
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 os\nimport zlib\nimport gzip\nimport bz2\nimport lzma\nimport zipfile\nimport shutil\n\ndef compress_and_extract(action: str, compression_type: str, source_path:... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049781",
"row_id": 49781,
"seed_ids": "[310]"
} | 0.664925 | Docs: Python310_49781 | I | [
"compress_and_extract",
"compress",
"compress_zlib",
"compress_gzip",
"compress_bz2",
"compress_lzma",
"compress_zip",
"extract",
"extract_zlib",
"extract_gzip",
"extract_bz2",
"extract_lzma",
"extract_zip"
] | 13 | [
[
"compress",
"compress_bz2"
],
[
"compress",
"compress_gzip"
],
[
"compress",
"compress_lzma"
],
[
"compress",
"compress_zip"
],
[
"compress",
"compress_zlib"
],
[
"compress_and_extract",
"compress"
],
[
"compress_and_extract",
"extrac... | 12 | [] | false | [] | false | pytest | true | [] | true | 9fc3c94d5d98a62a1adbeddcaca60e5a98ab2ecd | 0d390f48889be6d936197cbcef46c03213567b3f | |||
v1.0 | instruct | Docs | Docs: Scikit_49815_I | Analyzing Model Performance Using Validation and Learning Curves
**Objective**:
In this task, you will leverage the scikit-learn library to analyze the performance of a Support Vector Machine (SVM) classifier using validation and learning curves. You will implement functions to generate these curves, plot them, and in... | import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import validation_curve, learning_curve
def generate_validation_curve(X, y):
"""
Generates validation curve data for SVM with linear kernel over a range of C values.
Parameters:
- X: Features
... | from sklearn.datasets import load_iris
from sklearn.utils import shuffle
import numpy as np
# Assuming the functions are defined in a module named `solution`
from solution import generate_validation_curve, generate_learning_curve, plot_curves
def test_generate_validation_curve():
data = load_iris()
X, y = shu... | [
{
"docstring": "Generates validation curve data for SVM with linear kernel over a range of C values.\n\nParameters:\n- X: Features\n- y: Target\n\nReturns:\n- train_scores: Training scores for different C values.\n- valid_scores: Validation scores for different C values.",
"function_declaration": "def gener... | [
1,
0,
1,
0,
0,
0,
1,
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 numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import validation_curve, learning_curve\nfrom ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00049815",
"row_id": 49815,
"seed_ids": "[45]"
} | 0.613202 | Docs: Scikit_49815 | I | [
"generate_validation_curve",
"generate_learning_curve",
"plot_curves"
] | 3 | [
[
"plot_curves",
"generate_learning_curve"
],
[
"plot_curves",
"generate_validation_curve"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"sklearn"
] | false | 3a068daf8a1f7349c6c2b4dc2a3088491776d6e3 | eb3cf2157733205bc1f30a901c0dcae79887ecc7 | |||
v1.0 | instruct | Docs | Docs: Python310_49828_I | **Objective:**
Implement a module that keeps track of a startup sequence and a shutdown sequence of a program. Using the `atexit` module, ensure specific cleanup functions are executed at the program's normal termination.
### Requirements:
1. Create a Python module that maintains a log of startup and shutdown events.... | import atexit
from datetime import datetime
LOG_FORMAT = "{event_type}: {timestamp} - {message}\n"
def log_event(filename, event_type, message):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
try:
with open(filename, 'a') as file:
file.write(LOG_FORMAT.format(
eve... | import os
import pytest
from datetime import datetime
from solution import log_event, register_startup_log, register_shutdown_log, add_custom_shutdown, remove_custom_shutdown
def read_log_file(filename):
if not os.path.exists(filename):
return ""
with open(filename, 'r') as file:
return file.re... | [
{
"docstring": null,
"function_declaration": "def log_event(filename, event_type, message):",
"function_name": "log_event",
"parameter_list": "(filename, event_type, message)"
},
{
"docstring": null,
"function_declaration": "def register_startup_log():",
"function_name": "register_st... | [
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 atexit\nfrom datetime import datetime\n\nLOG_FORMAT = \"{event_type}: {timestamp} - {message}\\n\"\n\ndef log_event(filename, event_type, message):\n timestam... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00049828",
"row_id": 49828,
"seed_ids": "[278]"
} | 0.443768 | Docs: Python310_49828 | I | [
"log_event",
"register_startup_log",
"register_shutdown_log",
"add_custom_shutdown",
"remove_custom_shutdown",
"custom_goodbye"
] | 6 | [
[
"custom_goodbye",
"log_event"
],
[
"register_shutdown_log",
"log_event"
],
[
"register_startup_log",
"log_event"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | dc49be445a9ec72e5e19b62cff299460fb7c3620 | 540a2434ca10965ea7fe80df2c5f571c0c214ba4 | |||
v1.0 | instruct | Docs | Docs: Python310_49831_I | **Title:** Implement and Monitor Multiple Audit Events Using Python
**Objective:**
Design a program that triggers multiple audit events and adds an audit hook to monitor these events.
**Task Description:**
1. Write a function named `trigger_audit_events` that performs the following:
- Creates a new array using `ar... | import sys
import array
import os
audit_log = []
def audit_hook(event, args):
audit_log.append((event, args))
def trigger_audit_events():
# Add the audit hook
sys.addaudithook(audit_hook)
# Trigger array.__new__ audit event
arr = array.array('i', [1, 2, 3])
# Trigger compile audit event
... | from solution import trigger_audit_events, audit_log
def test_trigger_audit_events():
logged_events = trigger_audit_events()
# Check that we have logged all events
assert len(logged_events) >= 3
# Check that we have specific events logged
array_new_event = any(event[0] == 'array.__new__' for even... | [
{
"docstring": null,
"function_declaration": "def audit_hook(event, args):",
"function_name": "audit_hook",
"parameter_list": "(event, args)"
},
{
"docstring": null,
"function_declaration": "def trigger_audit_events():",
"function_name": "trigger_audit_events",
"parameter_list": ... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\n\n# Initialize the audit log list\naudit_log = []\n\ndef audit_hook(event, args):\n \"\"\"\n Logs the occurrence of audit events to audit_log.\n \"... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00049831",
"row_id": 49831,
"seed_ids": "[167]"
} | 0.509975 | Docs: Python310_49831 | I | [
"audit_hook",
"trigger_audit_events"
] | 2 | [
[
"trigger_audit_events",
"audit_hook"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cfdf613e19929ba6429b4804f82f91278646d201 | 7c3309a8819fe717b965394173e6514be4179250 | |||
v1.0 | instruct | Docs | Docs: Pytorch_49941_I | ### PyTorch Broadcasting Challenge
In this coding challenge, you are required to implement two functions related to PyTorch's broadcasting semantics.
#### Function 1: `are_broadcastable`
Implement a function `are_broadcastable(x: torch.Tensor, y: torch.Tensor) -> bool`, which takes two tensors `x` and `y` as input a... | import torch
def are_broadcastable(x: torch.Tensor, y: torch.Tensor) -> bool:
"""
Checks if two tensors are broadcastable according to PyTorch's broadcasting rules.
"""
x_shape = list(x.shape)
y_shape = list(y.shape)
# Reverse the shapes to compare from the last dimensions first
x_shap... | import torch
from solution import are_broadcastable, broadcast_tensors
def test_are_broadcastable_same_shape():
x = torch.empty(4, 3)
y = torch.empty(4, 3)
assert are_broadcastable(x, y) == True
def test_are_broadcastable_different_shapes():
x = torch.empty(5, 1, 4, 1)
y = torch.empty(3, 1, 1)
... | [
{
"docstring": "Checks if two tensors are broadcastable according to PyTorch's broadcasting rules.",
"function_declaration": "def are_broadcastable(x, y):",
"function_name": "are_broadcastable",
"parameter_list": "(x, y)"
},
{
"docstring": "Sums two tensors after broadcasting them if possibl... | [
1,
1,
1,
1,
0,
0,
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": "import torch\n\ndef are_broadcastable(x: torch.Tensor, y: torch.Tensor) -> bool:\n \"\"\"\n Check if two tensors can be broadcasted according to PyTorch's broadca... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049941",
"row_id": 49941,
"seed_ids": "[163]"
} | 0.470184 | Docs: Pytorch_49941 | I | [
"are_broadcastable",
"broadcast_tensors"
] | 2 | [
[
"broadcast_tensors",
"are_broadcastable"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 5a436e74e78f6bcb74a71dfce75bdb887a546641 | 4c991a6bd060eb7ae3f74670728fcff6a06b8d80 | |||
v1.0 | instruct | Filter | Filter_12_I | ### Create a Python program that uses the built-in `csv` module to read a CSV file named `data.csv` in the current directory, and then find the row(s) with the maximum value in the specified column (let's say the 3rd column, index 2). The program should handle cases where there are multiple rows with the maximum value.... | import csv
def find_max_value_rows_in_chunks(file_path, column_index, chunk_size=100):
"""
Finds the row(s) with the maximum value in the specified column by processing rows in chunks.
Args:
- file_path (str): Path to the CSV file.
- column_index (int): The index of the column to find the maximum ... | from solution import find_max_value_rows_in_chunks
def test_find_max_value_rows_single_max():
with open('test.csv', 'w') as f:
f.write("1,2,3\n4,5,6\n7,8,9\n")
assert find_max_value_rows_in_chunks('test.csv', 2) == [['7','8','9']]
def test_find_max_value_rows_multiple_max():
with open('test.csv', ... | [
{
"docstring": "Finds the row(s) with the maximum value in the specified column by processing rows in chunks.\n\nArgs:\n- file_path (str): Path to the CSV file.\n- column_index (int): The index of the column to find the maximum value in.\n- chunk_size (int): The number of rows to process at a time.\n\nReturns:\... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\n\ndef find_max_value_rows(file_path, column_index):\n \"\"\"\n Finds the row(s) with the maximum value in the specified column.\n\n Args:\n - file_path (str): Path to t... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00000012",
"row_id": 12,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_42']"
} | 0.628585 | Filter_12 | I | [
"find_max_value_rows_in_chunks",
"process_chunk"
] | 2 | [
[
"find_max_value_rows_in_chunks",
"process_chunk"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0aba16c213cfaac67b31cb93db38a5dec3bc4e77 | f575c5cfc55d22d72461e4492291bc9c7703b058 | |||
v1.0 | instruct | Filter | Filter_70_I | A binary tree is either empty or consists of a node with a value and two child nodes, referred to as the left child and the right child.
Write a function that returns the lowest common ancestor of two nodes in a binary tree.
The function will be called with a binary tree and two node values. The function should ret... | class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def find_LCA(root, val1, val2):
"""
Find the Lowest Common Ancestor (LCA) of two nodes with values val1 and val2 in a binary tree.
"""
# Base case: If tree is... | from solution import Node, lowest_common_ancestor
def test_lca_4_and_5():
root = Node(1, Node(2, Node(4), Node(5)), Node(3))
assert lowest_common_ancestor(root, 4, 5) == 2
def test_lca_4_and_6():
root = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
assert lowest_common_ancestor(root, 4, 6... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef find_lca(root, n1, n2):\n if root... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000070",
"row_id": 70,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_188']"
} | 0.544638 | Filter_70 | I | [
"find_LCA",
"lowest_common_ancestor"
] | 2 | [
[
"lowest_common_ancestor",
"find_LCA"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | c75ff1c8e8af880c27713b5dc4a549a3e68d23a9 | 5a06b41c0c471834e46b5b0a8df8dea67fec641f | |||
v1.0 | instruct | Filter | Filter_73_I | I was tasked with finding the shortest possible path between two points in a 2D grid, where I can move in any of the four primary directions (up, down, left, right) one step at a time. After researching, I've concluded to use the A* search algorithm. How can I implement this in Python? | from queue import PriorityQueue
def heuristic(a, b):
"""
Heuristic function for the A* algorithm.
It uses the Manhattan distance.
"""
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def a_star_search(grid, start, goal):
"""
Performs the A* search algorithm to find the shortest path in a 2D gri... | from solution import a_star_search
def test_basic_path():
grid = [
[0, 0, 0],
[1, 1, 0],
[0, 0, 0]
]
start = (0, 0)
goal = (2, 2)
assert a_star_search(grid, start, goal) == [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]
def test_no_valid_path():
grid = [
[0, 1, 0],
... | [
{
"docstring": "Heuristic function for the A* algorithm. \nIt uses the Manhattan distance.",
"function_declaration": "def heuristic(a, b):",
"function_name": "heuristic",
"parameter_list": "(a, b)"
},
{
"docstring": "Performs the A* search algorithm to find the shortest path in a 2D grid.\n\... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from queue import PriorityQueue\n\ndef heuristic(a, b):\n \"\"\"\n Heuristic function for the A* algorithm. \n It uses the Manhattan distance.\n \"\"\"\n return abs(a[0] - b[0])... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00000073",
"row_id": 73,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_195']"
} | 0.534025 | Filter_73 | I | [
"heuristic",
"a_star_search"
] | 2 | [
[
"a_star_search",
"heuristic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 13ed8a62a31a8eb8b9b7d2e468cfb2d36f8dfd89 | 10a58e9e0415421ea8f2e37f7a6439ea73df1f54 | |||
v1.0 | instruct | Filter | Filter_122_I | Here is the code snippet of the algorithm to find the Kth smallest element in an unsorted array:
```
def findKthSmallest(nums, k):
kth_smallest = sorted(nums)[k-1]
return kth_smallest
```
What is wrong with this approach? | def partition(nums, left, right):
pivot = nums[right]
i = left - 1
for j in range(left, right):
if nums[j] <= pivot:
i += 1
nums[i], nums[j] = nums[j], nums[i]
nums[i + 1], nums[right] = nums[right], nums[i + 1]
return i + 1
def quickselect(nums, left, right, k):
... | from solution import findKthSmallest
def test_findKthSmallest_basic():
assert findKthSmallest([3, 2, 1, 5, 6, 4], 2) == 2
assert findKthSmallest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) == 3
def test_findKthSmallest_edge_cases():
assert findKthSmallest([1], 1) == 1
assert findKthSmallest([5, 7, 2, 3], 1) == 2
... | [
{
"docstring": null,
"function_declaration": "def partition(nums, left, right):",
"function_name": "partition",
"parameter_list": "(nums, left, right)"
},
{
"docstring": null,
"function_declaration": "def quickselect(nums, left, right, k):",
"function_name": "quickselect",
"param... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def partition(nums, left, right):\n pivot = nums[right]\n i = left - 1\n for j in range(left, right):\n if nums[j] <= pivot:\n i += 1\n nums[i], nums[j] =... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00000122",
"row_id": 122,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_311']"
} | 0.626619 | Filter_122 | I | [
"partition",
"quickselect",
"findKthSmallest"
] | 3 | [
[
"findKthSmallest",
"quickselect"
],
[
"quickselect",
"partition"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3c01371c77f351334fff79351713b65af9a42939 | da373ca6a41837de270461fedecd8556b879af4b | |||
v1.0 | instruct | Filter | Filter_161_I | Twin primes are prime numbers that have exactly one number in between them. For example, 3 and 5 are twin primes, as well as 11 and 13. Write a Python program to identify all twin prime numbers up to a given limit. | def is_prime(n):
"""
Checks if a number n is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
def twin_primes(limit):
"""
... | from solution import twin_primes
def test_twin_primes_small_limit():
assert twin_primes(10) == [(3, 5), (5, 7)]
def test_twin_primes_no_twins():
assert twin_primes(3) == []
def test_twin_primes_up_to_17():
assert twin_primes(17) == [(3, 5), (5, 7), (11, 13)]
def test_twin_primes_large_limit():
resul... | [
{
"docstring": "Checks if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all twin prime pairs up to the given limit.",
"function_declaration": "def twin_primes(limit):",
"fun... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000161",
"row_id": 161,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_390']"
} | 0.549217 | Filter_161 | I | [
"is_prime",
"twin_primes"
] | 2 | [
[
"twin_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1d87b2319f4e1578ac98296d779372158d05825d | a454287f2db0ac54c78a6ffae44af1d98d491353 | |||
v1.0 | instruct | Filter | Filter_194_I | A program that creates a simple image with a red square at its center.
Here is the Python code to create the image:
```python
from PIL import Image, ImageDraw
# Create a new 400x400 image with white background.
img = Image.new('RGB', (400, 400), (255, 255, 255))
# Create a drawing context.
d = ImageDraw.Draw(img)
# Dr... | import random
from PIL import Image, ImageDraw, ImageSequence
# Function to create a random color.
def random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b)
# Function to create a random square.
def random_square(max_size, max_pos):
side ... | from PIL import Image
from solution import random_color, random_square, create_moving_squares_animation
def test_random_color():
color = random_color()
assert len(color) == 3
assert all(0 <= c <= 255 for c in color)
def test_random_square():
square = random_square(100, 800)
assert len(square) == 4... | [
{
"docstring": null,
"function_declaration": "def random_color():",
"function_name": "random_color",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def random_square(max_size, max_pos):",
"function_name": "random_square",
"parameter_list": "(max_size, max... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom PIL import Image, ImageDraw\n\n# Function to create a random color.\ndef random_color():\n r = random.randint(0, 255)\n g = random.randint(0, 255)\n b = random.ran... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000194",
"row_id": 194,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_466']"
} | 0.529213 | Filter_194 | I | [
"random_color",
"random_square",
"create_moving_squares_animation"
] | 3 | [
[
"create_moving_squares_animation",
"random_color"
],
[
"create_moving_squares_animation",
"random_square"
]
] | 2 | [] | false | [] | false | pytest | true | [
"PIL"
] | false | 6349aab44d62665f6523f4e09a59c261e46579bf | 1ef335124fc086ae0b35e3f8e6163d10d815b86b | |||
v1.0 | instruct | Filter | Filter_195_I | This problem involves a simple game where you start at position z=0 and can move z units to the right or left. The goal is to find the shortest path to the target z, which is z=3. The game also has a neutral initial state (z=0), a target state (z=3), and the right move operator R(z)=z+1 and the left move operator L(z)=... | def apply_operator(operator, state):
"""Apply a given operator (R or L) to a given state (z)."""
if operator == 'R':
return state + 1
elif operator == 'L':
return state - 1
else:
raise ValueError("Invalid operator. Only 'R' and 'L' are supported.")
def find_shortest_path(initial... | def test_apply_operator():
assert apply_operator('R', 0) == 1
assert apply_operator('L', 1) == 0
assert apply_operator('R', -1) == 0
def test_find_shortest_path():
assert find_shortest_path(0, 3) == ['R', 'R', 'R']
assert find_shortest_path(0, -3) == ['L', 'L', 'L']
assert find_shortest_pat... | [
{
"docstring": "Apply a given operator (R or L) to a given state (z).",
"function_declaration": "def apply_operator(operator, state):",
"function_name": "apply_operator",
"parameter_list": "(operator, state)"
},
{
"docstring": "Find the shortest path from the initial state to the target stat... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def apply_operator(operator, state):\n \"\"\"Apply a given operator (R or L) to a given state (z).\"\"\"\n if operator == 'R':\n return state + 1\n elif operator == 'L':\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00000195",
"row_id": 195,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_469']"
} | 0.487755 | Filter_195 | I | [
"apply_operator",
"find_shortest_path",
"run_simulation"
] | 3 | [
[
"run_simulation",
"apply_operator"
],
[
"run_simulation",
"find_shortest_path"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | eb2818d7a5fd2dddcecd0b2d388bda8511054054 | 35e0f091a5baef466686eb9ce4ea1f1fd6acd1d5 | |||
v1.0 | instruct | Filter | Filter_202_I | We are given a list of unique integers, each representing a node in a binary tree, and a target integer. The goal is to find the lowest common ancestor of the target nodes in the tree.
However, the tree structure is not explicitly given, but we can assume that the tree is a binary search tree (BST). In a BST, the lef... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def insert_into_bst(root, val):
"""
Inserts a value into the BST at the correct position.
"""
if root is None:
return TreeNode(val)
if val < root.val:
root.left = inser... | from solution import TreeNode, insert_into_bst, build_bst_from_list, find_node, lowestCommonAncestor
def test_lowest_common_ancestor():
values = [6, 2, 8, 0, 4, 7, 9, 3, 5]
root = build_bst_from_list(values)
p = find_node(root, 2)
q = find_node(root, 8)
lca = lowestCommonAncestor(root, p, q)
as... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef insert_into_bst(root, val):\n if root is None:\n return ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000202",
"row_id": 202,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_481']"
} | 0.506205 | Filter_202 | I | [
"insert_into_bst",
"build_bst_from_list",
"find_node",
"lowestCommonAncestor"
] | 4 | [
[
"build_bst_from_list",
"insert_into_bst"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 44d692f7e37720377e7f6d031d0ad91d8daf5783 | 61a7be673cf4558741a6d185b0cd54ed3aaa8426 | |||
v1.0 | instruct | Filter | Filter_205_I | This is a reinforcement learning problem. Given a 4x4 grid and an agent that can take an action at each position to move up, down, left or right. The agent starts at a random position and receives a reward of +1 for moving to the right and -1 for moving to the left. The agent receives a reward of 0 for all other action... | import numpy as np
import random
def find_action(grid, state):
# Return the possible actions for a given state
x, y = state
actions = []
if x > 0:
actions.append('up')
if x < len(grid) - 1:
actions.append('down')
if y > 0:
actions.append('left')
if y < len(grid) - 1:... | import numpy as np
import random
from solution import find_action, choose_action, get_reward, sarsa_control
def test_find_action():
grid = np.zeros((4, 4))
assert set(find_action(grid, (0,0))) == {'down', 'right'}
assert set(find_action(grid, (3,3))) == {'up', 'left'}
assert set(find_action(grid, (1,1)... | [
{
"docstring": null,
"function_declaration": "def find_action(grid, state):",
"function_name": "find_action",
"parameter_list": "(grid, state)"
},
{
"docstring": null,
"function_declaration": "def choose_action(grid, state, eps):",
"function_name": "choose_action",
"parameter_lis... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport random\n\ndef find_action(grid, state):\n # Return the possible actions for a given state\n x, y = state\n actions = []\n if x > 0:\n actions.appe... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000205",
"row_id": 205,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_493']"
} | 0.557249 | Filter_205 | I | [
"find_action",
"choose_action",
"get_reward",
"sarsa_control"
] | 4 | [
[
"choose_action",
"find_action"
],
[
"sarsa_control",
"choose_action"
],
[
"sarsa_control",
"find_action"
],
[
"sarsa_control",
"get_reward"
]
] | 4 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | b62a7e5b25110a63205f0f6bd0e4e954d2be0b26 | 8fd348def8e47cc80d828e58befcb84b89585db2 | |||
v1.0 | instruct | Filter | Filter_211_I | The local animal shelter will hold a dog wash and pet adoption event. Tickets are $5 per person or $20 per family. Write a program that prompts the user to enter the number of tickets and ticket type and calculates the total cost of the tickets.
Constraints:
* Tickets can be general admission or family tickets.
* Ge... | def get_general_admission_tickets():
while True:
try:
general_admission_tickets = int(input("Enter the number of general admission tickets: "))
if general_admission_tickets < 0:
print("Please enter a non-negative number of tickets.")
else:
... | def test_calculate_total_cost():
ticket_info = {'general_admission': 2, 'family': 3}
assert calculate_total_cost(ticket_info) == 70
def test_calculate_total_cost_zero_tickets():
ticket_info = {'general_admission': 0, 'family': 0}
assert calculate_total_cost(ticket_info) == 0
def test_calculate_total_c... | [
{
"docstring": null,
"function_declaration": "def get_general_admission_tickets():",
"function_name": "get_general_admission_tickets",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def get_family_tickets():",
"function_name": "get_family_tickets",
"param... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_general_admission_tickets():\n while True:\n try:\n general_admission_tickets = int(input(\"Enter the number of general admission tickets: \"))\n if gen... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00000211",
"row_id": 211,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_503']"
} | 0.58134 | Filter_211 | I | [
"get_general_admission_tickets",
"get_family_tickets",
"calculate_total_cost",
"main_menu"
] | 4 | [
[
"main_menu",
"calculate_total_cost"
],
[
"main_menu",
"get_family_tickets"
],
[
"main_menu",
"get_general_admission_tickets"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 2712df776903f372d56ab96aa5fa6c3ec14f2627 | 7bfe8fdfa12ab741a664fa1d565f9edcff4bd2eb | |||
v1.0 | instruct | Filter | Filter_215_I | ### Exercise 3.4
#Write a program that simulates the behavior of a coin toss. The program should ask the user to guess the outcome of the coin toss (either heads or tails). The program should then simulate the coin toss and print out the result. If the user's guess was correct, the program should print "You win!" Other... | import random
def get_user_guess(guess_input=None):
while True:
guess = guess_input if guess_input else input("Guess heads or tails: ")
if guess.lower() in ["heads", "tails"]:
return guess.lower()
else:
print("Invalid guess. Please enter heads or tails.")
... | from solution import get_user_guess, get_user_bet, simulate_coin_toss, play_round
def test_get_user_guess():
assert get_user_guess("heads") == "heads"
assert get_user_guess("tails") == "tails"
assert get_user_guess("Invalid") is None
def test_get_user_bet():
assert get_user_bet(100, "50") == 50
... | [
{
"docstring": null,
"function_declaration": "def get_user_guess(guess_input=None):",
"function_name": "get_user_guess",
"parameter_list": "(guess_input=None)"
},
{
"docstring": null,
"function_declaration": "def get_user_bet(balance, bet_input=None):",
"function_name": "get_user_bet... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_user_guess():\n guess = input(\"Guess heads or tails: \").strip().lower()\n if guess not in [\"heads\", \"tails\"]:\n raise ValueError(\"Invalid guess. Pl... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000215",
"row_id": 215,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_511']"
} | 0.530555 | Filter_215 | I | [
"get_user_guess",
"get_user_bet",
"simulate_coin_toss",
"play_round",
"main"
] | 5 | [
[
"play_round",
"get_user_bet"
],
[
"play_round",
"get_user_guess"
],
[
"play_round",
"simulate_coin_toss"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 2939ce0ed6f10b68b4e01892aed2626b2db978c2 | 699a675b2408267d161696b75e8f9edc9fbec88a | |||
v1.0 | instruct | Filter | Filter_227_I | This problem requires you to find the longest palindromic substring in a given string.
For example, the input string "babad" has two possible longest palindromic substrings: "bab" and "aba". However, the function should return "aba".
Here is a Python solution for this problem:
```
def longest_palindrome(s):
res = ... | def longest_palindrome(s):
"""
Finds the longest palindromic substring in the input string `s`.
"""
if not s:
return ""
start, end = 0, 0
for i in range(len(s)):
len1 = expand_around_center(s, i, i) # Odd length palindrome
len2 = expand_around_center(s, i, i + ... | from solution import longest_palindrome
def test_longest_palindrome():
assert longest_palindrome("babad") in ["bab", "aba"]
assert longest_palindrome("cbbd") == "bb"
assert longest_palindrome("a") == "a"
assert longest_palindrome("ac") in ["a", "c"]
assert longest_palindrome("racecar") == "racecar"... | [
{
"docstring": "Finds the longest palindromic substring in the input string `s`.",
"function_declaration": "def longest_palindrome(s):",
"function_name": "longest_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Expand around the center to find the length of the substring that \nis a ... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def longest_palindrome(s):\n \"\"\"\n Returns the longest palindromic substring in the input string s.\n Uses dynamic programming to achieve O(n^2) time complexity.\n \"\"\"\n\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000227",
"row_id": 227,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_538']"
} | 0.764529 | Filter_227 | I | [
"longest_palindrome",
"expand_around_center"
] | 2 | [
[
"longest_palindrome",
"expand_around_center"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 15f47a2ef50c914f50fdce5e24950d05a734414b | b2c6d918d11810f118e8cad91de609738170aff8 | |||
v1.0 | instruct | Filter | Filter_258_I | The game of "Rock, Paper, Scissors, Lizard, Spock" is a variation of the classic game of "Rock, Paper, Scissors." Here are the rules:
- Rock crushes Scissors
- Scissors cuts Paper
- Paper covers Rock
- Rock crushes Lizard
- Lizard poisons Spock
- Spock smashes Scissors
- Scissors decapitates Lizard
- Lizard eats Paper
... | import random
def get_winner(player1_choice, player2_choice):
"""
Determines the winner of a Rock, Paper, Scissors, Lizard, Spock game.
Returns 'Player 1', 'Player 2' or 'Tie'.
"""
winning_cases = {
'rock': ['scissors', 'lizard'],
'scissors': ['paper', 'lizard'],
'paper': ['... | from solution import get_winner, simulate_game
def test_tie_case():
assert get_winner('rock', 'rock') == 'Tie'
assert get_winner('paper', 'paper') == 'Tie'
assert get_winner('scissors', 'scissors') == 'Tie'
assert get_winner('lizard', 'lizard') == 'Tie'
assert get_winner('spock', 'spock') == 'Tie'
... | [
{
"docstring": "Determines the winner of a Rock, Paper, Scissors, Lizard, Spock game.\nReturns 'Player 1', 'Player 2' or 'Tie'.",
"function_declaration": "def get_winner(player1_choice, player2_choice):",
"function_name": "get_winner",
"parameter_list": "(player1_choice, player2_choice)"
},
{
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_random_choice():\n return random.choice(['Rock', 'Paper', 'Scissors', 'Lizard', 'Spock'])\n\ndef determine_winner(player1, player2):\n win_conditions = {\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000258",
"row_id": 258,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_641']"
} | 0.482837 | Filter_258 | I | [
"get_winner",
"simulate_game"
] | 2 | [
[
"simulate_game",
"get_winner"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0f7e89b087877bb0f8856bb30b3b4930840fda8a | a2cd87f890399591754f2627ae20f2905c800831 | |||
v1.0 | instruct | Filter | Filter_294_I | This problem is similar to an earlier one, but with a different type of puzzle. Here are the rules for the puzzle:
A cryptogram is a puzzle in which a quote or phrase is encoded, and the encoding is done by replacing each letter with a different letter a fixed number of positions down the alphabet. For example, with a ... | import random
def get_random_shift():
return random.randint(1, 25)
def caesar_cipher(text, shift):
"""
Encodes or decodes a given text using a Caesar cipher with the provided shift.
Case-insensitive. Non-alphabet characters remain unchanged.
"""
result = []
shift = shift % 26 # Ensure shi... | from solution import get_random_shift, caesar_cipher, caesar_cipher_decode
def test_random_shift():
for _ in range(100):
shift = get_random_shift()
assert 1 <= shift <= 25
def test_caesar_cipher_encoding():
shift = 3
assert caesar_cipher("abc", shift) == "def"
assert caesar_cipher("xyz... | [
{
"docstring": null,
"function_declaration": "def get_random_shift():",
"function_name": "get_random_shift",
"parameter_list": "()"
},
{
"docstring": "Encodes or decodes a given text using a Caesar cipher with the provided shift.\nCase-insensitive. Non-alphabet characters remain unchanged.",... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport string\n\ndef generate_random_shift():\n \"\"\"\n Returns a random shift between 1 and 25 inclusive.\n \"\"\"\n return random.randint(1, 25)\n\ndef caesar_cip... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000294",
"row_id": 294,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_716']"
} | 0.569994 | Filter_294 | I | [
"get_random_shift",
"caesar_cipher",
"caesar_cipher_decode"
] | 3 | [
[
"caesar_cipher_decode",
"caesar_cipher"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 61b3e6e795de37b3da382cd7825499dfe31f930f | cf6a67c215d1b5ae12e5c4e309ee4431f48301a4 | |||
v1.0 | instruct | Filter | Filter_320_I | In this problem, we consider a set of nodes in a network, where each node has a unique identifier and is either a regular node or a hub node.
We will be given a set of triples in the form of (source, destination, distance), which describes a direct connection between two nodes, including the distance between them.
Th... | import heapq
def dijkstra(graph, start_node):
# Priority queue to store (distance, node)
pq = [(0, start_node)]
distances = {node: float('infinity') for node in graph}
distances[start_node] = 0
while pq:
current_distance, current_node = heapq.heappop(pq)
if current_distance > dist... | from solution import shortest_path, build_graph
def test_shortest_path_direct_connection():
nodes = {'A': 'regular', 'B': 'regular'}
edges = [['A', 'B', 2]]
assert shortest_path(nodes, edges, 'A', 'B') == 2
def test_shortest_path_via_hub():
nodes = {'A': 'regular', 'B': 'regular', 'C': 'hub'}
edge... | [
{
"docstring": null,
"function_declaration": "def dijkstra(graph, start_node):",
"function_name": "dijkstra",
"parameter_list": "(graph, start_node)"
},
{
"docstring": null,
"function_declaration": "def build_graph(node_info, edges):",
"function_name": "build_graph",
"parameter_l... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef dijkstra(graph, start_node):\n \"\"\"\n Dijkstra's algorithm to find the shortest path from start_node to all other nodes.\n Returns a dictionary with the shortest... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00000320",
"row_id": 320,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_770']"
} | 0.556085 | Filter_320 | I | [
"dijkstra",
"build_graph",
"shortest_path"
] | 3 | [
[
"shortest_path",
"build_graph"
],
[
"shortest_path",
"dijkstra"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9f1f2d94e4cb20fc4c9713f3a5c46ee8d1a01417 | 213a6908bef9758f201bf6b51bf1e0d479e4f66b | |||
v1.0 | instruct | Filter | Filter_347_I | I want to create a simple game using Python. The game is a number guessing game. Here are the rules:
1. The game generates a random number between 1 and 100.
2. The user is asked to guess the number.
3. After the user's guess, the game tells the user if their guess is higher or lower than the random number.
4. The gam... | import random
def get_random_number(start=1, end=100):
"""
Returns a random integer between start and end, inclusive.
"""
return random.randint(start, end)
def get_user_guess():
"""
Prompts the user to enter a guess and returns the guess as an integer.
Validates the input to ensure it's a ... | import pytest
from unittest.mock import patch
from solution import get_random_number, get_user_guess, number_guessing_game
def test_get_random_number():
number = get_random_number()
assert 1 <= number <= 100
@patch('builtins.input', side_effect=['50'])
def test_get_user_guess_valid(mock_input):
guess = ge... | [
{
"docstring": "Returns a random integer between start and end, inclusive.",
"function_declaration": "def get_random_number(start=1, end=100):",
"function_name": "get_random_number",
"parameter_list": "(start=1, end=100)"
},
{
"docstring": "Prompts the user to enter a guess and returns the g... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef number_guessing_game():\n number_to_guess = random.randint(1, 100)\n print(\"Welcome to the Number Guessing Game!\")\n print(\"I've selected a number between 1 an... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00000347",
"row_id": 347,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_836']"
} | 0.527132 | Filter_347 | I | [
"get_random_number",
"get_user_guess",
"number_guessing_game"
] | 3 | [
[
"number_guessing_game",
"get_random_number"
],
[
"number_guessing_game",
"get_user_guess"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7d7e83240967fa54ecce20075faf9d5c72c98bfe | cf51355348e1cabcf3e400854ab7c7e25a467f48 | |||
v1.0 | instruct | Filter | Filter_366_I | I am working on a project where I need to find the expansion of $(x + y)^n$ for a given positive integer n.
Want to use python for this and my approach is to write a recursive function to compute the expansion.
My question is, how would I represent the expansion in a programmatic way. What data structure would be su... | def binomial_coeff(n, k):
"""Recursive function to calculate binomial coefficient."""
if k == 0 or k == n:
return 1
else:
return binomial_coeff(n-1, k-1) + binomial_coeff(n-1, k)
def expand_binomial(x, y, n):
"""
Expands the binomial (x + y)^n and returns the expansion as a list of ... | from solution import expand_binomial
def test_expand_binomial_n_0():
result = expand_binomial('x', 'y', 0)
expected = [(1, 0, 0)]
assert result == expected
def test_expand_binomial_n_1():
result = expand_binomial('x', 'y', 1)
expected = [(1, 1, 0), (1, 0, 1)]
assert result == expected
def tes... | [
{
"docstring": "Recursive function to calculate binomial coefficient.",
"function_declaration": "def binomial_coeff(n, k):",
"function_name": "binomial_coeff",
"parameter_list": "(n, k)"
},
{
"docstring": "Expands the binomial (x + y)^n and returns the expansion as a list of tuples.\nEach tu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def binomial_expansion(x, y, n):\n \"\"\"\n Returns the binomial expansion of (x + y)^n as a list of tuples.\n Each tuple contains (coefficient, exponent of x, exponent of y).\n \"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000366",
"row_id": 366,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_886']"
} | 0.419334 | Filter_366 | I | [
"binomial_coeff",
"expand_binomial"
] | 2 | [
[
"expand_binomial",
"binomial_coeff"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b44f7a09feb07c77a6e674d18938d244878b0d2b | b4404c51a2e73bad906a521545652b23f3a842c0 | |||
v1.0 | instruct | Filter | Filter_376_I | Your task is to make a simple text-based calculator app in Python. Here's I've done so far:
```
def get_input():
return input("Enter a number: ")
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
if y == 0:
return "Error: Division by zero... | def get_input():
while True:
try:
return float(input("Enter a number: "))
except ValueError:
print("Invalid input, please enter a number.")
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
if y == 0:
... | import pytest
from solution import add, sub, mul, div, perform_operation
def test_add():
assert add(2, 3) == 5
assert add(-2, 3) == 1
assert add(0, 0) == 0
assert add(2.5, 3.5) == 6.0
def test_sub():
assert sub(5, 3) == 2
assert sub(3, 5) == -2
assert sub(0, 0) == 0
assert sub(5.5, 3.5... | [
{
"docstring": null,
"function_declaration": "def get_input():",
"function_name": "get_input",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def add(x, y):",
"function_name": "add",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef get_input(prompt=\"Enter a number: \"):\n while True:\n try:\n return float(input(prompt))\n except ValueError:\n print(\"Invalid inpu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000376",
"row_id": 376,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_926']"
} | 0.519723 | Filter_376 | I | [
"get_input",
"add",
"sub",
"mul",
"div",
"perform_operation",
"calculator"
] | 7 | [
[
"calculator",
"get_input"
],
[
"calculator",
"perform_operation"
],
[
"perform_operation",
"add"
],
[
"perform_operation",
"div"
],
[
"perform_operation",
"mul"
],
[
"perform_operation",
"sub"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | 8a58164d217e2a13e6bd1e1d0de6e44e33ecbf66 | 797ba34d264aa52495dd6a732b364dba28339160 | |||
v1.0 | instruct | Filter | Filter_380_I | In this problem, you will be asked to design a game in which a player, initially at a random open cell, will move to an adjacent open cell, chosen randomly from the neighboring open cells in a grid. Write a Python code that implements this game.
## Step 1: Define the game grid
We need to define a grid of cells, where ... | import random
def create_grid(grid_size, density=0.2):
"""
Create a grid of specified size and block density.
"""
return [[0 if random.random() > density else 1 for _ in range(grid_size)] for _ in range(grid_size)]
def find_random_open_cell(grid):
"""
Find a random open cell in the grid.
"... | def test_create_grid():
grid = create_grid(5, density=0)
assert len(grid) == 5
assert all(len(row) == 5 for row in grid)
assert all(cell == 0 for row in grid for cell in row)
grid = create_grid(5, density=1)
assert all(cell == 1 for row in grid for cell in row)
def test_find_random_open_cell()... | [
{
"docstring": "Create a grid of specified size and block density.",
"function_declaration": "def create_grid(grid_size, density=0.2):",
"function_name": "create_grid",
"parameter_list": "(grid_size, density=0.2)"
},
{
"docstring": "Find a random open cell in the grid.",
"function_declar... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef print_grid(grid, player_position):\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if (i, j) == player_position:\n print... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000380",
"row_id": 380,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_934']"
} | 0.654226 | Filter_380 | I | [
"create_grid",
"find_random_open_cell",
"get_neighbors",
"move_player",
"print_grid",
"run_game"
] | 6 | [
[
"move_player",
"get_neighbors"
],
[
"run_game",
"create_grid"
],
[
"run_game",
"find_random_open_cell"
],
[
"run_game",
"move_player"
],
[
"run_game",
"print_grid"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | cbdb8ee34ad86c86f60241e6100beadcc88e06ee | 45c2e9d4319169531873401b73a6097368050594 | |||
v1.0 | instruct | Filter | Filter_392_I | Here is a 2D grid with some cells containing positive numbers, representing the height of the walls of a maze. There are two paths entering and exiting the maze. Provide a breadth-first search solution to determine if there is a path between these two paths, where a path that enters at a specific cell and exits at anot... | from collections import deque
def is_valid_move(maze, visited, row, col):
"""
Check if the move to (row, col) is within bounds, not blocked by a wall,
and not already visited.
"""
return (0 <= row < len(maze)) and (0 <= col < len(maze[0])) and \
maze[row][col] == 0 and not visited[row][c... | from solution import is_valid_move, bfs
def test_path_exists():
maze = [
[0, 3, 2, 0, 0, 0],
[0, 0, 0, 0, 3, 2],
[0, 3, 2, 3, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]
]
entrance = (0, 0)
exit = (5, 5)
assert bfs(maze, entrance... | [
{
"docstring": "Check if the move to (row, col) is within bounds, not blocked by a wall,\nand not already visited.",
"function_declaration": "def is_valid_move(maze, visited, row, col):",
"function_name": "is_valid_move",
"parameter_list": "(maze, visited, row, col)"
},
{
"docstring": "Perfo... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef is_valid_move(maze, visited, row, col):\n return (0 <= row < len(maze)) and (0 <= col < len(maze[0])) and maze[row][col] == 0 and not visited[row][col]\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00000392",
"row_id": 392,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_970']"
} | 0.665613 | Filter_392 | I | [
"is_valid_move",
"bfs"
] | 2 | [
[
"bfs",
"is_valid_move"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2ae9cfd277a098e79ea51049603d06ad6b93b4ea | 6c00c0d27f6f5e1a9f1af97469dba75fcdcd3178 | |||
v1.0 | instruct | Filter | Filter_424_I | def calculate_mandelbrot(xmin,xmax,ymin,ymax,width,height,max_iter):
r1 = np.linspace(xmin, xmax, width)
r2 = np.linspace(ymin, ymax, height)
return (r1,r2,np.array([[mandelbrot(complex(r, i),max_iter) for r in r1] for i in r2]))
def mandelbrot(c,max_iter):
z = c
for n in range(max_iter):
i... | import numpy as np
import matplotlib.pyplot as plt
def calculate_mandelbrot(xmin, xmax, ymin, ymax, width, height, max_iter):
r1 = np.linspace(xmin, xmax, width)
r2 = np.linspace(ymin, ymax, height)
return (r1, r2, np.array([[mandelbrot(complex(r, i), max_iter) for r in r1] for i in r2]))
def mandelbrot(c... | import numpy as np
from solution import calculate_mandelbrot, mandelbrot
def test_mandelbrot():
assert mandelbrot(complex(0, 0), 256) == 256
assert mandelbrot(complex(2, 2), 256) == 0
assert mandelbrot(complex(-1, 0), 256) == 256
def test_calculate_mandelbrot():
r1, r2, m = calculate_mandelbrot(-2... | [
{
"docstring": null,
"function_declaration": "def calculate_mandelbrot(xmin, xmax, ymin, ymax, width, height, max_iter):",
"function_name": "calculate_mandelbrot",
"parameter_list": "(xmin, xmax, ymin, ymax, width, height, max_iter)"
},
{
"docstring": null,
"function_declaration": "def m... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef calculate_mandelbrot(xmin, xmax, ymin, ymax, width, height, max_iter):\n \"\"\"\n Generates the Mandelbrot set coordinates and ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00000424",
"row_id": 424,
"seed_ids": "['Meta-Llama-3.1-70B-Instruct_1055']"
} | 0.527181 | Filter_424 | I | [
"calculate_mandelbrot",
"mandelbrot",
"draw_image"
] | 3 | [
[
"calculate_mandelbrot",
"mandelbrot"
],
[
"draw_image",
"calculate_mandelbrot"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | 8b0fa89703b11a9a7f7840a5f630adb98cd0ee86 | 82e8193bbeefbafdd19f9d1ca70d0ac8f1764030 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.