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_10864_I | #### Objective:
Demonstrate your understanding of Python's `__main__` special name, writing idiomatic script code that can be used both as a standalone script and as an importable module.
#### Problem Statement:
You are tasked with creating a Python module named `converter.py` that includes functionality for convertin... | import sys
def celsius_to_fahrenheit(celsius: float) -> float:
return celsius * 9/5 + 32
def fahrenheit_to_celsius(fahrenheit: float) -> float:
return (fahrenheit - 32) * 5/9
def celsius_to_kelvin(celsius: float) -> float:
return celsius + 273.15
def kelvin_to_celsius(kelvin: float) -> float:
return... | from solution import (
celsius_to_fahrenheit,
fahrenheit_to_celsius,
celsius_to_kelvin,
kelvin_to_celsius,
fahrenheit_to_kelvin,
kelvin_to_fahrenheit,
)
def test_celsius_to_fahrenheit():
assert celsius_to_fahrenheit(0) == 32
assert celsius_to_fahrenheit(100) == 212
def test_fahrenheit... | [
{
"docstring": null,
"function_declaration": "def celsius_to_fahrenheit(celsius):",
"function_name": "celsius_to_fahrenheit",
"parameter_list": "(celsius)"
},
{
"docstring": null,
"function_declaration": "def fahrenheit_to_celsius(fahrenheit):",
"function_name": "fahrenheit_to_celsiu... | [
0,
0,
0,
0,
1,
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 sys\n\ndef celsius_to_fahrenheit(celsius: float) -> float:\n return celsius * 9 / 5 + 32\n \ndef fahrenheit_to_celsius(fahrenheit: float) -> float:\n re... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00010864",
"row_id": 10864,
"seed_ids": "[306]"
} | 0.480683 | Docs: Python310_10864 | I | [
"celsius_to_fahrenheit",
"fahrenheit_to_celsius",
"celsius_to_kelvin",
"kelvin_to_celsius",
"fahrenheit_to_kelvin",
"kelvin_to_fahrenheit",
"main"
] | 7 | [
[
"fahrenheit_to_kelvin",
"celsius_to_kelvin"
],
[
"fahrenheit_to_kelvin",
"fahrenheit_to_celsius"
],
[
"kelvin_to_fahrenheit",
"celsius_to_fahrenheit"
],
[
"kelvin_to_fahrenheit",
"kelvin_to_celsius"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 3ee182cfb0bf302bb980b577da8542bd9cbf3653 | da0bc10a48747c227fe6accfae38c7df6394eace | |||
v1.0 | instruct | Docs | Docs: Scikit_10874_I | ## Coding Assessment Question
### Objective
To assess your understanding of scikit-learn, specifically focusing on handling multi-label classifications using the `OneVsRestClassifier`.
### Problem Statement
Given a text dataset, your task is to implement a pipeline to classify text data into multiple labels. Each pie... | from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
from sklearn.multiclass import OneVsRestClassifier
from sklearn.pipeline import make_pipeline
from sklearn.metrics import classification_report
from sklearn.model_selection impor... | import pytest
from solution import load_and_preprocess_data, create_pipeline, train_and_evaluate
def test_data_loading():
categories = ['alt.atheism', 'comp.graphics', 'sci.space', 'talk.politics.guns']
train_data, test_data = load_and_preprocess_data(categories)
assert len(train_data.data) > 0
assert ... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sklearn.datasets import fetch_20newsgroups\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.svm import LinearSVC\nfrom sklearn.multiclass... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00010874",
"row_id": 10874,
"seed_ids": "[56]"
} | 0.521682 | Docs: Scikit_10874 | I | [
"load_and_preprocess_data",
"create_pipeline",
"train_and_evaluate"
] | 3 | [
[
"train_and_evaluate",
"create_pipeline"
],
[
"train_and_evaluate",
"load_and_preprocess_data"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sklearn"
] | false | fa51fd175c877f0946dcf680f4fc076709f8a2e0 | e5fe87284c648af0d29c0f2cbcb8c059ef303d69 | |||
v1.0 | instruct | Docs | Docs: Python310_10972_I | **Command Line Argument Parser for a File Processor**
You are tasked with developing a command-line argument parser for a Python script that processes files. The script should accept the following options:
1. **-i or --input**: Specifies the input file path (required).
2. **-o or --output**: Specifies the output file... | import sys
import getopt
def parse_arguments(args):
"""
Parse command line arguments.
:param args: List of command-line arguments (excluding the script name).
:return: Dictionary with parsed options.
"""
options = {
'input': None,
'output': None,
'verbose': False,
... | import sys
import pytest
from solution import parse_arguments, print_usage
def test_parse_arguments_with_all_options():
args = ["-i", "input.txt", "-o", "output.txt", "-v"]
expected_output = {
'input': 'input.txt',
'output': 'output.txt',
'verbose': True,
'help': False
}
... | [
{
"docstring": "Parse command line arguments.\n\n:param args: List of command-line arguments (excluding the script name).\n:return: Dictionary with parsed options.",
"function_declaration": "def parse_arguments(args):",
"function_name": "parse_arguments",
"parameter_list": "(args)"
},
{
"doc... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nimport getopt\n\ndef parse_arguments(args):\n \"\"\"\n Parse command line arguments.\n\n :param args: List of command-line arguments (excluding the... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00010972",
"row_id": 10972,
"seed_ids": "[386]"
} | 0.576421 | Docs: Python310_10972 | I | [
"parse_arguments",
"print_usage"
] | 2 | [
[
"parse_arguments",
"print_usage"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 98f9f8a753426b9c44d4fb3420e4a2d3516c54d9 | b452f297922f8ff1f64d4d09aea019f53175cf34 | |||
v1.0 | instruct | Docs | Docs: Python310_11017_I | ### Terminal Control with Python's `tty` Module
You are tasked with designing a small command-line tool in Python to interactively toggle the terminal mode between `raw` and `cbreak`.
#### Requirements:
1. **Functions to Implement:**
- `enable_raw_mode(fd: int) -> None`: This function should set the terminal to ... | import sys
import termios
import tty
import time
import signal
def enable_raw_mode(fd: int) -> None:
"""
Sets the terminal to raw mode.
:param fd: File descriptor of the terminal
"""
tty.setraw(fd)
def enable_cbreak_mode(fd: int) -> None:
"""
Sets the terminal to cbreak (canonical) mo... | # Due to the interactive nature of terminal control and its requirement for manual interruption,
# writing unit tests for the above behavior requires mocking and isn't feasible as traditional unit tests.
# Therefore, we'll create pseudo-tests using mocks for demonstration, but in practice,
# these would be confirmed ma... | [
{
"docstring": "Sets the terminal to raw mode.\n\n:param fd: File descriptor of the terminal",
"function_declaration": "def enable_raw_mode(fd):",
"function_name": "enable_raw_mode",
"parameter_list": "(fd)"
},
{
"docstring": "Sets the terminal to cbreak (canonical) mode.\n\n:param fd: File ... | [
0,
0,
0,
0,
1,
1,
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 sys\nimport termios\nimport tty\nimport time\nimport signal\n\ndef enable_raw_mode(fd: int) -> None:\n tty.setraw(fd)\n\ndef enable_cbreak_mode(fd: int) -> No... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00011017",
"row_id": 11017,
"seed_ids": "[186]"
} | 0.339971 | Docs: Python310_11017 | I | [
"enable_raw_mode",
"enable_cbreak_mode",
"reset_terminal_mode",
"toggle_modes"
] | 4 | [
[
"toggle_modes",
"enable_cbreak_mode"
],
[
"toggle_modes",
"enable_raw_mode"
],
[
"toggle_modes",
"reset_terminal_mode"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 6ea6db3ae94301cc6f2fd1e6a0218eaa782b269c | 031bcc1b7c7d04f47b1f3ee775a9b97ffcbad655 | |||
v1.0 | instruct | Docs | Docs: Pytorch_11036_I | ### MPS Backend with PyTorch
In this task, you will demonstrate your understanding of utilizing the MPS backend for GPU computations in PyTorch. You will need to implement functions that verify the availability of the MPS device, perform tensor operations on the MPS device, and compare the performance and correctness ... | import torch
def check_mps_availability():
"""
Returns: True if MPS is available, else False
"""
if not torch.backends.mps.is_available():
return False
return True
def perform_mps_tensor_operations(n):
"""
Args:
n (int): The size of the tensor to create
Returns:
torch.... | import pytest
import torch
from solution import check_mps_availability, perform_mps_tensor_operations, compare_cpu_mps
def test_check_mps_availability():
# This test depends on the actual availability of MPS backend which might not be available in the testing environment.
assert isinstance(check_mps_availabili... | [
{
"docstring": "Returns: True if MPS is available, else False",
"function_declaration": "def check_mps_availability():",
"function_name": "check_mps_availability",
"parameter_list": "()"
},
{
"docstring": "Args:\nn (int): The size of the tensor to create\n\nReturns:\ntorch.Tensor: The result... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef check_mps_availability():\n \"\"\"\n Returns: True if MPS is available, else False\n \"\"\"\n if not torch.backends.mps.is_available():\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00011036",
"row_id": 11036,
"seed_ids": "[167]"
} | 0.495953 | Docs: Pytorch_11036 | I | [
"check_mps_availability",
"perform_mps_tensor_operations",
"compare_cpu_mps"
] | 3 | [
[
"compare_cpu_mps",
"check_mps_availability"
],
[
"perform_mps_tensor_operations",
"check_mps_availability"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 1660de87f7f9562145267d85269edc9a62266fcd | 29ceb194c55c88abd06ca83ca1909b42cd3c87bf | |||
v1.0 | instruct | Docs | Docs: Python310_11095_I | ### Context Management in Asynchronous Programming
**Objective**:
Write a function and a test suite to simulate an async server handling multiple clients using context variables to maintain client-specific state without interference.
**Background**:
You are to implement a simple echo server that maintains each clie... | import asyncio
import contextvars
client_addr_var = contextvars.ContextVar('client_addr')
def render_goodbye() -> bytes:
"""
Get the client's address from the context variable and return a goodbye message.
Returns:
bytes: Goodbye message encoded in bytes.
"""
client_addr = client_addr... | import pytest
import contextvars
from solution import render_goodbye, handle_request, client_addr_var
import asyncio
from asyncio import StreamReader, StreamWriter
def test_render_goodbye():
addr = ("127.0.0.1", 8081)
token = client_addr_var.set(addr)
greet_message = render_goodbye()
assert g... | [
{
"docstring": "Get the client's address from the context variable and return a goodbye message.\n\nReturns:\n bytes: Goodbye message encoded in bytes.",
"function_declaration": "def render_goodbye():",
"function_name": "render_goodbye",
"parameter_list": "()"
}
] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport contextvars\n\nclient_addr_var = contextvars.ContextVar('client_addr')\n\ndef render_goodbye() -> bytes:\n \"\"\"\n Get the client's addres... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011095",
"row_id": 11095,
"seed_ids": "[392]"
} | 0.576067 | Docs: Python310_11095 | I | [
"render_goodbye",
"handle_request",
"main"
] | 3 | [
[
"handle_request",
"render_goodbye"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b69187d067d630107db63fd9845df87432d1d599 | c0df2d2af19e061ef66b2fef896415ba8e60e123 | |||
v1.0 | instruct | Docs | Docs: Python310_11194_I | Your task is to implement a program that demonstrates the use of both thread-based and process-based parallelism to perform a computation-intensive task efficiently.
#### Problem Statement
You are given a large list of numbers, which you need to process in two steps:
1. **Step 1 - Thread-based Parallelism**:
- Us... | from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def compute_square(n):
return n * n
def sum_chunk(chunk):
return sum(chunk)
def compute_sum_of_squares(numbers):
# Step 1: Use ThreadPoolExecutor to compute squares of each number
with ThreadPoolExecutor() as executor:
squ... | from solution import compute_sum_of_squares
def test_compute_sum_of_squares_small_list():
numbers = [1, 2, 3, 4, 5]
assert compute_sum_of_squares(numbers) == 55
def test_compute_sum_of_squares_large_list():
numbers = list(range(1000))
expected_sum = sum(x * x for x in numbers)
assert compute_sum_o... | [
{
"docstring": null,
"function_declaration": "def compute_square(n):",
"function_name": "compute_square",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def sum_chunk(chunk):",
"function_name": "sum_chunk",
"parameter_list": "(chunk)"
},
{
"docst... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nimport math\n\ndef chunked_iterable(iterable, size):\n \"\"\"Helper function to split an iter... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011194",
"row_id": 11194,
"seed_ids": "[206]"
} | 0.631346 | Docs: Python310_11194 | I | [
"compute_square",
"sum_chunk",
"compute_sum_of_squares"
] | 3 | [
[
"compute_sum_of_squares",
"compute_square"
],
[
"compute_sum_of_squares",
"sum_chunk"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 631b3467cdb5745521b63e5861c4dbb2753eda83 | 94998b4ccabb60ced2eea8b18d9ece6077a7bb50 | |||
v1.0 | instruct | Docs | Docs: Python310_11247_I | #### Objective
Implement a simple chat server and client using the `asyncio` streams module. The purpose is to demonstrate your understanding of asynchronous networking, particularly employing `StreamReader` and `StreamWriter`.
#### Requirements
1. Implement an asynchronous chat server that can handle multiple clients... | import asyncio
clients = []
async def broadcast_message(message, writer):
for client_writer in clients:
if client_writer != writer:
client_writer.write(message.encode())
await client_writer.drain()
async def handle_client(reader, writer):
addr = writer.get_extra_info('peernam... | import asyncio
import pytest
from asyncio import StreamWriter, StreamReader
from solution import main, handle_client, broadcast_message
@pytest.mark.asyncio
async def test_broadcast_message(monkeypatch):
messages = []
class MockWriter:
def __init__(self):
self.data = b''
... | [] | [
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\nimport sys\n\nasync def handle_client(reader, writer):\n clients.append(writer)\n addr = writer.get_extra_info('peername')\n print(f\"{addr} is... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00011247",
"row_id": 11247,
"seed_ids": "[182]"
} | 0.539925 | Docs: Python310_11247 | I | [
"broadcast_message",
"handle_client",
"main"
] | 3 | [
[
"handle_client",
"broadcast_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9effe35455a376b6c72fb5194fb09402bb86444a | 2725a799a43825619135ec85680ae88a1b1f1dfe | |||
v1.0 | instruct | Docs | Docs: Python310_11267_I | **Objective:**
Implement a function using `asyncio` futures to simulate an asynchronous task scheduler.
**Problem Statement:**
You need to write a function `async_task_scheduler` that schedules and manages multiple asynchronous tasks using `asyncio` futures. Each task should simulate an asynchronous operation by slee... | import asyncio
import random
from typing import List
async def simulate_task(fut: asyncio.Future, delay: int, result: str) -> None:
await asyncio.sleep(delay)
fut.set_result(result)
async def async_task_scheduler(n: int) -> List[str]:
loop = asyncio.get_running_loop()
futures = []
for i in ra... | import pytest
import asyncio
from unittest.mock import patch
from solution import async_task_scheduler
@pytest.mark.asyncio
async def test_async_task_scheduler():
# Test the function with a defined number of tasks
n = 5
results = await async_task_scheduler(n)
assert len(results) == n
for i in rang... | [] | [
1,
1,
1
] | 3 | 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 simulate_task(fut: asyncio.Future, delay: int, result: str) -> None:\n await asyncio.sleep(delay)... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011267",
"row_id": 11267,
"seed_ids": "[113]"
} | 0.571226 | Docs: Python310_11267 | I | [
"simulate_task",
"async_task_scheduler"
] | 2 | [
[
"async_task_scheduler",
"simulate_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ea579dbd8e7c6dba2036ca20e943e43832654fd0 | 7bca226875f753ed3374df0b80fc8dcf5acb3e67 | |||
v1.0 | instruct | Docs | Docs: Python310_11272_I | ### Asynchronous Task and Exception Handling
**Objective:**
Implement an asynchronous function that performs multiple I/O operations and demonstrates comprehensive exception handling using the asyncio exceptions discussed above.
**Task Description:**
Write an asynchronous function `fetch_and_process_data` that:
1.... | import asyncio
from typing import List
async def fetch_data(url: str, timeout: float):
try:
await asyncio.sleep(timeout)
print(f"Fetched data from {url}")
except asyncio.TimeoutError:
print(f"TimeoutError: Fetching data from {url} timed out.")
except asyncio.CancelledError:
... | import asyncio
import pytest
from solution import fetch_and_process_data
@pytest.mark.asyncio
async def test_fetch_and_process_data_timeout():
urls = ["http://example.com/data1", "http://example.com/data2"]
timeout = 0.5 # Simulate a timeout for asyncio.sleep
await fetch_and_process_data(urls, timeout)
@... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List\n\nasync def fetch_data(url: str, timeout: float):\n try:\n await asyncio.sleep(timeout)\n print(f\"Fetched dat... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00011272",
"row_id": 11272,
"seed_ids": "[396]"
} | 0.554007 | Docs: Python310_11272 | I | [
"fetch_data",
"fetch_and_process_data"
] | 2 | [
[
"fetch_and_process_data",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8cec503a1c1b627932ec96d489730e3d550ae53b | c58a93febbe904592006b70c26fdd2d90df6321f | |||
v1.0 | instruct | Docs | Docs: Python310_11289_I | #### Objective:
The goal of this exercise is to create a series of functions that interact with floating-point objects in Python, utilizing provided C-API functions (simulated in the task) to manage and manipulate these objects effectively.
#### Problem Statement:
Implement a function that takes a list of numeric stri... | def is_valid_float(num_str: str) -> bool:
"""
Check if the given string can be converted to a valid float.
Input: num_str (str): A numeric string.
Output: bool: True if valid float, False otherwise.
"""
try:
float(num_str)
return True
except ValueError:
return False
... | from solution import is_valid_float, convert_to_float_object, float_info
def test_is_valid_float():
assert is_valid_float("12.34") == True
assert is_valid_float("0.001") == True
assert is_valid_float("-123.456") == True
assert is_valid_float("abc") == False
assert is_valid_float("") == False
as... | [
{
"docstring": "Check if the given string can be converted to a valid float.\nInput: num_str (str): A numeric string.\nOutput: bool: True if valid float, False otherwise.",
"function_declaration": "def is_valid_float(num_str):",
"function_name": "is_valid_float",
"parameter_list": "(num_str)"
},
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_valid_float(num_str: str) -> bool:\n \"\"\"\n Check if the given string can be converted to a valid float.\n Input: num_str (str): A numeric string.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011289",
"row_id": 11289,
"seed_ids": "[59]"
} | 0.563586 | Docs: Python310_11289 | I | [
"is_valid_float",
"convert_to_float_object",
"float_info"
] | 3 | [
[
"convert_to_float_object",
"is_valid_float"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b2eb347456aae86037a708ecda23f0a89f81f0ad | 5836a834958580dad6d53a08ebffda9de68f86d2 | |||
v1.0 | instruct | Docs | Docs: Python310_11292_I | #### Task
You are tasked with implementing a simplified **asyncio-based task scheduler**. This scheduler should be capable of scheduling multiple tasks concurrently, handling task timeouts, and managing task cancellations.
Implement the following three functions:
1. **`async def schedule_tasks(tasks, timeout=None)`... | import asyncio
from typing import List, Tuple, Any
async def run_task(coro, name, timeout=None):
try:
result = await asyncio.wait_for(coro, timeout)
return (name, result)
except asyncio.TimeoutError:
return (name, "Timeout")
async def schedule_tasks(tasks: List[Tuple[str, Any]], timeou... | import asyncio
from solution import run_task, schedule_tasks
async def task_duration(duration, result):
await asyncio.sleep(duration)
return result
def test_run_task_complete():
coro = task_duration(1, "Completed")
name = "Test_Task_Complete"
result = asyncio.run(run_task(coro, name, timeout=3))
... | [
{
"docstring": null,
"function_declaration": "def main():",
"function_name": "main",
"parameter_list": "()"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def run_task(coro, name, timeout=None):\n \"\"\"\n Runs a single task and returns its result or timeout message.\n \"\"\"\n try:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011292",
"row_id": 11292,
"seed_ids": "[317]"
} | 0.627015 | Docs: Python310_11292 | I | [
"run_task",
"schedule_tasks",
"main"
] | 3 | [
[
"schedule_tasks",
"run_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6494fb523e7736b2795dc1f9ad1cbca4f361b6bb | e68a5344aac7b9887d219fa561230d5c668bcca1 | |||
v1.0 | instruct | Docs | Docs: Python310_11345_I | Title: Parallel Data Processing using Concurrent Execution
## Background
You are tasked with designing a data processing system that efficiently handles large datasets by utilizing concurrent execution. You will implement a program that processes data in parallel using the provided `concurrent` module functionalities... | from typing import List
import time
from concurrent.futures import ThreadPoolExecutor
def process_item(data: int) -> int:
"""
Multiplies the input data by 2 and simulates a time-consuming task by sleeping for 1 second.
"""
time.sleep(1) # Simulating time-consuming task
return data * 2
def process... | from solution import process_item, process_data_in_parallel
def test_process_item():
assert process_item(2) == 4
assert process_item(5) == 10
assert process_item(0) == 0
assert process_item(-3) == -6
def test_process_data_in_parallel():
# Test with a list of positive integers
assert process_da... | [
{
"docstring": "Multiplies the input data by 2 and simulates a time-consuming task by sleeping for 1 second.",
"function_declaration": "def process_item(data):",
"function_name": "process_item",
"parameter_list": "(data)"
},
{
"docstring": "Processes a list of integers in parallel using Thre... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef process_item(data: int) -> int:\n \"\"\"\n Multiplies the input dat... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011345",
"row_id": 11345,
"seed_ids": "[206]"
} | 0.603796 | Docs: Python310_11345 | I | [
"process_item",
"process_data_in_parallel"
] | 2 | [
[
"process_data_in_parallel",
"process_item"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e6f298f7962faa06b1025918c4d61ca5deeac8da | de02822604352a1e7fd8885c65e0066d5e966f8e | |||
v1.0 | instruct | Docs | Docs: Python310_11361_I | #### Objective
Implement a mini asynchronous chat server using the `contextvars` module to manage client-specific states.
#### Problem Statement
You need to create a simple asynchronous chat server that supports multiple clients connecting and sending messages. Use the `contextvars` module to manage and store the stat... | import asyncio
import contextvars
from asyncio import StreamReader, StreamWriter
from typing import Dict, Set
client_id_var = contextvars.ContextVar('client_id')
connected_clients: Dict[str, StreamWriter] = {}
async def broadcast_message(message: str, sender_id: str):
for client_id, writer in connected_clients.it... | import asyncio
import pytest
import contextvars
from contextvars import ContextVar
from typing import Dict, Set
from asyncio import StreamReader, StreamWriter
from solution import handle_client, main, connected_clients, client_id_var
@pytest.fixture
def event_loop():
loop = asyncio.new_event_loop()
yield loop
... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport contextvars\n\nclient_id_var = contextvars.ContextVar('client_id')\nclients = {}\n\nasync def handle_client(reader, writer):\n client_id = f\"... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011361",
"row_id": 11361,
"seed_ids": "[392]"
} | 0.573792 | Docs: Python310_11361 | I | [
"broadcast_message",
"handle_client",
"main"
] | 3 | [
[
"handle_client",
"broadcast_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0b059751ac2bc64f9c5a543ce3d7954bd004d9ae | 1a917efc8fab8e8be8cd1e7f9f279b18af035f1d | |||
v1.0 | instruct | Docs | Docs: Python310_11364_I | **Question: Profiling Python Functions with cProfile**
In this assessment, you will demonstrate your understanding of the `cProfile` module by profiling a Python script and analyzing its performance data.
### Task
1. **Profile a Function**
Write a Python function `calculate_prime_factors(n: int) -> List[int]` to ... | import cProfile
import pstats
from typing import List
def calculate_prime_factors(n: int) -> List[int]:
"""
Returns a list of prime factors of the given integer n.
"""
i = 2
factors = []
# Check for the number of times 2 divides n
while n % i == 0:
factors.append(i)
n = n //... | from solution import calculate_prime_factors
def test_calculate_prime_factors():
assert calculate_prime_factors(30) == [2, 3, 5]
assert calculate_prime_factors(987654321) == [3, 3, 17, 17, 379721]
assert calculate_prime_factors(19) == [19]
assert calculate_prime_factors(100) == [2, 2, 5, 5]
assert ... | [
{
"docstring": "Returns a list of prime factors of the given integer n.",
"function_declaration": "def calculate_prime_factors(n):",
"function_name": "calculate_prime_factors",
"parameter_list": "(n)"
},
{
"docstring": "Profiles the calculate_prime_factors function with the input value 98765... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cProfile\nimport pstats\nfrom typing import List\n\ndef calculate_prime_factors(n: int) -> List[int]:\n \"\"\"\n Returns all prime factors of a given integ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011364",
"row_id": 11364,
"seed_ids": "[142]"
} | 0.504098 | Docs: Python310_11364 | I | [
"calculate_prime_factors",
"profile_function",
"analyze_profiling_result"
] | 3 | [
[
"profile_function",
"calculate_prime_factors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e70430e6ba04578e8f5213446aee63de6f600587 | 5c32ef7efd27a23642002ba2c2479afe4d1da035 | |||
v1.0 | instruct | Docs | Docs: Python310_11421_I | ### Advanced Python Functional Programming: Assess Students' Understanding of Iterators, Generators, and Higher-Order Functions
#### Objective:
Create a Python script that processes a log file and extracts information about user activity. Use iterators, generators, and functions from itertools and functools modules to... | import itertools
from collections import defaultdict
def log_iterator(file_path):
"""
Yields each line in the given log file.
"""
with open(file_path, 'r') as file:
for line in file:
yield line.strip()
def parse_log(log_iter):
"""
Parses each line from log iterator into a t... | import pytest
from solution import log_iterator, parse_log, filter_by_action, group_by_user, user_activity_summary
def test_log_iterator(tmp_path):
file_path = tmp_path / "log.txt"
lines = ["2023-10-01 12:00:00, user123, login", "2023-10-01 12:05:00, user123, upload"]
file_path.write_text("\n".join(lines))... | [
{
"docstring": "Yields each line in the given log file.",
"function_declaration": "def log_iterator(file_path):",
"function_name": "log_iterator",
"parameter_list": "(file_path)"
},
{
"docstring": "Parses each line from log iterator into a tuple (timestamp, user_id, action).",
"function_... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\nimport functools\n\ndef log_iterator(file_path):\n \"\"\"\n Returns an iterator that yields each line in the log file.\n \"\"\"\n with ope... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011421",
"row_id": 11421,
"seed_ids": "[78]"
} | 0.605927 | Docs: Python310_11421 | I | [
"log_iterator",
"parse_log",
"filter_by_action",
"group_by_user",
"user_activity_summary"
] | 5 | [
[
"user_activity_summary",
"group_by_user"
],
[
"user_activity_summary",
"log_iterator"
],
[
"user_activity_summary",
"parse_log"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ab9989c651a2792a05dc008730349ccf015a9f02 | 80c855175de19d785b9dafccb001ae1a4357b064 | |||
v1.0 | instruct | Docs | Docs: Pytorch_11493_I | **Problem Statement:**
You are given a 1D signal represented as a PyTorch tensor. Your task is to apply different window functions from the `torch.signal.windows` module to this signal and analyze their effects on the signal by performing a Fast Fourier Transform (FFT). After applying each window function and performi... | import torch
import torch.fft
import matplotlib.pyplot as plt
import numpy as np
def apply_window_and_fft(signal: torch.Tensor, window_function: str) -> torch.Tensor:
"""
Applies a specified window function to the input signal and performs a Fast Fourier Transform (FFT).
Args:
signal (torch.Te... | import torch
from solution import apply_window_and_fft
def test_apply_window_and_fft_hann():
signal = torch.sin(torch.linspace(0, 2 * torch.pi * 5, 500))
spectrum = apply_window_and_fft(signal, 'hann')
assert len(spectrum) == len(signal)
assert torch.max(spectrum).item() > 0
def test_apply_window_and_... | [
{
"docstring": "Applies a specified window function to the input signal and performs a Fast Fourier Transform (FFT).\n\nArgs:\n signal (torch.Tensor): 1D input signal tensor.\n window_function (str): Name of the window function.\n\nReturns:\n torch.Tensor: Magnitude spectrum of the transformed signal."... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.fft\nimport matplotlib.pyplot as plt\nfrom typing import List\n\ndef apply_window_and_fft(signal: torch.Tensor, window_function: str) -> torc... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011493",
"row_id": 11493,
"seed_ids": "[58]"
} | 0.580923 | Docs: Pytorch_11493 | I | [
"apply_window_and_fft",
"compare_window_functions"
] | 2 | [
[
"compare_window_functions",
"apply_window_and_fft"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"torch"
] | false | 28801fe153e8982ada0eed01857b963219a36310 | e9de144f0826afc5c7049da32e4284c52f4dc5c2 | |||
v1.0 | instruct | Docs | Docs: Python310_11503_I | ### Problem Description
You are provided with a list of URLs that need to be fetched asynchronously. There is also a requirement to process the fetched data and save the results to a file. To handle this scenario, you need to implement an asynchronous function in Python using the asyncio module for fetching the URLs, ... | import aiohttp
import asyncio
from typing import List, Callable
async def fetch(url: str) -> str:
"""
Fetches the content of the given URL.
Returns the content as a string, or raises an exception if the fetch fails.
"""
async with aiohttp.ClientSession() as session:
try:
async ... | import asyncio
import pytest
from solution import fetch_and_process
async def sample_process_func(url, content):
return f"Processed content from {url} with length {len(content)}"
@pytest.mark.asyncio
async def test_fetch_and_process():
urls = [
"https://httpbin.org/get",
"https://httpbin.org/d... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import aiohttp\nimport asyncio\nfrom typing import List, Callable\n\nasync def fetch(url: str, session: aiohttp.ClientSession) -> str:\n try:\n async with ses... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011503",
"row_id": 11503,
"seed_ids": "[317]"
} | 0.559539 | Docs: Python310_11503 | I | [
"fetch",
"fetch_and_process"
] | 2 | [
[
"fetch_and_process",
"fetch"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 6df91cdae1758a2ee6ede69eb0d0f0a8aa746daa | fa88a5cbc2cb495613ffc95f7090f821bbe0c6a9 | |||
v1.0 | instruct | Docs | Docs: Scikit_11512_I | **Custom Distance Metric and Kernel Matrix Calculation**
### Objective:
Implement a custom Manhattan distance metric and a custom Linear kernel function, then compute the pairwise distance and kernel matrices for given datasets and verify these calculations against scikit-learn's built-in functions.
### Instructions:... | import numpy as np
def manhattan_distance(a, b):
"""
Returns the Manhattan distance between two 1D numpy arrays a and b.
"""
return np.sum(np.abs(a - b))
def linear_kernel(a, b):
"""
Returns the linear kernel (dot product) between two 1D numpy arrays a and b.
"""
return np.dot(a, b)
... | import numpy as np
import pytest
from sklearn.metrics import pairwise_distances
from sklearn.metrics.pairwise import pairwise_kernels
from solution import manhattan_distance, linear_kernel, pairwise_manhattan_distances, pairwise_linear_kernels
# Example dataset
X = np.array([[2, 3], [3, 5], [5, 8], [1, 0], [2, 1]])
d... | [
{
"docstring": "Returns the Manhattan distance between two 1D numpy arrays a and b.",
"function_declaration": "def manhattan_distance(a, b):",
"function_name": "manhattan_distance",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the linear kernel (dot product) between two 1D numpy arr... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef manhattan_distance(a, b):\n \"\"\"\n Computes the Manhattan distance between two 1D numpy arrays a and b.\n \"\"\"\n return np.sum... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011512",
"row_id": 11512,
"seed_ids": "[38]"
} | 0.567183 | Docs: Scikit_11512 | I | [
"manhattan_distance",
"linear_kernel",
"pairwise_manhattan_distances",
"pairwise_linear_kernels"
] | 4 | [
[
"pairwise_linear_kernels",
"linear_kernel"
],
[
"pairwise_manhattan_distances",
"manhattan_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 36c8d830d063c5744be3e0f91ae7facfa3439de6 | eb71092f05b33dfc948ac455d27688ea9ca450f7 | |||
v1.0 | instruct | Docs | Docs: Python310_11518_I | ### XML Processing with ElementTree
#### Objective
Implement a function that parses, manipulates, and produces XML data using the `xml.etree.ElementTree` module.
#### Problem Statement
A company maintains a database of products in XML format. Each product entry includes details such as the product's ID, name, categor... | import xml.etree.ElementTree as ET
from typing import Optional, Dict
def parse_xml(xml_string: str) -> ET.ElementTree:
"""
Parses an XML string into an ElementTree object.
"""
return ET.ElementTree(ET.fromstring(xml_string))
def find_product_by_id(tree: ET.ElementTree, product_id: str) -> Optional[ET.... | from solution import parse_xml, find_product_by_id, add_product, update_product_price, generate_xml
def test_parse_xml():
xml_string = '<products><product id="p1"><name>Product 1</name></product></products>'
tree = parse_xml(xml_string)
assert tree.getroot().tag == 'products'
def test_find_product_by_id()... | [
{
"docstring": "Parses an XML string into an ElementTree object.",
"function_declaration": "def parse_xml(xml_string):",
"function_name": "parse_xml",
"parameter_list": "(xml_string)"
},
{
"docstring": "Finds a product by its ID in the ElementTree.",
"function_declaration": "def find_pro... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import xml.etree.ElementTree as ET\nfrom typing import Optional, Dict\n\ndef parse_xml(xml_string: str) -> ET.ElementTree:\n \"\"\"\n Parses an XML string into an... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011518",
"row_id": 11518,
"seed_ids": "[283]"
} | 0.546656 | Docs: Python310_11518 | I | [
"parse_xml",
"find_product_by_id",
"add_product",
"update_product_price",
"generate_xml"
] | 5 | [
[
"update_product_price",
"find_product_by_id"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 622d5d21ec12e9f9cc7bda239ba8a9a846b56379 | 75e43d3731048459ae12900fdd93d739a88ff148 | |||
v1.0 | instruct | Docs | Docs: Python310_11549_I | ### Asyncio Futures: Task Scheduling and Management
You are tasked with creating a function that handles multiple asynchronous operations using `asyncio.Future` objects. The function will simulate fetching data from different sources, each with varying delay times. Your goal is to start all fetch tasks simultaneously ... | import asyncio
from typing import List, Tuple
async def fetch_single_source(data: str, delay: int) -> str:
"""
Fetches data after a delay.
"""
await asyncio.sleep(delay)
print(f"{data} fetched in {delay} seconds")
return data
async def fetch_data_in_parallel(sources: List[Tuple[str, int]]) -> ... | import asyncio
from solution import fetch_data_in_parallel
def test_fetch_data_in_parallel():
sources = [('data1', 2), ('data2', 3), ('data3', 1)]
results = asyncio.run(fetch_data_in_parallel(sources))
assert results == ['data3', 'data1', 'data2']
def test_fetch_zero_delay():
sources = [('data1', 0), ... | [] | [
1,
1,
1,
1,
1,
1,
1,
1
] | 8 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def fetch_data(source: Tuple[str, int]) -> str:\n data, delay = source\n await as... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00011549",
"row_id": 11549,
"seed_ids": "[113]"
} | 0.600712 | Docs: Python310_11549 | I | [
"fetch_single_source",
"fetch_data_in_parallel"
] | 2 | [
[
"fetch_data_in_parallel",
"fetch_single_source"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c073a6229d410cd0c780a4adfd3e48a5b46a6cb7 | 06a568fee1d7095e740e7b086d7465f0bbf1a336 | |||
v1.0 | instruct | Docs | Docs: Seaborn_11550_I | ### Question: Advanced Color Palettes with Seaborn
**Objective**:
Demonstrate your understanding of seaborn color palettes by generating various types of color palettes and utilizing them in plots.
**Task**:
1. Implement a function `create_custom_palette()` that returns a customized seaborn color palette.
2. Impleme... | import seaborn as sns
import matplotlib.pyplot as plt
def create_custom_palette():
"""
Creates a custom seaborn color palette by combining predefined palettes.
Returns:
custom_palette (list): List of colors in the palette.
"""
palette1 = sns.color_palette("Set3", 3)
palette2 = sns.... | from solution import create_custom_palette, plot_with_custom_palette, convert_palette_to_hex
import seaborn as sns
import matplotlib.pyplot as plt
def test_create_custom_palette():
palette = create_custom_palette()
assert isinstance(palette, list)
assert len(palette) == 5 # Should create a palette with ex... | [
{
"docstring": "Creates a custom seaborn color palette by combining predefined palettes.\n\nReturns:\n custom_palette (list): List of colors in the palette.",
"function_declaration": "def create_custom_palette():",
"function_name": "create_custom_palette",
"parameter_list": "()"
},
{
"doc... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef create_custom_palette():\n \"\"\"\n Creates a custom seaborn color palette by combining elements fro... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00011550",
"row_id": 11550,
"seed_ids": "[64]"
} | 0.622966 | Docs: Seaborn_11550 | I | [
"create_custom_palette",
"plot_with_custom_palette",
"convert_palette_to_hex"
] | 3 | [
[
"plot_with_custom_palette",
"create_custom_palette"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"seaborn"
] | false | 08f3e73cd2afcd87f8dd2430b9586efd6bb0d0cf | 09cf66b9ea6bce1c3dcbcc0fb0c0cd460af25a72 | |||
v1.0 | instruct | Docs | Docs: Python310_11573_I | #### Objective
The goal of this assessment is to evaluate your understanding of Python generators and your ability to manipulate them effectively.
#### Task
Implement a function `sum_of_squares(n)` that generates and returns the sum of the squares of the first `n` natural numbers using a generator.
#### Details
1. De... | def generate_squares(n):
"""
A generator function that yields the square of numbers from 1 to n.
Parameters:
n (int): The number of terms to generate.
Yields:
int: The square of the current number in the sequence.
"""
for i in range(1, n + 1):
yield i ** 2
def sum_of_squares(n... | from solution import generate_squares, sum_of_squares
def test_generate_squares():
assert list(generate_squares(1)) == [1]
assert list(generate_squares(2)) == [1, 4]
assert list(generate_squares(3)) == [1, 4, 9]
assert list(generate_squares(5)) == [1, 4, 9, 16, 25]
def test_sum_of_squares():
asser... | [
{
"docstring": "A generator function that yields the square of numbers from 1 to n.\n\nParameters:\nn (int): The number of terms to generate.\n\nYields:\nint: The square of the current number in the sequence.",
"function_declaration": "def generate_squares(n):",
"function_name": "generate_squares",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_squares(n):\n \"\"\"\n A generator function that yields the square of numbers from 1 to n.\n\n Parameters:\n n (int): The number of terms to ge... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00011573",
"row_id": 11573,
"seed_ids": "[27]"
} | 0.729984 | Docs: Python310_11573 | I | [
"generate_squares",
"sum_of_squares"
] | 2 | [
[
"sum_of_squares",
"generate_squares"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5fa869e1ae116b00b23413a30b2337644f80e31a | 43c0db126c2b4e69ce7a7e8adfaa5779ef6d25a2 | |||
v1.0 | instruct | Docs | Docs: Pytorch_11627_I | ### Problem: Implementing and Testing Dynamic Shapes in PyTorch
#### Objective:
You are asked to implement a function that performs operations on dynamically shaped tensors and another function that verifies the correct functioning of dynamic shape handling using guards and symbolic sizes.
#### Task:
1. **Function Im... | import torch
import torch._dynamo
def dynamic_operations(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""
Perform a concatenation of two tensors followed by a conditional operation.
Args:
- x (torch.Tensor): Input tensor 1.
- y (torch.Tensor): Input tensor 2.
Returns:
- torch.Tensor... | import pytest
import torch
from solution import dynamic_operations, verify_dynamic_shapes
def test_dynamic_operations_concat_greater_than_two_rows():
x = torch.randn(2, 2)
y = torch.randn(1, 2)
result = dynamic_operations(x, y)
expected = torch.cat([x, y]).mul(2)
assert torch.equal(result, expected... | [
{
"docstring": "Perform a concatenation of two tensors followed by a conditional operation.\n\nArgs:\n- x (torch.Tensor): Input tensor 1.\n- y (torch.Tensor): Input tensor 2.\n\nReturns:\n- torch.Tensor: Result tensor after conditional operations.",
"function_declaration": "def dynamic_operations(x, y):",
... | [
0,
0,
0,
0,
0,
0,
0,
1,
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 dynamic_operations(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Perform a concatenation of two tensors followed by a conditio... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00011627",
"row_id": 11627,
"seed_ids": "[120]"
} | 0.447323 | Docs: Pytorch_11627 | I | [
"dynamic_operations",
"verify_dynamic_shapes"
] | 2 | [
[
"verify_dynamic_shapes",
"dynamic_operations"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 85ef9783d9383b4e73ba1f17fcf0b84845290df7 | 5262ea54220c23aaa779848b458baed36489250f | |||
v1.0 | instruct | Docs | Docs: Python310_11664_I | **Objective:**
To assess the student's understanding of asyncio task management, task synchronization, and exception handling.
**Problem Statement:**
You are required to write an asyncio-based function that simulates a basic server-client interaction using TCP connections. The server will handle multiple clients conc... | import asyncio
async def handle_client(reader, writer):
# Read the data sent by the client
data = await reader.read(100)
message = data.decode()
# Simulate processing time
await asyncio.sleep(2)
# Send a response back to the client
writer.write(data)
await writer.drain()
... | import asyncio
import pytest
from solution import run_server_client_interaction
@pytest.mark.asyncio
async def test_single_client():
port = 8888
message = "Hello Server"
client_count = 1
responses = await run_server_client_interaction(port, message, client_count)
assert len(responses) == client_cou... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n data = await reader.read(100)\n message = data.decode()\n print(f\"Received {message!r} from {writ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011664",
"row_id": 11664,
"seed_ids": "[360]"
} | 0.611621 | Docs: Python310_11664 | I | [
"handle_client",
"run_server",
"client",
"run_server_client_interaction"
] | 4 | [
[
"run_server",
"handle_client"
],
[
"run_server_client_interaction",
"client"
],
[
"run_server_client_interaction",
"run_server"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 22fbd90808500b81303de86c9b73df634f1c103e | 3a558ac5ee44ec612251af734b11126e7b71038b | |||
v1.0 | instruct | Docs | Docs: Python310_11686_I | ### Profiling Functions in Python
In this assessment, you will demonstrate your understanding of Python's `cProfile` and `pstats` modules by profiling a provided function and analyzing the results.
#### Objective
You need to:
1. Profile a given function using the `cProfile` module.
2. Save the profiling results to a ... | def sample_function():
import time
def fibonacci(n):
if n < 0:
raise ValueError("Input should be a non-negative integer")
elif n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
start_time = tim... | def test_profile_function():
profile_function()
# We can't assert specific values in the test for profiling output,
# as the output depends on runtime, environment, and is meant for human analysis.
# The aim here is to ensure that `profile_function` runs without errors. | [
{
"docstring": null,
"function_declaration": "def sample_function():",
"function_name": "sample_function",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def profile_function():",
"function_name": "profile_function",
"parameter_list": "()"
},
{
"d... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sample_function():\n import time\n def fibonacci(n):\n if n < 0:\n raise ValueError(\"Input should be a non-negative integer\")\n eli... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00011686",
"row_id": 11686,
"seed_ids": "[142]"
} | 0.605222 | Docs: Python310_11686 | I | [
"sample_function",
"profile_function"
] | 2 | [
[
"profile_function",
"sample_function"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 424a15149aa45298f8be917d0d730152c16c6643 | 8689f0ed0c9f0be354a9943d5ffe006a717748f2 | |||
v1.0 | instruct | Docs | Docs: Python310_11755_I | ### Quoted-Printable Encoding/Decoding Challenge
You are provided with several utility functions within the `quopri` module in Python, which helps encode and decode MIME quoted-printable data. Your task is to implement a custom encoder and decoder for quoted-printable data with the following constraints:
1. Implement... | def _to_hex(value: int) -> str:
return f'={value:02X}'
def custom_encode(input_string: str, quotetabs: bool = False, header: bool = False) -> str:
encoded_chars = []
for char in input_string:
ascii_code = ord(char)
if header and char == ' ':
encoded_chars.append('_')
eli... | from solution import custom_encode, custom_decode
def test_custom_encode_basic():
assert custom_encode("Hello World!") == 'Hello World!'
def test_custom_encode_non_printable():
assert custom_encode("Hello\nWorld!") == 'Hello=0AWorld!'
def test_custom_encode_space_end_line():
assert custom_encode("Hello W... | [
{
"docstring": null,
"function_declaration": "def _to_hex(value):",
"function_name": "_to_hex",
"parameter_list": "(value)"
},
{
"docstring": null,
"function_declaration": "def custom_encode(input_string, quotetabs=False, header=False):",
"function_name": "custom_encode",
"parame... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def custom_encode(input_string: str, quotetabs: bool = False, header: bool = False) -> str:\n encoded_chars = []\n for i, char in enumerate(input_string):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011755",
"row_id": 11755,
"seed_ids": "[390]"
} | 0.588545 | Docs: Python310_11755 | I | [
"_to_hex",
"custom_encode",
"custom_decode"
] | 3 | [
[
"custom_encode",
"_to_hex"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8ba94e56f4b1f18f8437651475cd1c0a93d4ef9d | 0601c7389ed968a1c63a2fa155bf18e8b4b1587f | |||
v1.0 | instruct | Docs | Docs: Python310_11771_I | You are tasked with creating a Python GUI application using the `tkinter.font` module to handle font customization. Your application should allow users to select a font family, size, weight, and style for a text display. You need to implement the following features:
1. A drop-down menu for selecting a font family from... | import tkinter as tk
from tkinter import font
def apply_font(sample_text, font_family, font_size, font_weight, font_style):
try:
size = int(font_size.get())
except ValueError:
size = 10 # default font size
font_conf = {
"family": font_family.get(),
"size": size,
"we... | import pytest
from unittest.mock import MagicMock, patch
import tkinter as tk
from tkinter import font
from solution import apply_font
@pytest.fixture
def mocked_widgets():
sample_text = MagicMock()
font_family = MagicMock()
font_family.get.return_value = "Courier"
font_size = MagicMock()
font_size... | [
{
"docstring": null,
"function_declaration": "def apply_font(sample_text, font_family, font_size, font_weight, font_style):",
"function_name": "apply_font",
"parameter_list": "(sample_text, font_family, font_size, font_weight, font_style)"
},
{
"docstring": null,
"function_declaration": ... | [
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 tkinter as tk\nfrom tkinter import font\n\ndef apply_font_settings(display_label, font_settings):\n \"\"\"\n Apply the font settings to the display label.\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00011771",
"row_id": 11771,
"seed_ids": "[352]"
} | 0.358216 | Docs: Python310_11771 | I | [
"apply_font",
"setup_app"
] | 2 | [
[
"setup_app",
"apply_font"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4d64038fd00e844c96d075663f508c3b250b8941 | e72d037601396c63369f16fe38e24ec174146140 | |||
v1.0 | instruct | Docs | Docs: Scikit_11809_I | ### Question on Clustering with K-Means
**Context:**
You are tasked to cluster data points using the K-Means clustering algorithm. To deepen your understanding, you will first implement the K-Means algorithm from scratch. Afterward, you will use sklearn's `KMeans` to cluster the same data and compare the results.
**I... | import numpy as np
from sklearn.metrics import silhouette_score, calinski_harabasz_score
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
import pandas as pd
def initialize_centroids(X, k, init='random'):
"""
Initialize centroids for K-Means clustering.
Parameters:
- X: np.n... | from solution import initialize_centroids, assign_clusters, compute_centroids, kmeans
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score, calinski_harabasz_score
def test_initialize_centroids():
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
centroids = init... | [
{
"docstring": "Initialize centroids for K-Means clustering.\n\nParameters:\n- X: np.ndarray, data points\n- k: int, number of clusters\n- init: str, 'random' or 'kmeans++'\n\nReturns:\n- centroids: np.ndarray, initialized centroids",
"function_declaration": "def initialize_centroids(X, k, init='random'):",... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"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\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import silhouette_score, calinski_harabasz_score\nfrom sklearn.cluster im... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011809",
"row_id": 11809,
"seed_ids": "[60]"
} | 0.735439 | Docs: Scikit_11809 | I | [
"initialize_centroids",
"assign_clusters",
"compute_centroids",
"kmeans",
"plot_clusters"
] | 5 | [
[
"kmeans",
"assign_clusters"
],
[
"kmeans",
"compute_centroids"
],
[
"kmeans",
"initialize_centroids"
]
] | 3 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"pandas",
"sklearn"
] | false | b870507662d026f23bb4117aeaf4f20022ae20b8 | 00b79127f67fc703819677adc095466822ca4fb5 | |||
v1.0 | instruct | Docs | Docs: Python310_11827_I | You are working on a Python project that involves updating an old codebase. This codebase uses several deprecated methods and you need to ensure that all deprecations are handled properly without overwhelming the standard output with warning messages during execution. You also need to ensure the warnings are properly c... | import warnings
from typing import Type, List
def custom_warn(message: str, category: Type[Warning], stacklevel: int = 1) -> None:
"""
Issues a warning with the specified message, category, and stacklevel.
"""
warnings.warn(message, category, stacklevel=stacklevel)
class SuppressWarnings:
"""
... | from solution import custom_warn, SuppressWarnings, test_warnings
def test_custom_warn():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
custom_warn("Test deprecation warning.", DeprecationWarning, stacklevel=2)
assert len(w) == 1
assert issubclass(w... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import warnings\nfrom typing import Type, List\n\ndef custom_warn(message: str, category: Type[Warning], stacklevel: int = 1) -> None:\n \"\"\"\n Issues a warning... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00011827",
"row_id": 11827,
"seed_ids": "[125]"
} | 0.395589 | Docs: Python310_11827 | I | [
"custom_warn",
"test_warnings"
] | 2 | [
[
"test_warnings",
"custom_warn"
]
] | 1 | [] | false | [
"SuppressWarnings"
] | true | pytest | true | [] | true | 0f9c5b5e4e6c699506e14bda124fc45e8b46076d | d2eeaaa5099c9d392b0bf16fbc127a5e323f5197 | |||
v1.0 | instruct | Docs | Docs: Python310_11878_I | You are tasked to design and implement a Python program that calculates the determinants of multiple 2x2 matrices using multiple processes to expedite the computation. The goal is to demonstrate proficiency in creating and managing processes, sharing data between them, and coordinating their activities.
### Requiremen... | import multiprocessing
from typing import List
def compute_determinant(matrix: List[List[int]]) -> int:
"""
Computes the determinant of a 2x2 matrix.
Parameters:
matrix (List[List[int]]): A 2x2 matrix represented as a list of two lists,
each containing two int... | import pytest
from multiprocessing import Queue
from solution import compute_determinant, worker
def test_compute_determinant():
assert compute_determinant([[1, 2], [3, 4]]) == -2
assert compute_determinant([[2, 0], [1, 2]]) == 4
assert compute_determinant([[0, 1], [1, 0]]) == -1
assert compute_determi... | [
{
"docstring": "Computes the determinant of a 2x2 matrix.\n\nParameters:\n matrix (List[List[int]]): A 2x2 matrix represented as a list of two lists,\n each containing two integers.\n\nReturns:\n int: The determinant of the matrix.",
"function_declaration": "def compute_de... | [
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 multiprocessing\nfrom typing import List\n\ndef compute_determinant(matrix: List[List[int]]) -> int:\n \"\"\"\n Calculate the determinant of a 2x2 matrix.\... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00011878",
"row_id": 11878,
"seed_ids": "[338]"
} | 0.485241 | Docs: Python310_11878 | I | [
"compute_determinant",
"worker",
"calculate_determinants"
] | 3 | [
[
"worker",
"compute_determinant"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 35486415870121fb397a1ad957afad000e47176b | 86242b9285da78abd3e0237008bade0e926160f8 | |||
v1.0 | instruct | Docs | Docs: Python310_11920_I | **Objective**: Demonstrate your understanding of the `glob` module by writing functions that make use of its capabilities.
**Problem Statement**:
You are given a root directory path `"root_dir"` and different file patterns. Your task is to implement three functions:
1. `list_all_files_with_pattern(root_dir: str, pat... | import glob
from typing import List
def list_all_files_with_pattern(root_dir: str, pattern: str) -> List[str]:
"""
Returns a list of all files in the root_dir that match the specified pattern.
"""
return glob.glob(f"{root_dir}/**/{pattern}", recursive=True)
def count_files_with_pattern(root_dir: str, ... | import os
import tempfile
from solution import list_all_files_with_pattern, count_files_with_pattern, escape_and_list_files_with_pattern
def test_list_all_files_with_pattern():
with tempfile.TemporaryDirectory() as root_dir:
# Create some test files
open(os.path.join(root_dir, 'file1.txt'), 'w').cl... | [
{
"docstring": "Returns a list of all files in the root_dir that match the specified pattern.",
"function_declaration": "def list_all_files_with_pattern(root_dir, pattern):",
"function_name": "list_all_files_with_pattern",
"parameter_list": "(root_dir, pattern)"
},
{
"docstring": "Returns th... | [
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 glob\nimport os\nfrom typing import List\n\ndef list_all_files_with_pattern(root_dir: str, pattern: str) -> List[str]:\n \"\"\"\n Returns a list of all fil... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00011920",
"row_id": 11920,
"seed_ids": "[354]"
} | 0.706594 | Docs: Python310_11920 | I | [
"list_all_files_with_pattern",
"count_files_with_pattern",
"escape_and_list_files_with_pattern"
] | 3 | [
[
"count_files_with_pattern",
"list_all_files_with_pattern"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | db826fbc382bd8c4103a17711d8d617f4a3018bb | cc4d8b1207ff3d887572ca90c0f6aa582a2f24ae | |||
v1.0 | instruct | Docs | Docs: Python310_11984_I | Working with the `marshal` Module
#### Objective:
Write a program that takes a complex nested data structure, serializes it using the `marshal` module, and then deserializes it back. Your task is to ensure that the data integrity is maintained and handle any possible unsupported types specified by the `marshal` module... | import marshal
def serialize_structure(data, file_path, version=4):
"""
Serializes the given data structure to the specified file using marshal.
Parameters:
- data: The data structure to be serialized.
- file_path: The file path where the data should be serialized to.
- version: The versio... | import os
import pytest
from solution import serialize_structure, deserialize_structure
def test_serialize_and_deserialize_int():
data = 123
file_path = "test_serialize_and_deserialize_int.bin"
serialize_structure(data, file_path)
result = deserialize_structure(file_path)
assert result == data
... | [
{
"docstring": "Serializes the given data structure to the specified file using marshal.\n\nParameters:\n- data: The data structure to be serialized.\n- file_path: The file path where the data should be serialized to.\n- version: The version of the marshal format to use.\n\nRaises:\n- ValueError if the data con... | [
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 marshal\n\ndef serialize_structure(data, file_path, version=4):\n \"\"\"\n Serializes the given data structure to the specified file using marshal.\n \n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00011984",
"row_id": 11984,
"seed_ids": "[190]"
} | 0.524483 | Docs: Python310_11984 | I | [
"serialize_structure",
"deserialize_structure",
"test_serialization"
] | 3 | [
[
"test_serialization",
"deserialize_structure"
],
[
"test_serialization",
"serialize_structure"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 856619fc27bd321b6f3b04a55345585444f841c7 | be7327eb55aabe02b4459be93429c1da2560ce58 | |||
v1.0 | instruct | Docs | Docs: Flask_12044_I | ### Flask Deployment Challenge
You have developed a simple Flask application and now it's time to deploy it to a production environment. Your task is to write a script that handles the following deployment steps:
1. **Build the Application**:
- Create a distribution (`.whl`) file of the Flask application using the... | import os
import secrets
import subprocess
def build_application():
"""
Builds the Flask application into a distribution file using the build tool.
"""
subprocess.run(['pip', 'install', 'build'], check=True)
subprocess.run(['python', '-m', 'build'], check=True)
print("Application built successf... | import os
import secrets
from solution import configure_application, build_application, initialize_database, run_application
from unittest.mock import patch, mock_open, call
def test_generate_secret_key():
secret_key = secrets.token_urlsafe(32)
assert len(secret_key) > 0
@patch('builtins.open', new_callable=m... | [
{
"docstring": "Builds the Flask application into a distribution file using the build tool.",
"function_declaration": "def build_application():",
"function_name": "build_application",
"parameter_list": "()"
},
{
"docstring": "Initializes the database for the Flask application.",
"functio... | [
0,
0,
0,
1,
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": "import os\nimport subprocess\nimport secrets\n\ndef build_application():\n \"\"\"\n Build the Flask application to create a .whl distribution file.\n \"\"\"\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00012044",
"row_id": 12044,
"seed_ids": "[54]"
} | 0.554058 | Docs: Flask_12044 | I | [
"build_application",
"initialize_database",
"configure_application",
"run_application",
"deploy"
] | 5 | [
[
"deploy",
"build_application"
],
[
"deploy",
"configure_application"
],
[
"deploy",
"initialize_database"
],
[
"deploy",
"run_application"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 18b00e415981b340654118a515578b0b09a925f8 | 89759dfb6c47503b6299bf450b9579fc4b721d74 | |||
v1.0 | instruct | Docs | Docs: Scikit_12090_I | #### Objective
Write a Python program that performs clustering on a given dataset using multiple clustering algorithms from the scikit-learn library and evaluates the performance of each clustering method.
#### Requirements
1. Implement clustering using the following algorithms:
- K-Means
- DBSCAN
- Agglomera... | import pandas as pd
from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
from sklearn.metrics import adjusted_rand_score, silhouette_score
def load_data(file_path):
"""
Load the dataset from the CSV file.
Args:
- file_path (str): Path to the CSV file.
Returns:
- pd.Data... | import pytest
import pandas as pd
from io import StringIO
from solution import load_data, apply_clustering_and_evaluate
def test_load_data():
data = """Feature1,Feature2,Feature3
5.1,3.5,1.4
4.9,3.0,1.4
4.7,3.2,1.3
4.6,3.1,1.5
5.0,3.6,1.4"""
# Simulate a CSV file using StringIO
df ... | [
{
"docstring": "Load the dataset from the CSV file.\n\nArgs:\n- file_path (str): Path to the CSV file.\n\nReturns:\n- pd.DataFrame: Loaded dataset.",
"function_declaration": "def load_data(file_path):",
"function_name": "load_data",
"parameter_list": "(file_path)"
},
{
"docstring": "Apply th... | [
0,
0,
0,
1,
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 pandas as pd\nfrom sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering\nfrom sklearn.metrics import adjusted_rand_score, silhouette_score\n\ndef load_... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00012090",
"row_id": 12090,
"seed_ids": "[60]"
} | 0.665346 | Docs: Scikit_12090 | I | [
"load_data",
"apply_clustering_and_evaluate"
] | 2 | [
[
"apply_clustering_and_evaluate",
"load_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas",
"sklearn"
] | false | 9a466f435cb67341ba158b01c39b6254f6c4bf3c | f7027eb964f708f07a9630a439c9c5ac8ee4cc47 | |||
v1.0 | instruct | Docs | Docs: Python310_12094_I | **Coding Assessment Question: Performance Evaluation of Sorting Algorithms**
**Objective:**
The objective of this task is for you to implement and compare the performance of two different sorting algorithms: Merge Sort and Quick Sort. You will use Python's `timeit` module to measure and compare the execution times of ... | import random
import timeit
def merge_sort(arr):
"""Implements the merge sort algorithm."""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
... | from solution import merge_sort, quick_sort, generate_random_list
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_multiple_elements():
assert merge_sort([3, 1, 4, 1, 5, 9, 2, 6, 5]) == [1, 1, 2, 3, 4, 5,... | [
{
"docstring": "Implements the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport timeit\n\ndef merge_sort(arr):\n if len(arr) <= 1:\n return arr\n\n def merge(left, right):\n sorted_arr = []\n left_id... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012094",
"row_id": 12094,
"seed_ids": "[328]"
} | 0.550767 | Docs: Python310_12094 | I | [
"merge_sort",
"merge",
"quick_sort",
"generate_random_list",
"main"
] | 5 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 40a90ee6a0096e864a3c641c993ca437827db38f | d4a66fd14f37fce0439fbd65ba2272fa417ec35b | |||
v1.0 | instruct | Docs | Docs: Python310_12135_I | **Problem Statement: Building a Secure CGI Script for User Registration**
You are tasked with creating a CGI script for a user registration form. The form is expected to gather the following details from the users:
1. Username (must be unique)
2. Email
3. Password
4. Profile Picture (Optional, File Upload)
Your scrip... | #!/usr/bin/env python3
import cgi
import cgitb
import re
import os
cgitb.enable() # This line helps with debugging.
UPLOAD_DIR = "uploads/"
def validate_username(username):
# Ensure the username is alphanumeric and length is between 3 and 20 characters.
return re.match(r'^[a-zA-Z0-9]{3,20}$', username)
de... | import pytest
import os
from solution import validate_username, is_username_unique, save_username
def setup_module(module):
# Setup code (similar to a fixture in pytest)
if os.path.exists("usernames.txt"):
os.remove("usernames.txt")
def teardown_module(module):
if os.path.exists("usernames.txt"):
... | [
{
"docstring": null,
"function_declaration": "def validate_username(username):",
"function_name": "validate_username",
"parameter_list": "(username)"
},
{
"docstring": null,
"function_declaration": "def is_username_unique(username, datafile='usernames.txt'):",
"function_name": "is_us... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"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\nimport os\n\ncgitb.enable() # This line helps with debugging.\n\nUPLOAD_DIR = \"uploads/\"\n\ndef valida... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012135",
"row_id": 12135,
"seed_ids": "[183]"
} | 0.446219 | Docs: Python310_12135 | I | [
"validate_username",
"is_username_unique",
"save_username",
"handle_form_submission",
"generate_html_response",
"main"
] | 6 | [
[
"handle_form_submission",
"is_username_unique"
],
[
"handle_form_submission",
"save_username"
],
[
"handle_form_submission",
"validate_username"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 4d2b5d8d033d32369ce42b044833d1aa26ecd7c6 | 8d2675f4d9233aea73371a8904fafd022907f784 | |||
v1.0 | instruct | Docs | Docs: Python310_12149_I | #### Objective:
The goal is to assess your ability to use the `unittest.mock` module for creating and using mock objects and making assertions about their interactions.
#### Problem Statement:
You are developing a data processing pipeline for a software system, and you need to write unit tests for a function that pro... | def save_to_database(value):
# Imagine this is an external service that saves data to a database
pass
def log(message):
# Imagine this is an external service for logging messages
pass
def process_and_save_data(data):
"""
This function processes the input data (a dictionary), performs some calc... | from unittest.mock import patch
from solution import process_and_save_data
def test_successful_saving():
with patch('solution.save_to_database') as mock_save, \
patch('solution.log') as mock_log:
mock_save.return_value = True
result = process_and_save_data({'value': 5})
mock_save.a... | [
{
"docstring": null,
"function_declaration": "def save_to_database(value):",
"function_name": "save_to_database",
"parameter_list": "(value)"
},
{
"docstring": null,
"function_declaration": "def log(message):",
"function_name": "log",
"parameter_list": "(message)"
},
{
"d... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def save_to_database(value):\n # Imagine this is an external service that saves data to a database\n pass\n\ndef log(message):\n # Imagine this is an external ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012149",
"row_id": 12149,
"seed_ids": "[375]"
} | 0.587792 | Docs: Python310_12149 | I | [
"save_to_database",
"log",
"process_and_save_data"
] | 3 | [
[
"process_and_save_data",
"log"
],
[
"process_and_save_data",
"save_to_database"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6f21ef2ef2b1bd9fe7c2e40159a8eea504758258 | 9bc6c7d169240b032e6107d3ba069f887da08521 | |||
v1.0 | instruct | Docs | Docs: Python310_12151_I | **Objective:**
Implement a Python function that uses concurrent processing to calculate a large number of prime numbers efficiently and correctly handles errors and timeouts.
**Question:**
Write a function `calculate_primes(numbers, max_workers=4, timeout=None)` that takes a list of integers and returns a dictionary ... | from typing import List, Dict
import concurrent.futures
import logging
def is_prime(n: int) -> bool:
"""
Determines if a number is prime.
"""
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
sqrt_n = int(n ** 0.5) + 1
for i in range(3, sq... | from solution import calculate_primes
def test_calculate_primes_basic():
numbers = [2, 3, 4, 5, 6]
result = calculate_primes(numbers)
assert result == {2: True, 3: True, 4: False, 5: True, 6: False}
def test_large_prime_number():
numbers = [99999941] # Known large prime number
result = calculate_... | [
{
"docstring": "Determines if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Calculate the primality of a list of numbers using concurrent processing.",
"function_declaration": "def calculate_primes... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict\n\ndef is_prime(n: int) -> bool:\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n re... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012151",
"row_id": 12151,
"seed_ids": "[347]"
} | 0.631346 | Docs: Python310_12151 | I | [
"is_prime",
"calculate_primes"
] | 2 | [
[
"calculate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0f5119413d0b5a5426f64f44ca524c44329e5819 | 2ac0c09ad0177707bec01ccf1db89fed511962f9 | |||
v1.0 | instruct | Docs | Docs: Python310_12176_I | #### Objective:
You are tasked with creating a Python script that simulates a complex function call scenario. Additionally, you need to write a SystemTap script that traces and outputs the function call and return hierarchy for your Python script.
#### Requirements:
1. **Python Script:**
- Create a Python script n... | def main_function():
try:
func_a()
except Exception as e:
print("Exception in main_function:", e)
def func_a():
func_b()
func_d()
def func_b():
for i in range(3):
try:
func_c(i)
except ValueError as e:
print(f"Exception caught in func_b: {e}"... | def test_func_c_raises():
"""
Test that func_c raises a ValueError when x is even.
"""
try:
func_c(2)
except ValueError as e:
assert str(e) == "Intentional Error: 2 is even"
def test_func_c_no_exception():
"""
Test that func_c does not raise an error when x is odd.
"... | [
{
"docstring": null,
"function_declaration": "def main_function():",
"function_name": "main_function",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def func_a():",
"function_name": "func_a",
"parameter_list": "()"
},
{
"docstring": null,
"fu... | [
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": "# complex_call_scenario.py\n\ndef main_function():\n try:\n func_a()\n except Exception as e:\n print(\"Exception in main_function:\", e)\n\ndef fun... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00012176",
"row_id": 12176,
"seed_ids": "[79]"
} | 0.5189 | Docs: Python310_12176 | I | [
"main_function",
"func_a",
"func_b",
"func_c",
"func_d",
"func_e",
"func_f"
] | 7 | [
[
"func_a",
"func_b"
],
[
"func_a",
"func_d"
],
[
"func_b",
"func_c"
],
[
"func_d",
"func_e"
],
[
"func_d",
"func_f"
],
[
"main_function",
"func_a"
]
] | 6 | [] | false | [] | false | pytest | false | [] | true | 941cba362cdf830a533b4aa6911c1aedb527234b | cc36087d54db4cb259253f0dd63c0be973286bca | |||
v1.0 | instruct | Docs | Docs: Pytorch_12226_I | #### Objective
Your task is to create a PyTorch-based application that demonstrates understanding and implementation of reproducibility in every step. This will test your knowledge of handling randomness and ensuring consistent results across multiple runs.
#### Problem Statement
Create a PyTorch script that:
1. Initi... | import torch
import numpy as np
import random
from torch.utils.data import DataLoader, TensorDataset
def seed_all(seed):
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
def seed_worker(worker_id):
w... | from solution import reproducible_pytorch_app
def test_tensor_size_5():
reproducible_pytorch_app(5)
def test_tensor_size_10():
reproducible_pytorch_app(10)
def test_reproducibility_check():
seed = 0
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.benchm... | [
{
"docstring": null,
"function_declaration": "def seed_all(seed):",
"function_name": "seed_all",
"parameter_list": "(seed)"
},
{
"docstring": null,
"function_declaration": "def seed_worker(worker_id):",
"function_name": "seed_worker",
"parameter_list": "(worker_id)"
},
{
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport numpy as np\nimport random\nfrom torch.utils.data import DataLoader, TensorDataset\n\ndef seed_all(seed):\n torch.manual_seed(seed)\n np.rand... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012226",
"row_id": 12226,
"seed_ids": "[174]"
} | 0.628685 | Docs: Pytorch_12226 | I | [
"seed_all",
"seed_worker",
"reproducible_pytorch_app"
] | 3 | [
[
"reproducible_pytorch_app",
"seed_all"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"torch"
] | false | d6cb5d099b9c0a5a9b6aa7c0f9e5dd91027a3939 | 230943a6798cb79c26a405538c273ef32360728a | |||
v1.0 | instruct | Docs | Docs: Python310_12269_I | ### Asynchronous File Processing with Timeout and Shielding
**Problem Statement:**
You are tasked with creating an asynchronous file processing system. The system will read multiple files concurrently, process their contents (in this case, converting all text to uppercase), and save the processed content back to the ... | import asyncio
import os
async def process_file(file_path, timeout):
try:
# Read file contents
async with aiofiles.open(file_path, 'r') as f:
content = await f.read()
# Simulate processing delay
await asyncio.sleep(0.1) # Simulate processing time
# Con... | import asyncio
import os
import pytest
from solution import process_files
@pytest.fixture
def setup_files(tmp_path):
file1 = tmp_path / "file1.txt"
file2 = tmp_path / "file2.txt"
file3 = tmp_path / "file3.txt"
file1.write_text("hello world")
file2.write_text("asyncio is fun!")
file3.write_... | [] | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport aiofiles\n\nasync def process_file(file_path, timeout):\n try:\n async with aiofiles.open(file_path, mode='r') as f:\n conte... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00012269",
"row_id": 12269,
"seed_ids": "[317]"
} | 0.543328 | Docs: Python310_12269 | I | [
"process_file",
"shield_file_processing",
"process_files"
] | 3 | [
[
"process_files",
"shield_file_processing"
],
[
"shield_file_processing",
"process_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8c3b3c236af1e72cf262b6b4e22fbac0a142a9d7 | 9bbd2a6a690fe5fee51231bd528f44e061069d5e | |||
v1.0 | instruct | Docs | Docs: Python310_12429_I | **Objective:**
Implement a function that computes the factorial of a large number in a parallel fashion using the `concurrent.futures` module.
**Task Description:**
You are required to write a function `parallel_factorial(n: int) -> int` that calculates the factorial of a given large integer `n` using parallel compu... | import concurrent.futures
from functools import reduce
import operator
def factorial_partial(start, end):
"""Compute partial factorial from `start` to `end` (both inclusive)"""
result = 1
for i in range(start, end + 1):
result *= i
return result
def parallel_factorial(n: int) -> int:
if n ... | from solution import parallel_factorial
def test_parallel_factorial_small_numbers():
assert parallel_factorial(0) == 1
assert parallel_factorial(1) == 1
assert parallel_factorial(2) == 2
assert parallel_factorial(3) == 6
assert parallel_factorial(4) == 24
assert parallel_factorial(5) == 120
de... | [
{
"docstring": "Compute partial factorial from `start` to `end` (both inclusive)",
"function_declaration": "def factorial_partial(start, end):",
"function_name": "factorial_partial",
"parameter_list": "(start, end)"
},
{
"docstring": null,
"function_declaration": "def parallel_factorial(... | [
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 concurrent.futures\nfrom functools import reduce\nfrom operator import mul\nfrom itertools import islice\n\ndef chunked_iterable(iterable, size):\n it = iter(... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012429",
"row_id": 12429,
"seed_ids": "[224]"
} | 0.656602 | Docs: Python310_12429 | I | [
"factorial_partial",
"parallel_factorial"
] | 2 | [
[
"parallel_factorial",
"factorial_partial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c9bf3f3c60e8e3795604bb2deabc3931c99825a0 | 704d4309fa472690ba757c12c1e79f2f9d4bcc1a | |||
v1.0 | instruct | Docs | Docs: Python310_12443_I | ### Question: Building an Asynchronous Task Manager
You are tasked with building an asynchronous task manager using Python's `asyncio` library. Your manager will handle multiple tasks that simulate asynchronous I/O operations such as network requests or database queries. The goal is to implement a system that can run ... | import asyncio
async def perform_task(task_id: int, duration: float) -> int:
"""
Simulates an asynchronous task with given task_id and duration.
Args:
task_id (int): The ID of the task.
duration (float): The duration for which the task will run.
Returns:
int: The task_id upon comp... | from solution import run_task_manager
import pytest
def test_run_task_manager():
tasks = [(1, 1), (2, 2), (3, 0.5)]
results = run_task_manager(tasks)
# Since asyncio.gather keeps the order of the tasks as in the input
# we expect results to be in order of task IDs
assert results == [1, 2,... | [
{
"docstring": "Runs the asynchronous task manager.\n\nArgs:\ntasks (list of tuples): Each tuple contains task_id and duration.\n\nReturns:\nlist of int: The task_ids of all completed tasks.",
"function_declaration": "def run_task_manager(tasks):",
"function_name": "run_task_manager",
"parameter_lis... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def perform_task(task_id: int, duration: float) -> int:\n \"\"\"\n Simulates an asynchronous I/O operation.\n \n Args:\n task_id ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012443",
"row_id": 12443,
"seed_ids": "[270]"
} | 0.635933 | Docs: Python310_12443 | I | [
"perform_task",
"task_manager",
"run_task_manager"
] | 3 | [
[
"run_task_manager",
"task_manager"
],
[
"task_manager",
"perform_task"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4a1207d80e1cdecc7ca73885fc062f0bb13a12c9 | 2ad31c6cebca41eff6a68bc85b68a9d9d62f9e84 | |||
v1.0 | instruct | Docs | Docs: Pandas_12454_I | You have been provided with a DataFrame that contains information about several machines and their status during different time periods. The DataFrame `df` has a nullable boolean column 'status' that indicates whether each machine was operating (`True`), not operating (`False`), or if the information is unavailable (`N... | import pandas as pd
def calculate_operation_percentage(df):
"""
Calculate the percentage of time each machine was operational.
Parameters:
- df: pandas DataFrame with columns 'machine_id', 'time_period', and 'status'
Returns:
- A dictionary with machine_id as keys and their operation ... | from solution import calculate_operation_percentage, filter_machines
import pandas as pd
def test_calculate_operation_percentage():
data = {
'machine_id': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'time_period': ['2021-Q1', '2021-Q2', '2021-Q3', '2021-Q1', '2021-Q2', '2021-Q3', '2021-Q1', '2021-Q2', '2021-Q3'],... | [
{
"docstring": "Calculate the percentage of time each machine was operational.\n\nParameters:\n- df: pandas DataFrame with columns 'machine_id', 'time_period', and 'status'\n\nReturns:\n- A dictionary with machine_id as keys and their operation percentage as values",
"function_declaration": "def calculate_o... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\n\ndef calculate_operation_percentage(df):\n \"\"\"\n Calculates the percentage of time each machine was operational over all the time periods... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012454",
"row_id": 12454,
"seed_ids": "[25]"
} | 0.649152 | Docs: Pandas_12454 | I | [
"calculate_operation_percentage",
"filter_machines"
] | 2 | [
[
"filter_machines",
"calculate_operation_percentage"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | 24e1307e26b6de7ed7803adab9a666a7b3bb16c2 | 4f9c4524b3b82a1d7e4e47a3d5a0e5450e1cbf2e | |||
v1.0 | instruct | Docs | Docs: Pandas_12529_I | Analyzing Soccer Player Statistics using Pandas
**Objective:**
To assess your ability to manipulate and analyze data using the pandas library.
**Problem Statement:**
You are provided with a CSV file that contains statistics of various soccer players. The CSV file has the following columns:
- `Player`: Name of the p... | import pandas as pd
import matplotlib.pyplot as plt
def load_data(file_path):
"""
Load the data from the provided CSV file into a pandas DataFrame.
"""
return pd.read_csv(file_path)
def basic_data_exploration(df):
"""
Perform basic data exploration: display first 10 rows, summary statistics,
... | import pandas as pd
import pytest
from solution import (
load_data,
basic_data_exploration,
handle_missing_values,
create_goal_contribution,
filter_appearances,
average_goal_contribution_per_team,
top_players_by_goal_contribution,
nationality_with_most_players,
plot_avg_goal_contribu... | [
{
"docstring": "Load the data from the provided CSV file into a pandas DataFrame.",
"function_declaration": "def load_data(file_path):",
"function_name": "load_data",
"parameter_list": "(file_path)"
},
{
"docstring": "Perform basic data exploration: display first 10 rows, summary statistics,... | [
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 matplotlib.pyplot as plt\n\ndef read_data(file_path):\n \"\"\"\n Reads data from a CSV file into a DataFrame.\n \"\"\"\n return ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00012529",
"row_id": 12529,
"seed_ids": "[36]"
} | 0.728971 | Docs: Pandas_12529 | I | [
"load_data",
"basic_data_exploration",
"handle_missing_values",
"create_goal_contribution",
"filter_appearances",
"average_goal_contribution_per_team",
"top_players_by_goal_contribution",
"nationality_with_most_players",
"plot_avg_goal_contribution_per_position",
"analyze_soccer_stats"
] | 10 | [
[
"analyze_soccer_stats",
"average_goal_contribution_per_team"
],
[
"analyze_soccer_stats",
"basic_data_exploration"
],
[
"analyze_soccer_stats",
"create_goal_contribution"
],
[
"analyze_soccer_stats",
"filter_appearances"
],
[
"analyze_soccer_stats",
"handle_... | 9 | [] | false | [] | false | pytest | true | [
"matplotlib",
"pandas"
] | false | 1abe12d28fcdc897002b78326d4f3e727d85fd05 | f769b8ce9eb232803d07a9a97fd77c33e596e8e4 | |||
v1.0 | instruct | Docs | Docs: Scikit_12534_I | ### Question: Optimizing Machine Learning Model Performance
#### Problem Statement:
You are given a high-dimensional dataset for a binary classification task. Your objective is to implement a machine learning pipeline using `scikit-learn` that:
1. **Optimizes prediction latency** by choosing an appropriate model and a... | import numpy as np
import time
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
def calculate_sparsity(X):
"""
Calculate the sparsity ratio of the input feature matrix X.
Sparsity ratio is defined as the fraction of zero elements to the total elements.
"""
r... | import numpy as np
from solution import calculate_sparsity, train_model, predict_performance, model_complexity_analysis, main
def generate_dummy_data(n_samples=100, n_features=10):
"""
Generate dummy data for testing purposes.
"""
np.random.seed(42)
X = np.random.randn(n_samples, n_features)
y ... | [
{
"docstring": "Calculate the sparsity ratio of the input feature matrix X.\nSparsity ratio is defined as the fraction of zero elements to the total elements.",
"function_declaration": "def calculate_sparsity(X):",
"function_name": "calculate_sparsity",
"parameter_list": "(X)"
},
{
"docstrin... | [
0,
0,
0,
1,
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 numpy as np\nimport time\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\nfrom scipy.sparse import csr_matrix\n\ndef ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00012534",
"row_id": 12534,
"seed_ids": "[64]"
} | 0.497265 | Docs: Scikit_12534 | I | [
"calculate_sparsity",
"train_model",
"predict_performance",
"model_complexity_analysis",
"main"
] | 5 | [
[
"model_complexity_analysis",
"predict_performance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | e0fe75a72fdd6496997fc65b465565aaf9c1b417 | 1ef958d27251a3b2f682664d83def2bc2448eddd | |||
v1.0 | instruct | Docs | Docs: Scikit_12537_I | ### Custom Scoring Function and Model Evaluation with Cross-Validation
#### Objective
To assess the students' understanding of custom scoring functions, cross-validation, and the use of advanced evaluation metrics in scikit-learn.
#### Problem Statement
You are given a dataset `X` (features) and `y` (target labels). ... | from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
from sklearn.metrics import make_scorer
import numpy as np
def custom_scorer(y_true, y_pred):
"""
Custom scoring function to calculate mean squared l... | from solution import custom_scorer, evaluate_model_with_custom_scorer, grid_search_with_custom_scorer
import numpy as np
def test_custom_scorer():
y_true = np.array([3, 5, 2.5, 7])
y_pred = np.array([2.5, 5, 4, 8])
expected_msle = np.mean((np.log1p(y_true) - np.log1p(y_pred)) ** 2)
assert custom_scorer... | [
{
"docstring": "Custom scoring function to calculate mean squared logarithmic error (MSLE).",
"function_declaration": "def custom_scorer(y_true, y_pred):",
"function_name": "custom_scorer",
"parameter_list": "(y_true, y_pred)"
},
{
"docstring": "Evaluates a RandomForestRegressor model using ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nfrom sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV\nfrom... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012537",
"row_id": 12537,
"seed_ids": "[25]"
} | 0.717762 | Docs: Scikit_12537 | I | [
"custom_scorer",
"evaluate_model_with_custom_scorer",
"grid_search_with_custom_scorer"
] | 3 | [
[
"evaluate_model_with_custom_scorer",
"custom_scorer"
],
[
"grid_search_with_custom_scorer",
"custom_scorer"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | c4b6f78105866b13f5c0b56bde10245bd9111b90 | 347f3eba35dfcdfbe2f85c294b26abe3be2d2da9 | |||
v1.0 | instruct | Docs | Docs: Pytorch_12538_I | ### Custom Profiling Callback with PyTorch
In this task, you are asked to implement a custom profiling callback in PyTorch using Python. You will use `torch.autograd.profiler` to measure the time taken by specific operations in a given neural network model.
### Requirements
1. Implement a neural network model using... | import torch
import torch.nn as nn
import torch.autograd.profiler as profiler
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.layer1 = nn.Linear(10, 20)
self.layer2 = nn.Linear(20, 10)
self.layer3 = nn.Linear(10, 5)
def forward(self, x... | from solution import SimpleModel, profile_model
import torch
def test_model_structure():
model = SimpleModel()
assert hasattr(model, 'layer1'), "Layer 1 is missing"
assert hasattr(model, 'layer2'), "Layer 2 is missing"
assert hasattr(model, 'layer3'), "Layer 3 is missing"
assert isinstance(model.la... | [] | [
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 torch\nimport torch.nn as nn\nimport torch.autograd.profiler as profiler\n\nclass SimpleModel(nn.Module):\n def __init__(self):\n super(SimpleModel, se... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00012538",
"row_id": 12538,
"seed_ids": "[162]"
} | 0.584759 | Docs: Pytorch_12538 | I | [
"custom_profiler_callback",
"profile_model",
"main"
] | 3 | [
[
"profile_model",
"custom_profiler_callback"
]
] | 1 | [] | false | [
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | 86a86409690ec85af7bac06bc2055bdef513202c | ea7b7991ed1f1dd7c23d26e3d6d1b24c908d0a58 | |||
v1.0 | instruct | Docs | Docs: Python310_12559_I | ### Python C API: Tuple and Struct Sequence Manipulation
Using the Python C API, write a Python program that accomplishes the following tasks:
1. **Check Tuple Type**:
Create a C function that checks whether a given Python object is a tuple and another that checks if it is exactly a tuple type (not a subtype).
2... | def is_tuple(obj):
"""
Check if the object is a tuple.
"""
return isinstance(obj, tuple)
def is_exact_tuple(obj):
"""
Check if the object type is exactly tuple (not a subtype).
"""
return type(obj) is tuple
def create_and_populate_tuple():
"""
Create a tuple of length 5, popula... | from solution import is_tuple, is_exact_tuple, create_and_populate_tuple, slice_tuple, Person
def test_is_tuple():
assert is_tuple((1, 2, 3)) == True
assert is_tuple([1, 2, 3]) == False
def test_is_exact_tuple():
class MyTuple(tuple):
pass
assert is_exact_tuple((1, 2, 3)) == True
assert i... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_tuple(obj):\n \"\"\"\n Check if the object is a tuple.\n \"\"\"\n return isinstance(obj, tuple)\n\ndef is_exact_tuple(obj):\n \"\"\"\n Check if... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012559",
"row_id": 12559,
"seed_ids": "[56]"
} | 0.49165 | Docs: Python310_12559 | I | [
"is_tuple",
"is_exact_tuple",
"create_and_populate_tuple",
"slice_tuple",
"demonstrate"
] | 5 | [
[
"demonstrate",
"create_and_populate_tuple"
],
[
"demonstrate",
"is_exact_tuple"
],
[
"demonstrate",
"is_tuple"
],
[
"demonstrate",
"slice_tuple"
]
] | 4 | [] | false | [
"Person"
] | true | pytest | true | [] | true | b285d4a05041e1efcf3d6a62d89eff8a38fdd303 | 93e4de48c534e015ec11036eaf597a3dc108d7e1 | |||
v1.0 | instruct | Docs | Docs: Python310_12624_I | ### Asynchronous File Processing with asyncio
In this challenge, you are required to use the asyncio library to implement an asynchronous function for processing log files.
#### Objective:
Write an asynchronous function `process_logs(log_filenames: List[str]) -> Dict[str, int]` that:
1. Takes a list of log file nam... | import asyncio
import re
from typing import List, Dict
def normalize_text(text: str) -> List[str]:
# Remove punctuation and convert to lower case
text = re.sub(r'[^\w\s]', '', text).lower()
return text.split()
async def count_words_in_file(filename: str) -> Dict[str, int]:
word_count = {}
async wi... | import pytest
import asyncio
from solution import process_logs
@pytest.mark.asyncio
async def test_process_logs_single_file():
result = await process_logs(['log1.txt'])
expected = {
"error": 1,
"occurred": 1,
"in": 1,
"the": 1,
"system": 1
}
assert result == expe... | [
{
"docstring": null,
"function_declaration": "def normalize_text(text):",
"function_name": "normalize_text",
"parameter_list": "(text)"
}
] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Dict\nimport re\nimport aiofiles\n\ndef normalize_text(text: str) -> List[str]:\n # Remove punctuation and convert to lower ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012624",
"row_id": 12624,
"seed_ids": "[270]"
} | 0.606658 | Docs: Python310_12624 | I | [
"normalize_text",
"count_words_in_file",
"process_logs"
] | 3 | [
[
"count_words_in_file",
"normalize_text"
],
[
"process_logs",
"count_words_in_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0e5ef97c920b4295b4c0477e0e531c933b79ac90 | 329dc1038d10ef273aec0a1d3afab4c6b796f01d | |||
v1.0 | instruct | Docs | Docs: Pytorch_12633_I | **Optimizing PyTorch Computation Using SIMD Instructions**
### Objective:
The objective of this question is to assess your understanding of PyTorch and how to leverage SIMD instructions to optimize a computation task on x86 CPUs.
### Problem Statement:
You are given a task to optimize matrix multiplication operations... | import subprocess
import torch
def check_simd_support():
def has_instruction(output, instruction):
return instruction in output
avx512_support = amx_support = False
try:
result = subprocess.check_output(['lscpu']).decode('utf-8')
avx512_support = has_instruction(result, 'avx512')... | import torch
from solution import check_simd_support, optimized_matrix_multiplication
def test_check_simd_support_keys():
simd_support = check_simd_support()
assert 'avx512' in simd_support
assert 'amx' in simd_support
assert isinstance(simd_support['avx512'], bool)
assert isinstance(simd_support['... | [
{
"docstring": null,
"function_declaration": "def check_simd_support():",
"function_name": "check_simd_support",
"parameter_list": "()"
},
{
"docstring": "Perform matrix multiplication of two PyTorch tensors A and B.\nLeveraging any available SIMD instructions.",
"function_declaration": ... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport subprocess\n\ndef check_simd_support():\n \"\"\"\n Check if the machine supports AVX-512 or AMX instructions.\n Returns:\n A dictio... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012633",
"row_id": 12633,
"seed_ids": "[99]"
} | 0.491939 | Docs: Pytorch_12633 | I | [
"check_simd_support",
"optimized_matrix_multiplication"
] | 2 | [
[
"optimized_matrix_multiplication",
"check_simd_support"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 975d6463fe9308a130348639dbae6e5daddf6b9f | f49e7042f439f9cef512ea92112f08a51caff300 | |||
v1.0 | instruct | Docs | Docs: Python310_12640_I | #### Objective
Write a function that extends the functionality of the `imghdr` module by adding a custom test to detect a specific image format that is not natively supported by `imghdr`.
#### Problem Statement
Create a Python function that detects whether a file is of a custom image type called "xyz". The "xyz" forma... | import imghdr
def xyz_test(h, f):
"""
Test function for "xyz" format.
"""
if h[:3] == b'XYZ':
return 'xyz'
def add_xyz_test():
"""
Adds the custom 'xyz' test to imghdr.
"""
imghdr.tests.append(xyz_test)
def detect_image_type(file_path: str) -> str:
"""
Detects the type... | import os
import pytest
from solution import add_xyz_test, detect_image_type
# Create test files for testing
def setup_module(module):
with open('test1.xyz', 'wb') as f:
f.write(b'XYZcontent')
with open('test2.png', 'wb') as f:
f.write(b'\x89PNG\r\n\x1a\n')
def teardown_module(module):
os.... | [
{
"docstring": "Test function for \"xyz\" format.",
"function_declaration": "def xyz_test(h, f):",
"function_name": "xyz_test",
"parameter_list": "(h, f)"
},
{
"docstring": "Adds the custom 'xyz' test to imghdr.",
"function_declaration": "def add_xyz_test():",
"function_name": "add_x... | [
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 imghdr\n\ndef add_xyz_test():\n \"\"\"\n Adds a custom test to detect 'xyz' image format.\n \"\"\"\n def test_xyz(header, file):\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012640",
"row_id": 12640,
"seed_ids": "[410]"
} | 0.532307 | Docs: Python310_12640 | I | [
"xyz_test",
"add_xyz_test",
"detect_image_type"
] | 3 | [
[
"add_xyz_test",
"xyz_test"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a99a473fd5b53e8fc17579455dd48578af3ed0dc | bf842d10e4e48f8e65afbc05bee5d4982198a129 | |||
v1.0 | instruct | Docs | Docs: Python310_12649_I | ### XML Document Navigation and Modification using `xml.dom`
**Objective:**
Demonstrate your understanding of the `xml.dom` module by writing Python functions to navigate and modify an XML document.
**Problem Statement:**
You are provided with an XML document represented as a string, and you need to perform severa... | from xml.dom.minidom import parseString, Document
def parse_xml(xml_string):
"""
Parse the given XML string into a Document object.
"""
return parseString(xml_string)
def find_element_by_tag_name(document, tag_name):
"""
Find the first element in the document with the specified tag name.
"... | import pytest
from xml.dom.minidom import Document
from solution import parse_xml, find_element_by_tag_name, add_element, remove_element_by_tag_name, serialize_document
def test_parse_xml():
xml_string = "<root><child>data</child></root>"
document = parse_xml(xml_string)
assert isinstance(document, Documen... | [
{
"docstring": "Parse the given XML string into a Document object.",
"function_declaration": "def parse_xml(xml_string):",
"function_name": "parse_xml",
"parameter_list": "(xml_string)"
},
{
"docstring": "Find the first element in the document with the specified tag name.",
"function_dec... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from xml.dom.minidom import parseString, Document\n\ndef parse_xml(xml_string):\n \"\"\"\n Parse the given XML string into a Document object.\n \"\"\"\n ret... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012649",
"row_id": 12649,
"seed_ids": "[244]"
} | 0.632333 | Docs: Python310_12649 | I | [
"parse_xml",
"find_element_by_tag_name",
"add_element",
"remove_element_by_tag_name",
"serialize_document"
] | 5 | [
[
"add_element",
"find_element_by_tag_name"
],
[
"remove_element_by_tag_name",
"find_element_by_tag_name"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 36719f0b9d7f7826b08c44495f21dded927d9309 | cc9228164ffbc936d7dbc60826e17f6c0379ea42 | |||
v1.0 | instruct | Docs | Docs: Python310_12689_I | ### Asyncio Task Management and Synchronization
#### Background
The asyncio library in Python allows for writing concurrent code using the async/await syntax. It provides high-level APIs to run coroutines concurrently, manage network IO, and synchronize concurrent code. This assessment focuses on creating, running, an... | import asyncio
async def network_operation(task_id, delay):
"""
Simulates a network operation that takes `delay` seconds to complete.
Args:
- task_id (int): The ID of the task.
- delay (int): The time in seconds that the task will take to complete.
Returns:
- str: A string message indicat... | import pytest
import asyncio
from solution import network_operation, manage_tasks
def test_network_operation():
result = asyncio.run(network_operation(1, 1))
assert result == "Task 1 completed."
@pytest.mark.asyncio
async def test_manage_tasks_order():
task_details = [(1, 5), (2, 1), (3, 3)]
result = ... | [] | [
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\n\nasync def network_operation(task_id, delay):\n \"\"\"\n Simulates a network operation that takes `delay` seconds to complete.\n\n Args:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012689",
"row_id": 12689,
"seed_ids": "[270]"
} | 0.661163 | Docs: Python310_12689 | I | [
"network_operation",
"manage_tasks"
] | 2 | [
[
"manage_tasks",
"network_operation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8eca7d7ba497b83bb25bb5da3960ec3fd9b84af2 | 173062ed49eab96a2a4e3c8cca0aef9bed531560 | |||
v1.0 | instruct | Docs | Docs: Python310_12750_I | You are tasked with writing a function `process_integer_objects()` that performs various operations using `PyLongObject` handling functions provided in the `python310` package. The function should take a list of integers and perform the following tasks:
1. Check if each integer qualifies as a `PyLongObject`.
2. Conver... | import sys
# Define the PyLongObject handling functions using the built-in Python functions
def PyLong_Check(val):
"""
Mimic Python's PyLong_Check
"""
return isinstance(val, int)
def PyLong_FromLong(val):
"""
Convert from C long (int) type to PyLongObject (int in Python)
"""
return int... | def test_process_integer_objects():
int_list = [10, 20, 30]
result = process_integer_objects(int_list)
assert result == [10, 20, 30], "Test failed for normal integers"
def test_process_large_integers():
int_list = [10**20, -10**20]
result = process_integer_objects(int_list)
assert result == [],... | [
{
"docstring": "Mimic Python's PyLong_Check",
"function_declaration": "def PyLong_Check(val):",
"function_name": "PyLong_Check",
"parameter_list": "(val)"
},
{
"docstring": "Convert from C long (int) type to PyLongObject (int in Python)",
"function_declaration": "def PyLong_FromLong(val)... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\n\n# Define the PyLongObject handling functions using the built-in Python functions\ndef PyLong_Check(val):\n \"\"\"\n Mimic Python's PyLong_Check\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012750",
"row_id": 12750,
"seed_ids": "[52]"
} | 0.532948 | Docs: Python310_12750 | I | [
"PyLong_Check",
"PyLong_FromLong",
"PyLong_AsLong",
"process_integer_objects"
] | 4 | [
[
"process_integer_objects",
"PyLong_AsLong"
],
[
"process_integer_objects",
"PyLong_Check"
],
[
"process_integer_objects",
"PyLong_FromLong"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 6a23b311d109fb68603a1a262b8d4be296c0592d | 89a77938ef52947875c9e59fa4ad65be3ca75086 | |||
v1.0 | instruct | Docs | Docs: Python310_12791_I | ## Coding Assessment Question
### Context
The "concurrent.futures" module in Python allows for the execution of code in parallel using threads or processes. As a developer, you might need to perform multiple IO-bound or CPU-bound operations simultaneously to improve the performance of your application.
### Task
You a... | from concurrent.futures import ThreadPoolExecutor
from typing import List
def square(n: int) -> int:
return n * n
def parallel_square(numbers: List[int]) -> List[int]:
with ThreadPoolExecutor() as executor:
results = list(executor.map(square, numbers))
return results | from solution import parallel_square
def test_parallel_square_basic():
assert parallel_square([1, 2, 3, 4, 5]) == [1, 4, 9, 16, 25]
def test_parallel_square_negative_numbers():
assert parallel_square([-1, -2, -3, -4, -5]) == [1, 4, 9, 16, 25]
def test_parallel_square_mixed_numbers():
assert parallel_squa... | [
{
"docstring": null,
"function_declaration": "def square(n):",
"function_name": "square",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def parallel_square(numbers):",
"function_name": "parallel_square",
"parameter_list": "(numbers)"
}
] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from concurrent.futures import ThreadPoolExecutor\nfrom typing import List\n\ndef parallel_square(numbers: List[int]) -> List[int]:\n def square(n: int) -> int:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012791",
"row_id": 12791,
"seed_ids": "[224]"
} | 0.60147 | Docs: Python310_12791 | I | [
"square",
"parallel_square"
] | 2 | [
[
"parallel_square",
"square"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bfb14e6a82dd68886508fa98c95e2662d71df86e | cc4aac5b13e1beb91aebe072071f058acce6f0b7 | |||
v1.0 | instruct | Docs | Docs: Scikit_12822_I | **Title: Multivariate Linear Regression and Regularization Techniques in scikit-learn**
**Objective:**
Demonstrate your understanding of linear regression models and regularization techniques in scikit-learn by analyzing a given dataset, addressing multicollinearity, and comparing the performance of different models.
... | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.py... | # Import the functions for testing
from solution import load_and_preprocess_data, calculate_correlation_matrix, train_linear_models, plot_results
# Add pytest framework
import pytest
@pytest.fixture
def example_dataset():
# Example dataframe for testing purposes
data = {
'feature1': np.random.rand(100... | [
{
"docstring": "Load and preprocess the data.\n\nArgs:\nfilepath (str): Path to the CSV file.\n\nReturns:\npd.DataFrame: Preprocessed DataFrame.",
"function_declaration": "def load_and_preprocess_data(filepath):",
"function_name": "load_and_preprocess_data",
"parameter_list": "(filepath)"
},
{
... | [
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 pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso\nfrom skl... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012822",
"row_id": 12822,
"seed_ids": "[53]"
} | 0.528038 | Docs: Scikit_12822 | I | [
"load_and_preprocess_data",
"calculate_correlation_matrix",
"apply_pca",
"train_linear_models",
"plot_results"
] | 5 | [
[
"train_linear_models",
"apply_pca"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"pandas",
"sklearn"
] | false | ee87e4a8509194f7a925aa205a62763ba1a38238 | 1bafd45b24687795c41811d2da73c94c191ce687 | |||
v1.0 | instruct | Docs | Docs: Python310_12828_I | **Networking and Interprocess Communication — Asynchronous Web Server**
**Question:**
You are to implement a simple asynchronous web server using the `asyncio` and `socket` modules in Python. This server will accept incoming HTTP GET requests and respond with a simple HTML message. Ensure that the server can handle m... | import asyncio
import socket
async def handle_client(client_socket):
request = await asyncio.get_event_loop().sock_recv(client_socket, 1024)
request_line = request.decode().splitlines()[0]
method, path, _ = request_line.split()
if method != 'GET':
response = 'HTTP/1.1 405 Method Not Allowed\r\... | import asyncio
import socket
import pytest
from solution import run_server
@pytest.mark.asyncio
async def test_server_responds_with_hello_world():
port = 9000
server_task = asyncio.create_task(run_server('127.0.0.1', port))
await asyncio.sleep(1) # Allow server some time to start
reader, writer = aw... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport socket\n\nasync def handle_client(client_socket):\n request = await asyncio.to_thread(client_socket.recv, 1024)\n request_line = request.de... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012828",
"row_id": 12828,
"seed_ids": "[151]"
} | 0.655405 | Docs: Python310_12828 | I | [
"handle_client",
"run_server"
] | 2 | [
[
"run_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a302b8f67b02e81904f78c30b8a2f82c4491fbf4 | c0d402724137016fe900f5f58e814991c7722c7d | |||
v1.0 | instruct | Docs | Docs: Python310_12857_I | **Problem Statement:**
Write a Python program that sets up custom signal handlers for different types of signals. Your program should demonstrate the ability to:
1. Set and handle the `SIGINT` signal (typically sent using Ctrl+C).
2. Set and handle the `SIGALRM` signal using a timer.
3. Set and handle the `SIGUSR1` sig... | import signal
import sys
def handle_sigint(signum, frame):
print("SIGINT received, exiting.")
sys.exit(0)
def handle_sigalrm(signum, frame):
print("SIGALRM received, alarm triggered.")
def handle_sigusr1(signum, frame):
print("SIGUSR1 received.")
def setup_signal_handlers():
signal.signal(si... | import signal
import os
import subprocess
import time
def test_handle_sigint():
process = subprocess.Popen(['python', 'solution.py'], stdout=subprocess.PIPE, text=True)
# Give the process some time to start and pause waiting for signals
time.sleep(2)
process.send_signal(signal.SIGINT)
stdout, _ = p... | [
{
"docstring": null,
"function_declaration": "def handle_sigint(signum, frame):",
"function_name": "handle_sigint",
"parameter_list": "(signum, frame)"
},
{
"docstring": null,
"function_declaration": "def handle_sigalrm(signum, frame):",
"function_name": "handle_sigalrm",
"parame... | [
0,
1,
0,
1,
1,
0,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\nimport sys\n\ndef handle_sigint(signum, frame):\n print(\"SIGINT received, exiting.\")\n sys.exit(0)\n\ndef handle_sigalrm(signum, frame):\n pri... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00012857",
"row_id": 12857,
"seed_ids": "[253]"
} | 0.46153 | Docs: Python310_12857 | I | [
"handle_sigint",
"handle_sigalrm",
"handle_sigusr1",
"setup_signal_handlers",
"main"
] | 5 | [
[
"setup_signal_handlers",
"handle_sigalrm"
],
[
"setup_signal_handlers",
"handle_sigint"
],
[
"setup_signal_handlers",
"handle_sigusr1"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 58138a2cebddd5528f57f977d8e084b281b62795 | 49e2165e321dec29a46255c164a7907ca128a701 | |||
v1.0 | instruct | Docs | Docs: Python310_12882_I | ### Asynchronous Iterator Challenge
#### Objective
Implement a function `async_even_generator()` that provides an asynchronous iterator. The iterator should generate even numbers up to a given limit asynchronously. Additionally, implement a synchronous function `collect_even_numbers(n)` that utilizes this asynchronous... | import asyncio
async def async_even_generator(limit):
"""
Asynchronous generator function that yields even numbers up to the specified limit.
"""
for number in range(0, limit + 1, 2):
await asyncio.sleep(0) # Simulate asynchronous behavior
yield number
def collect_even_numbers(n):
... | from solution import collect_even_numbers
def test_collect_even_numbers():
# Test with a small limit
assert collect_even_numbers(10) == [0, 2, 4, 6, 8, 10]
# Test with a limit that is not an even number
assert collect_even_numbers(15) == [0, 2, 4, 6, 8, 10, 12, 14]
# Test with zero as lim... | [
{
"docstring": "Synchronous function that collects all even numbers up to n using the async_even_generator.",
"function_declaration": "def collect_even_numbers(n):",
"function_name": "collect_even_numbers",
"parameter_list": "(n)"
}
] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def async_even_generator(limit):\n for num in range(0, limit + 1, 2):\n yield num\n await asyncio.sleep(0) # Simulates an asyn... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012882",
"row_id": 12882,
"seed_ids": "[105]"
} | 0.648646 | Docs: Python310_12882 | I | [
"async_even_generator",
"collect_even_numbers"
] | 2 | [
[
"collect_even_numbers",
"async_even_generator"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 90250029962feb3590c089fbda3c1f44df587b5f | 9a535bbb57402371f4597d41e30d6df82646c46e | |||
v1.0 | instruct | Docs | Docs: Python310_12927_I | ### **Asyncio Futures Simulation with Task Management**
In this assessment, you are tasked with demonstrating your understanding of `asyncio` futures by implementing a simple asynchronous task management system using `asyncio.Future`.
**Instructions**:
1. **Create a Function `delayed_result(delay, value)`**:
- Th... | import asyncio
async def delayed_result(delay: int, value: any) -> any:
"""
Returns the value after a specified delay.
Args:
delay: The wait time in seconds.
value: The value to be returned after the delay.
"""
await asyncio.sleep(delay)
return value
async def run_tasks(tasks:... | import pytest
import asyncio
from solution import delayed_result, run_tasks
@pytest.mark.asyncio
async def test_delayed_result():
result = await delayed_result(1, 42)
assert result == 42
@pytest.mark.asyncio
async def test_run_tasks():
tasks = [(1, 'task1'), (2, 'task2'), (3, 'task3')]
results = await... | [
{
"docstring": "Main function to create and run tasks.",
"function_declaration": "def main():",
"function_name": "main",
"parameter_list": "()"
}
] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def delayed_result(delay, value):\n \"\"\"\n Returns the value after a specified delay.\n \"\"\"\n await asyncio.sleep(delay)\n r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012927",
"row_id": 12927,
"seed_ids": "[113]"
} | 0.613163 | Docs: Python310_12927 | I | [
"delayed_result",
"run_tasks",
"main"
] | 3 | [
[
"run_tasks",
"delayed_result"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 58f9451c05af1e0dd92d99e285cbe1b44f5e2c02 | 12978364a937612b3338e9250709adf77c81e534 | |||
v1.0 | instruct | Docs | Docs: Python310_12933_I | ### Question: Parallel Data Processing with `concurrent.futures`
You are given a list of URLs pointing to various JSON data files on the web. Your task is to write a Python function that downloads and processes these JSON files concurrently to extract specific information. The information you're interested in is the v... | import concurrent.futures
import requests
def fetch_json(url):
try:
response = requests.get(url)
response.raise_for_status()
return response.json()
except (requests.RequestException, ValueError):
return None
def process_json_urls(urls, key):
result = {}
def process_url... | from solution import process_json_urls
import requests
from unittest.mock import patch
def mock_requests_get(url):
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
def json(self):
return se... | [
{
"docstring": null,
"function_declaration": "def fetch_json(url):",
"function_name": "fetch_json",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def process_json_urls(urls, key):",
"function_name": "process_json_urls",
"parameter_list": "(urls, key)"... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\nimport requests\nimport json\n\ndef fetch_json_data(url, key):\n \"\"\"\n Fetch JSON data from the given URL and extract the value asso... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012933",
"row_id": 12933,
"seed_ids": "[224]"
} | 0.599814 | Docs: Python310_12933 | I | [
"fetch_json",
"process_json_urls"
] | 2 | [
[
"process_json_urls",
"fetch_json"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | b332503b865ef0391fc7ed61fc054c6858200a76 | b65b79c3b1e5efbdb399f5df4177d2f5ae64d42f | |||
v1.0 | instruct | Docs | Docs: Python310_12942_I | ### Objective:
To evaluate the understanding and application of Python’s profiling tools (`cProfile`, `profile`, and `pstats`) for analyzing program performance.
### Problem Statement:
Write a Python script to profile the performance of different sorting algorithms. You need to implement the following sorting algorith... | import random
import cProfile
import pstats
from pstats import SortKey
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) ... | import random
from solution import bubble_sort, merge_sort, profile_sorting_algorithms, analyze_profile_data
def test_bubble_sort():
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
assert arr == [11, 12, 22, 25, 34, 64, 90]
def test_merge_sort():
arr = [64, 34, 25, 12, 22, 11, 90]
merge_sort(a... | [
{
"docstring": null,
"function_declaration": "def bubble_sort(arr):",
"function_name": "bubble_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport cProfile\nimport pstats\nfrom pstats import SortKey\n\ndef bubble_sort(arr):\n n = len(arr)\n for i in range(n):\n for j in range(0, ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012942",
"row_id": 12942,
"seed_ids": "[142]"
} | 0.464634 | Docs: Python310_12942 | I | [
"bubble_sort",
"merge_sort",
"profile_sorting_algorithms",
"analyze_profile_data"
] | 4 | [
[
"profile_sorting_algorithms",
"bubble_sort"
],
[
"profile_sorting_algorithms",
"merge_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 15663c816c49f3f15658369b41ab6ccbed12ddf3 | d6282023dc888aef8d0d74160daa9072a45d195f | |||
v1.0 | instruct | Docs | Docs: Python310_12992_I | ### Question: Custom Data Processing with Iterators, Generators, and Functional Programming
#### Objective
Implement a sequence data processing pipeline utilizing custom iterators, generators, and functional programming constructs using `itertools` and `functools` modules to process and analyze a stream of numerical d... | class SensorDataIterator:
def __init__(self, data):
self.data = data
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index < len(self.data):
result = self.data[self.index]
self.index += 1
return result
e... | from solution import SensorDataIterator, filter_above_threshold, process_sensor_data
def test_SensorDataIterator():
data = [1, 2, 3]
sensor_data_iter = SensorDataIterator(data)
result = list(sensor_data_iter)
assert result == [1, 2, 3]
def test_filter_above_threshold():
data = [10, 5, 3, 7, 9]
... | [] | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class SensorDataIterator:\n def __init__(self, data):\n self.data = data\n self.index = 0\n\n def __iter__(self):\n return self\n\n def __... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00012992",
"row_id": 12992,
"seed_ids": "[78]"
} | 0.543125 | Docs: Python310_12992 | I | [
"filter_above_threshold",
"process_sensor_data"
] | 2 | [
[
"process_sensor_data",
"filter_above_threshold"
]
] | 1 | [] | false | [
"SensorDataIterator"
] | true | pytest | true | [] | true | 2979596dd4e974da69e06c289dea359579ac3594 | 243c19f70091a4f4a24c4d07a6903d9c9a8bb235 | |||
v1.0 | instruct | Docs | Docs: Python310_13125_I | ### Advanced Asynchronous Programming with asyncio
**Objective:** Implement an asynchronous function using Python's `asyncio` library that demonstrates the ability to manage multiple asynchronous tasks, handle potential pitfalls, and effectively use debugging and logging.
#### Problem Statement:
Write an asynchronou... | import asyncio
import aiohttp
import logging
# Configure logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
async def fetch_content(url: str) -> str:
"""
Fetch content from the given URL asynchronously.
"""
try:
async with aiohttp.ClientSession() as session:
... | import asyncio
from solution import process_urls
def test_process_urls_success(monkeypatch):
urls = ["http://example.com", "http://example.org"]
async def mock_fetch_content(url):
return "content"
async def mock_process_content(content):
return len(content)
monkeypatch.setatt... | [] | [
1,
0,
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 aiohttp\nimport logging\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\nasync def fetch... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013125",
"row_id": 13125,
"seed_ids": "[200]"
} | 0.563189 | Docs: Python310_13125 | I | [
"fetch_content",
"process_content",
"process_single_url",
"process_urls"
] | 4 | [
[
"process_single_url",
"fetch_content"
],
[
"process_single_url",
"process_content"
],
[
"process_urls",
"process_single_url"
]
] | 3 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 311f46eb6451f28eb2aff4cfc69d1e1f9f20eb71 | 6c5817cc9f7c35736e504ba58c65e6b0050bf3e6 | |||
v1.0 | instruct | Docs | Docs: Python310_13143_I | Python's `pydoc` module is a comprehensive tool for generating documentation from Python modules. For this assessment, you will implement a simplified version of some functionalities described in the `pydoc` documentation.
#### Objectives
1. **Generate Documentation**: Create a function that generates documentation fo... | import importlib
import inspect
def generate_doc(target: str) -> str:
"""
Generates the documentation for a specified module, class, or function.
Args:
target (str): The name of the module, class, or function as a string.
Returns:
str: The documentation string if available, otherwise ... | import pytest
from io import StringIO
import sys
from solution import generate_doc, print_doc
def test_generate_doc_module():
assert generate_doc('os') == inspect.getdoc(importlib.import_module('os'))
def test_generate_doc_class():
assert generate_doc('os.path') == inspect.getdoc(importlib.import_module('os')... | [
{
"docstring": "Generates the documentation for a specified module, class, or function.\n\nArgs:\ntarget (str): The name of the module, class, or function as a string.\n\nReturns:\nstr: The documentation string if available, otherwise \"No documentation available.\"",
"function_declaration": "def generate_d... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import importlib\nimport inspect\n\ndef generate_doc(target: str) -> str:\n \"\"\"\n Generates documentation for the given module, class, or function.\n \n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00013143",
"row_id": 13143,
"seed_ids": "[240]"
} | 0.551459 | Docs: Python310_13143 | I | [
"generate_doc",
"print_doc"
] | 2 | [
[
"print_doc",
"generate_doc"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5650c13645b3587bb2f16db41a162af85e7e342e | d60acd903c4308989675f8a261fed0d7a8b792cb | |||
v1.0 | instruct | Docs | Docs: Python310_13182_I | ### Question: Advanced Iterator and Generator Usage in Python
Implement a custom iterator and a generator function, and then use them in combination with functions from the `itertools` and `functools` modules to solve the following problem:
**Problem Statement:**
You are given a stream of numbers representing tempera... | import itertools
import functools
class TemperatureStream:
def __init__(self, temperatures):
self.temperatures = temperatures
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.temperatures):
raise StopIteration
... | from solution import TemperatureStream, temperature_variation, max_24_hour_variation, average_temperature, analyze_temperature_readings
def test_temperature_stream():
temps = [1, 2, 3, 4, 5]
temp_stream = TemperatureStream(temps)
assert list(temp_stream) == temps
def test_temperature_variation():
temp... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\nimport functools\n\nclass TemperatureStream:\n def __init__(self, temperatures):\n self.temperatures = temperatures\n self.index = 0\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013182",
"row_id": 13182,
"seed_ids": "[78]"
} | 0.500069 | Docs: Python310_13182 | I | [
"temperature_variation",
"max_24_hour_variation",
"average_temperature",
"analyze_temperature_readings"
] | 4 | [
[
"analyze_temperature_readings",
"average_temperature"
],
[
"analyze_temperature_readings",
"max_24_hour_variation"
],
[
"max_24_hour_variation",
"temperature_variation"
]
] | 3 | [] | false | [
"TemperatureStream"
] | true | pytest | true | [] | true | 84f80c43dca04f897898af2e1d07e05626fa5906 | 0438e81e0ef3c5bf2cdd742f4d230d1d5b4e32a4 | |||
v1.0 | instruct | Docs | Docs: Python310_13193_I | ## Task
Implement an asyncio-based task manager that handles tasks with different priorities using an `asyncio.PriorityQueue`. Your task manager should be capable of adding tasks with specified priorities, processing these tasks concurrently, and providing status updates.
## Requirements
1. **Function Signature:**
... | import asyncio
from typing import List, Tuple
async def worker(name: str, queue: asyncio.PriorityQueue):
while True:
priority, task = await queue.get()
print(f"Worker {name} is processing task: {task} with priority: {priority}")
queue.task_done()
await asyncio.sleep(0) # Simulating... | import asyncio
import pytest
from solution import manage_tasks
@pytest.mark.asyncio
async def test_manage_tasks_order():
tasks = [(3, "Low priority task"), (1, "High priority task"), (2, "Medium priority task")]
async def run_and_capture_output():
output = []
def mock_print(*args):
... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def worker(worker_id: int, queue: asyncio.PriorityQueue):\n while True:\n priority, task = await queue... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00013193",
"row_id": 13193,
"seed_ids": "[111]"
} | 0.635808 | Docs: Python310_13193 | I | [
"worker",
"manage_tasks"
] | 2 | [
[
"manage_tasks",
"worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 15507d658be9fb79bb808b0626eabc4420526656 | 79562b02afd9240556f7ab9e9edabf3a8b94933e | |||
v1.0 | instruct | Docs | Docs: Python310_13206_I | ### CSV File Manipulation and Analysis
#### Problem Statement:
You have been provided a CSV file containing information about employees in a company. Each row in the CSV file includes the following fields:
- `id`: Employee ID
- `name`: Employee name
- `department`: Department of the employee
- `salary`: Salary of the... | import csv
def read_employee_data(filename: str) -> list:
"""
Reads employee data from a CSV file and returns a list of dictionaries.
Parameters:
- filename: str: The name of the CSV file to read from.
Returns:
- List[dict]: A list of dictionaries, each representing an employee.
"""
w... | import os
import csv
import pytest
from solution import read_employee_data, increment_salary, average_salary_by_department
def create_csv(filename, content):
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(content)
def test_read_employee_data():
create_... | [
{
"docstring": "Reads employee data from a CSV file and returns a list of dictionaries.\n\nParameters:\n- filename: str: The name of the CSV file to read from.\n\nReturns:\n- List[dict]: A list of dictionaries, each representing an employee.",
"function_declaration": "def read_employee_data(filename):",
... | [
0,
0,
0,
1,
0,
1,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\n\ndef read_employee_data(filename):\n \"\"\"\n Reads employee data from a CSV file and returns a list of dictionaries.\n \n Parameters:\n - f... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00013206",
"row_id": 13206,
"seed_ids": "[272]"
} | 0.663413 | Docs: Python310_13206 | I | [
"read_employee_data",
"increment_salary",
"average_salary_by_department"
] | 3 | [
[
"average_salary_by_department",
"read_employee_data"
],
[
"increment_salary",
"read_employee_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 072a45cfd8894e99ea09beebff1b9d4f788c3a65 | c4a2129d48abafd034e224604cccf4c39648d730 | |||
v1.0 | instruct | Docs | Docs: Python310_13291_I | #### **Title:** Implementing a Custom Iterable Data Structure with Functional Utilities
#### **Objective:**
Design and implement a custom iterable data structure in Python using generators. Extend the functionality of this data structure with utility functions using features from the `itertools` and `functools` module... | import itertools
import functools
class FibonacciSequence:
def __init__(self):
self.a, self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
a = self.a
self.a, self.b = self.b, self.a + self.b
return a
def take(n, iterable):
return list(itertools.i... | from solution import FibonacciSequence, take, sum_of_squares
def test_fibonacci_sequence():
fib_seq = FibonacciSequence()
first_10_fibs = take(10, fib_seq)
assert first_10_fibs == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
def test_take():
fib_seq = FibonacciSequence()
first_5_fibs = take(5, fib_seq)
a... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\nfrom functools import reduce\n\nclass FibonacciSequence:\n def __init__(self):\n self.a, self.b = 0, 1\n\n def __iter__(self):\n r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013291",
"row_id": 13291,
"seed_ids": "[78]"
} | 0.708137 | Docs: Python310_13291 | I | [
"take",
"sum_of_squares"
] | 2 | [
[
"sum_of_squares",
"take"
]
] | 1 | [] | false | [
"FibonacciSequence"
] | true | pytest | true | [] | true | c2f8e8401d1b35de4e3d6801c71db3b74d8ee487 | 455be1c952d36f15bbffa622df207ccc7b29d47d | |||
v1.0 | instruct | Docs | Docs: Python310_13298_I | ### Asynchronous Task Management with asyncio
**Objective:**
Your task is to implement a Python function using the `asyncio` package, which demonstrates handling multiple asynchronous tasks concurrently.
**Question:**
Write a function `manage_tasks` using asyncio that:
1. Creates three asynchronous tasks:
- Ta... | import asyncio
from typing import List
async def task1():
await asyncio.sleep(2)
return "Task 1 Completed"
async def task2():
await asyncio.sleep(3)
return "Task 2 Completed"
async def task3():
await asyncio.sleep(1)
return "Task 3 Completed"
async def manage_tasks() -> List[str]:
tasks ... | import pytest
import asyncio
from solution import manage_tasks
@pytest.mark.asyncio
async def test_manage_tasks():
results = await manage_tasks()
assert results == ["Task 1 Completed", "Task 2 Completed", "Task 3 Completed"]
def test_manage_tasks_event_loop():
loop = asyncio.get_event_loop()
results =... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"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 task1():\n await asyncio.sleep(2)\n return \"Task 1 Completed\"\n\nasync def task2():\n await asyncio.slee... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013298",
"row_id": 13298,
"seed_ids": "[270]"
} | 0.634438 | Docs: Python310_13298 | I | [
"task1",
"task2",
"task3",
"manage_tasks"
] | 4 | [
[
"manage_tasks",
"task1"
],
[
"manage_tasks",
"task2"
],
[
"manage_tasks",
"task3"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | d3334522921d22b891530aa9539751d4f16c9a72 | 8bdb9bfea4b7e4a0c9f62b81689b54e52d633ef8 | |||
v1.0 | instruct | Docs | Docs: Pandas_13417_I | ## Question: Optimizing DataFrame Computations with Cython and Numba
You are provided with a pandas DataFrame containing data about various mathematical functions and their parameters. Your task is to implement a function that performs numerical integration based on the DataFrame's contents. Your solution should then ... | import pandas as pd
import numpy as np
def linear(x):
return x
def quadratic(x):
return x**2
def integrate_function(df):
def integrate(a, b, N, func):
dx = (b - a) / N
total_sum = 0.0
for i in range(N):
x = a + i*dx
if func == "linear":
tota... | import pandas as pd
from solution import integrate_function
def test_integrate_function():
df = pd.DataFrame({
"a": [0, 0],
"b": [1, 2],
"N": [1000, 2000],
"func": ["linear", "quadratic"]
})
result_df = integrate_function(df)
# Expected values derived by analyt... | [
{
"docstring": null,
"function_declaration": "def linear(x):",
"function_name": "linear",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def quadratic(x):",
"function_name": "quadratic",
"parameter_list": "(x)"
},
{
"docstring": null,
"functi... | [
0,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport numpy as np\nfrom numba import jit\n\n# Define mathematical functions\ndef linear(x):\n return x\n\ndef quadratic(x):\n return x**2\n\... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00013417",
"row_id": 13417,
"seed_ids": "[10]"
} | 0.527004 | Docs: Pandas_13417 | I | [
"linear",
"quadratic",
"integrate_function"
] | 3 | [
[
"integrate_function",
"linear"
],
[
"integrate_function",
"quadratic"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas"
] | false | b7f963e6dc7ea3ecbe5809d6735c6540f37250f9 | 64db73fefd0ec4dbcccfb980d13b0330a3531428 | |||
v1.0 | instruct | Docs | Docs: Python310_13422_I | ### Asynchronous Task Management with asyncio
**Objective:**
Implement an asynchronous Python program that utilizes different features of the asyncio package to manage and coordinate multiple tasks.
**Problem Statement:**
You are required to create an asynchronous program that executes a series of tasks in parallel, ... | import asyncio
import random
from typing import List
async def task_coro(task_id: int) -> str:
"""
Simulates a task that takes between 1 to 5 seconds to complete.
Once done, it returns a string `Task {task_id} completed`.
"""
await asyncio.sleep(random.uniform(1, 5))
return f'Task {task_id} com... | import pytest
import asyncio
from solution import task_coro, gather_tasks, main
@pytest.mark.asyncio
async def test_task_coro():
result = await task_coro(1)
assert result == 'Task 1 completed'
@pytest.mark.asyncio
async def test_gather_tasks():
results = await gather_tasks(5)
assert len(results) == 5
... | [] | [
1,
0,
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 random\nfrom typing import List\n\nasync def task_coro(task_id: int) -> str:\n \"\"\"\n Simulates a task that takes between 1 to 5 seconds ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013422",
"row_id": 13422,
"seed_ids": "[360]"
} | 0.64715 | Docs: Python310_13422 | I | [
"task_coro",
"gather_tasks",
"main"
] | 3 | [
[
"gather_tasks",
"task_coro"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aacdca9168113c811cfbe977e65e42fcdb1859ba | 065d842f7f0ea172a559ef2d44bd6e469eaccd32 | |||
v1.0 | instruct | Docs | Docs: Pytorch_13431_I | #### Objective
Implement a fault-tolerant distributed training script using the `torch.distributed.elastic` module. Your task is to create a script that performs distributed training on a simple neural network while being able to gracefully handle node failures and automatically rescale the training processes.
#### Ba... | import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
class SimpleNet(nn.Module):
def __init__(self):
super(SimpleNet, self).__init__()
self.fc1 = nn.Linear(10, 50)... | from solution import SimpleNet, generate_fake_data
def test_simple_net():
model = SimpleNet()
sample_input = torch.randn(1, 10)
output = model(sample_input)
assert output.shape == (1, 2)
def test_generate_fake_data():
dataset = generate_fake_data(100)
assert len(dataset) == 100
sample_inpu... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data as data\nfrom torch.distributed.elastic.multiprocessing import run\nfrom torch... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013431",
"row_id": 13431,
"seed_ids": "[21]"
} | 0.410907 | Docs: Pytorch_13431 | I | [
"generate_fake_data",
"train_fn"
] | 2 | [
[
"train_fn",
"generate_fake_data"
]
] | 1 | [] | false | [
"SimpleNet"
] | true | pytest | true | [
"torch"
] | false | 4e8e03c10637b6276401acd2dcb5ec797b04a664 | b9b13e1eef3263734ceec7e9cb58269dc6856b21 | |||
v1.0 | instruct | Docs | Docs: Pytorch_13439_I | PyTorch func Transformations and Gradient Calculation
In this assessment, you are required to demonstrate your understanding of the `torch.func` transformations and how to compute model gradients using these transformations.
#### Problem Statement
You are provided with a simple model and a dataset consisting of inpu... | import torch
from torch.func import functional_call, grad
from typing import Dict
def compute_loss(params: Dict[str, torch.Tensor], inputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
"""
Computes the Mean Squared Error (MSE) loss between the model predictions and the targets.
:param params:... | import torch
from solution import compute_loss, compute_gradients
def test_compute_loss():
inputs = torch.randn(64, 3)
targets = torch.randn(64, 3)
model = torch.nn.Linear(3, 3)
params = {name: param.detach().requires_grad_() for name, param in model.named_parameters()}
loss = compute_loss(par... | [
{
"docstring": "Computes the Mean Squared Error (MSE) loss between the model predictions and the targets.\n\n:param params: Dictionary of model parameters.\n:param inputs: Input tensor.\n:param targets: Target tensor.\n:return: Computed loss.",
"function_declaration": "def compute_loss(params, inputs, targe... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.func import functional_call, grad\n\ndef compute_loss(params, inputs, targets):\n \"\"\"\n Compute the Mean Squared Error (MSE) loss betw... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00013439",
"row_id": 13439,
"seed_ids": "[23]"
} | 0.567766 | Docs: Pytorch_13439 | I | [
"compute_loss",
"compute_gradients"
] | 2 | [
[
"compute_gradients",
"compute_loss"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | a794fa10606b174ac81e5bb085c04431f1fa275d | 283e7f97cb5d95cfe470f8241e7a3ffa8f146bce | |||
v1.0 | instruct | Docs | Docs: Python310_13460_I | ## Coding Assessment Question:
### Objective:
Implement an incremental encoder and decoder for a simple custom text codec that reverses the input text during encoding and restores it during decoding.
### Problem Statement:
Your task is to create a custom codec named `reverse_codec` that reverses the input string when... | import codecs
class ReverseIncrementalEncoder(codecs.IncrementalEncoder):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.buffer = ""
def encode(self, input, final=False):
self.buffer += input
if final:
result = self.buffer[::-1]
... | import codecs
from solution import register_reverse_codec, ReverseIncrementalEncoder, ReverseIncrementalDecoder
def test_reverse_codec():
# Register the custom codec
register_reverse_codec()
# Fetch the incremental encoder and decoder
encoder = codecs.getincrementalencoder('reverse_codec')()
d... | [] | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import codecs\n\nclass ReverseIncrementalEncoder(codecs.IncrementalEncoder):\n def encode(self, input, final=False):\n return input[::-1]\n\n def reset(sel... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00013460",
"row_id": 13460,
"seed_ids": "[211]"
} | 0.515657 | Docs: Python310_13460 | I | [
"reverse_codec_search",
"register_reverse_codec"
] | 2 | [
[
"register_reverse_codec",
"reverse_codec_search"
]
] | 1 | [] | false | [
"ReverseIncrementalEncoder",
"ReverseIncrementalDecoder"
] | true | pytest | true | [] | true | 6a8dfd1864c01b8f4a66c2537da9d8f98b552466 | 1a9215601faf22fcfb9ad921ec09fc799e3bb71c | |||
v1.0 | instruct | Docs | Docs: Pytorch_13475_I | ### Description
You are tasked with implementing a custom CUDA tensor operation pipeline using PyTorch, incorporating various CUDA features, such as device management, memory management, and CUDA streams. The pipeline will process data stored on multiple CUDA devices, perform operations asynchronously, and utilize CUD... | import torch
import time
def select_cuda_device(device_index):
"""
Sets the selected CUDA device and prints the device name.
Raises an error if the device is not available.
"""
if not torch.cuda.is_available():
raise RuntimeError("CUDA is not available.")
if device_index < 0 or device_i... | import pytest
import torch
from solution import select_cuda_device, perform_tensor_operations, async_tensor_operations, cuda_graph_operations
def test_select_cuda_device():
if torch.cuda.is_available():
select_cuda_device(0) # Assuming at least one CUDA device is available
assert True
else:
... | [
{
"docstring": "Sets the selected CUDA device and prints the device name.\nRaises an error if the device is not available.",
"function_declaration": "def select_cuda_device(device_index):",
"function_name": "select_cuda_device",
"parameter_list": "(device_index)"
},
{
"docstring": "Creates t... | [
0,
0,
0,
0,
0,
1,
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": "import torch\nimport time\n\ndef select_cuda_device(device_index):\n \"\"\"\n Selects a CUDA device based on the given index and verifies its availability.\n \... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00013475",
"row_id": 13475,
"seed_ids": "[178]"
} | 0.495903 | Docs: Pytorch_13475 | I | [
"select_cuda_device",
"perform_tensor_operations",
"async_tensor_operations",
"cuda_graph_operations"
] | 4 | [
[
"async_tensor_operations",
"select_cuda_device"
],
[
"cuda_graph_operations",
"select_cuda_device"
],
[
"perform_tensor_operations",
"select_cuda_device"
]
] | 3 | [] | false | [] | false | pytest | true | [
"torch"
] | false | fabfd5da7483c06553a8d0ac951e2889a9a2234e | c219e3aad16abb354c0174172f7f5bc0aa286191 | |||
v1.0 | instruct | Docs | Docs: Python310_13503_I | **Custom Codec Implementation and Usage**
You are required to implement a custom codec to encode and decode a specific format. This format includes a prefix and suffix around the original message.
### Specifications
1. **Prefix**: `"[ENC]"`.
2. **Suffix**: `"[END]"`.
Example:
- Original Message: `"Hello, World!"`
... | import codecs
class CustomCodecInfo:
prefix = "[ENC]"
suffix = "[END]"
@staticmethod
def encode(input: str, errors: str = 'strict') -> tuple:
encoded = CustomCodecInfo.prefix + input + CustomCodecInfo.suffix
return encoded, len(encoded)
@staticmethod
def decode(input: ... | import codecs
import pytest
from solution import register_custom_codec, unregister_custom_codec, CustomCodecInfo
def test_encode():
register_custom_codec()
message = "Hello, World!"
encoded = codecs.encode(message, "custom_enc")
assert encoded == "[ENC]Hello, World![END]"
unregister_custom_codec()
... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import codecs\n\nclass CustomCodecInfo:\n prefix = \"[ENC]\"\n suffix = \"[END]\"\n \n @staticmethod\n def encode(input: str, errors: str = 'strict') -> ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013503",
"row_id": 13503,
"seed_ids": "[211]"
} | 0.594535 | Docs: Python310_13503 | I | [
"search_function",
"register_custom_codec",
"unregister_custom_codec"
] | 3 | [
[
"register_custom_codec",
"search_function"
],
[
"unregister_custom_codec",
"search_function"
]
] | 2 | [] | false | [
"CustomCodecInfo"
] | true | pytest | true | [] | true | 5d40efb9466bade6c1410175403c8c486b21decb | 8185dbbac4f25e1a12f382226f0af0bb1b8f2093 | |||
v1.0 | instruct | Docs | Docs: Python310_13547_I | ### Assessment Question: Concurrent Subprocess Monitoring
In this task, you will implement a Python function that concurrently runs multiple shell commands using `asyncio`'s subprocess APIs. Your function will execute each command, capture its output, print the output, and handle any errors.
#### Function Signature
`... | import asyncio
async def execute_command(command):
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
return stdout.decode(), stderr.decode()
async def execute_c... | from solution import execute_commands
import asyncio
def test_execute_commands():
commands = ['echo Hello', 'ls nonexistent_directory', 'sleep 1; echo Done']
results = asyncio.run(execute_commands(commands))
assert 'echo Hello' in results
assert results['echo Hello'] == ('Hello\n', '')
assert 'ls n... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def execute_commands(commands: list) -> dict:\n async def run_command(command):\n proc = await asyncio.create_subprocess_shell(\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013547",
"row_id": 13547,
"seed_ids": "[264]"
} | 0.725762 | Docs: Python310_13547 | I | [
"execute_command",
"execute_commands"
] | 2 | [
[
"execute_commands",
"execute_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 068502cfa3883d662ca46454af57308546f72c33 | 5c03bca10eee569e1c5dbdff1c8fe258a916eb8a | |||
v1.0 | instruct | Docs | Docs: Python310_13555_I | **Question**: Implement a Python program that uses the `ensurepip` module to achieve the following tasks. Your implementation should consist of two parts: using the CLI and the Module API of `ensurepip`.
### Part 1: Command Line Interface:
Write a Python script to be executed using the command:
```bash
python your_sc... | import subprocess
import ensurepip
import sys
def check_pip_installed():
try:
result = subprocess.run([sys.executable, '-m', 'pip', '--version'], capture_output=True, text=True)
if result.returncode == 0:
print(f"pip is already installed. Version: {result.stdout}")
return Tr... | from solution import check_pip_installed, get_ensurepip_version, setup_pip
def test_check_pip_installed(monkeypatch):
import subprocess
def mock_run(*args, **kwargs):
if args[0] == [sys.executable, '-m', 'pip', '--version']:
mock_resp = subprocess.CompletedProcess(args, 0, stdout="pip ... | [
{
"docstring": null,
"function_declaration": "def check_pip_installed():",
"function_name": "check_pip_installed",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def install_pip_cli():",
"function_name": "install_pip_cli",
"parameter_list": "()"
},
{
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import subprocess\nimport sys\nimport ensurepip\nimport os\n\n\ndef check_pip_installed():\n try:\n subprocess.run(['pip', '--version'], check=True, stdout=su... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013555",
"row_id": 13555,
"seed_ids": "[194]"
} | 0.587218 | Docs: Python310_13555 | I | [
"check_pip_installed",
"install_pip_cli",
"get_ensurepip_version",
"setup_pip"
] | 4 | [
[
"setup_pip",
"check_pip_installed"
],
[
"setup_pip",
"get_ensurepip_version"
],
[
"setup_pip",
"install_pip_cli"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 8f16a3054ef2b79e865a596c7d6d597a668af8fa | 45b73ac5ff8e47b5db069e5887512c6a5e43713b | |||
v1.0 | instruct | Docs | Docs: Python310_13670_I | You are provided with two matrix multiplication algorithms: a naive implementation and an optimized implementation using NumPy. You need to use the `timeit` module to compare the performance of these two matrix multiplication methods.
**Objective**: Write a Python function `compare_matrix_multiplication_times()` that ... | import numpy as np
import timeit
def naive_multiply(A, B):
n = len(A)
result = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += A[i][k] * B[k][j]
return result
def numpy_multiply(A, B):
return np.dot(A, B)
def... | def test_compare_matrix_multiplication_times():
import timeit
result = compare_matrix_multiplication_times(10)
assert "naive" in result, "Result dictionary should contain 'naive' key"
assert "numpy" in result, "Result dictionary should contain 'numpy' key"
assert isinstance(result["naive"... | [
{
"docstring": null,
"function_declaration": "def naive_multiply(A, B):",
"function_name": "naive_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def numpy_multiply(A, B):",
"function_name": "numpy_multiply",
"parameter_list": "(A, B)"
},
... | [
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 numpy as np\nimport timeit\n\ndef naive_multiply(A, B):\n n = len(A)\n result = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013670",
"row_id": 13670,
"seed_ids": "[328]"
} | 0.488227 | Docs: Python310_13670 | I | [
"naive_multiply",
"numpy_multiply",
"generate_random_matrix",
"compare_matrix_multiplication_times"
] | 4 | [
[
"compare_matrix_multiplication_times",
"generate_random_matrix"
],
[
"compare_matrix_multiplication_times",
"naive_multiply"
],
[
"compare_matrix_multiplication_times",
"numpy_multiply"
]
] | 3 | [] | false | [] | false | pytest | false | [
"numpy"
] | false | 7d8ce482f7f7864ba81ed83076766608b6a007ad | 192d7805486f4b2949328b0a025f305b91743d81 | |||
v1.0 | instruct | Docs | Docs: Python310_13700_I | **Concurrency in Asyncio**
You are required to manage a set of tasks that need to be executed concurrently using Python's asyncio library. The challenge is to ensure these tasks are managed properly, and their results are collected efficiently.
### Task Details
You need to implement a function `asyncio_manage_tasks... | import asyncio
from typing import List, Tuple
async def async_task(delay: int, message: str) -> str:
await asyncio.sleep(delay)
return message
async def asyncio_manage_tasks(task_list: List[Tuple[int, str]]) -> List[str]:
tasks = [asyncio.create_task(async_task(delay, message)) for delay, message in task_... | import asyncio
import pytest
from solution import asyncio_manage_tasks
@pytest.mark.asyncio
async def test_single_task():
task_list = [(2, "task1 completed")]
result = await asyncio_manage_tasks(task_list)
assert result == ["task1 completed"]
@pytest.mark.asyncio
async def test_multiple_tasks():
task_... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def async_task(delay: int, message: str) -> str:\n await asyncio.sleep(delay)\n return message\n\nasync de... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013700",
"row_id": 13700,
"seed_ids": "[317]"
} | 0.717561 | Docs: Python310_13700 | I | [
"async_task",
"asyncio_manage_tasks"
] | 2 | [
[
"asyncio_manage_tasks",
"async_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b1893fa6fab50ff78a0a150f1b249a2de5aaad41 | 4f6703a8ee0a557f6edd1511221bbc1c56b52dbe | |||
v1.0 | instruct | Docs | Docs: Python310_13708_I | **Task: Implement `asyncio` Function with Platform-specific Conditions**
You are tasked with writing a Python function using the `asyncio` module that handles platform-specific conditions effectively. The function should create a TCP echo server and client, keeping in mind the given platform restrictions.
### Functio... | import asyncio
import platform
import sys
async def tcp_echo_server(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
"""
Implements a simple TCP echo server.
"""
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {mes... | import pytest
import asyncio
import platform
from solution import start_server, start_client
@pytest.mark.asyncio
async def test_server_and_client_communication():
server_task = asyncio.create_task(start_server())
await asyncio.sleep(0.1) # Give the server time to start
client_task = asyncio.create_task(... | [
{
"docstring": null,
"function_declaration": "def main():",
"function_name": "main",
"parameter_list": "()"
}
] | [
1,
0,
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 sys\n\nasync def tcp_echo_server(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):\n \"\"\"\n Implements a simp... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013708",
"row_id": 13708,
"seed_ids": "[370]"
} | 0.653285 | Docs: Python310_13708 | I | [
"tcp_echo_server",
"start_server",
"start_client",
"main_server",
"main_client",
"main"
] | 6 | [
[
"main_client",
"start_client"
],
[
"main_server",
"start_server"
],
[
"start_server",
"tcp_echo_server"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | b415f318f941131ce0a88717ac74b1ea83636df0 | 0e1d6f6b0479fbb6d661193f86780b49d0a7cd9b | |||
v1.0 | instruct | Docs | Docs: Python310_13740_I | ### Secure Login System Implementation
**Objective:**
Implement a secure login system using the `getpass` module. The system should prompt the user for their username and password securely, verifying the credentials against a predefined set of users.
**Task:**
1. Implement a function `get_credentials()` that:
- P... | import getpass
def get_credentials():
"""
Prompts the user for their username and password securely,
then returns a tuple containing the entered username and password.
"""
username = input("Enter your username: ")
password = getpass.getpass("Password: ")
return (username, password)
def lo... | from solution import login_system
def test_login_system_valid_credentials(monkeypatch):
users = {
"alice": "password123",
"bob": "secure456",
"charlie": "passwd789"
}
inputs = iter(["alice", "password123"])
monkeypatch.setattr('builtins.input', lambda x: next(inputs))
m... | [
{
"docstring": "Prompts the user for their username and password securely, \nthen returns a tuple containing the entered username and password.",
"function_declaration": "def get_credentials():",
"function_name": "get_credentials",
"parameter_list": "()"
},
{
"docstring": "Accepts a dictiona... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import getpass\n\ndef get_credentials():\n \"\"\"\n Prompts the user for their username and password securely.\n Returns a tuple containing the entered usernam... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00013740",
"row_id": 13740,
"seed_ids": "[164]"
} | 0.637056 | Docs: Python310_13740 | I | [
"get_credentials",
"login_system"
] | 2 | [
[
"login_system",
"get_credentials"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 630eebe7531d4df0edba596edd47c85960b53247 | d60ce6f10f2319e09a73e140dcf4e889229ae8a8 | |||
v1.0 | instruct | Docs | Docs: Python310_13755_I | **Problem: Asynchronous Task Manager**
You are required to implement a simplified asynchronous task manager that executes multiple asynchronous tasks concurrently. You must use the asyncio library and handle specific exceptions defined in the asyncio documentation accordingly.
### Requirements:
1. Implement an async... | import asyncio
import random
async def perform_task(task_id):
"""
Simulates performing a task. Randomly raises an exception or completes successfully.
"""
exceptions = [
asyncio.TimeoutError,
asyncio.CancelledError,
asyncio.InvalidStateError,
asyncio.IncompleteReadError,... | import asyncio
import pytest
from solution import perform_task, run_tasks
@pytest.mark.asyncio
async def test_perform_task_success():
random.seed(0) # Control randomness for test predictability
result = await perform_task(1)
assert result == "Task 1 completed successfully"
@pytest.mark.asyncio
async def ... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\n\nasync def perform_task(task_id):\n \"\"\"\n Simulates performing a task. Randomly raises specific asyncio exceptions or completes... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00013755",
"row_id": 13755,
"seed_ids": "[396]"
} | 0.479107 | Docs: Python310_13755 | I | [
"perform_task",
"run_tasks"
] | 2 | [
[
"run_tasks",
"perform_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1dd22325c1f2d5f0bbde9bbf416088df04e58db3 | 93463171bf00b6decff00eef1464c7da24312d07 | |||
v1.0 | instruct | Docs | Docs: Scikit_13760_I | **Objective**: Demonstrate your understanding of out-of-core learning and incremental model training using scikit-learn.
### Problem Statement:
You are given a stream of text data for spam email classification. Due to the large volume of emails, it is not feasible to load all data into memory. Your task is to build a... | import numpy as np
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
def stream_emails(file_path):
"""
Generator function to stream emails from a file.
Args:
file_path (str): Path to the file cont... | from solution import stream_emails, train_spam_classifier
import pytest
import os
# Create a sample emails.txt file for testing
@pytest.fixture(scope='module')
def create_test_file():
test_data = [
"1\tThis is a spam email",
"0\tThis is a regular email",
"1\tBuy cheap products now",
... | [
{
"docstring": "Generator function to stream emails from a file.\n\nArgs:\nfile_path (str): Path to the file containing email data.\n\nYields:\ntuple: Label and email text.",
"function_declaration": "def stream_emails(file_path):",
"function_name": "stream_emails",
"parameter_list": "(file_path)"
... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00013760",
"row_id": 13760,
"seed_ids": "[63]"
} | 0.48637 | Docs: Scikit_13760 | I | [
"stream_emails",
"train_spam_classifier"
] | 2 | [
[
"train_spam_classifier",
"stream_emails"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | c0405095c39d5e1d67c25f4c24d65c5c8a167527 | 31b8c55bace2ea743afddcf1d858479ad574d56f | |||
v1.0 | instruct | Docs | Docs: Python310_13788_I | ### WAV File Processing and Modification
In this assessment, you will demonstrate your understanding of the "wave" module by writing functions that read a WAV file, process its audio data, and create a new modified WAV file.
#### Requirements
1. Implement a function `read_wav_file(file_path)` that:
- Takes a stri... | import wave
import struct
def read_wav_file(file_path):
with wave.open(file_path, 'rb') as wav:
wav_data = {
"nchannels": wav.getnchannels(),
"sampwidth": wav.getsampwidth(),
"framerate": wav.getframerate(),
"nframes": wav.getnframes(),
"comptype"... | import pytest
import tempfile
import struct
from solution import read_wav_file, write_wav_file, modify_wav_file
def create_test_wav_file(file_path):
with wave.open(file_path, 'wb') as wav:
wav.setnchannels(1)
wav.setsampwidth(2)
wav.setframerate(44100)
wav.setnframes(4)
wav.... | [
{
"docstring": null,
"function_declaration": "def read_wav_file(file_path):",
"function_name": "read_wav_file",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def write_wav_file(file_path, wav_data):",
"function_name": "write_wav_file",
"paramete... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import wave\nimport struct\n\ndef read_wav_file(file_path):\n with wave.open(file_path, 'rb') as wav:\n wav_data = {\n \"nchannels\": wav.getnchann... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013788",
"row_id": 13788,
"seed_ids": "[150]"
} | 0.573764 | Docs: Python310_13788 | I | [
"read_wav_file",
"write_wav_file",
"modify_wav_file"
] | 3 | [
[
"modify_wav_file",
"read_wav_file"
],
[
"modify_wav_file",
"write_wav_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1c4c818c9071351b1e8d0b8fe96792b6d507e7ec | 7b9f77ab1d5fb105769c611ee856889d6d8ffd2f | |||
v1.0 | instruct | Docs | Docs: Python310_13790_I | ### Asynchronous Programming Assessment
**Objective**: Demonstrate your understanding of Python's asynchronous programming by implementing a coroutine-based solution for a real-world problem.
#### Problem Statement:
You are tasked with creating an asynchronous file download manager using Python's `asyncio` library. ... | import asyncio
import aiohttp
import os
from typing import List
async def download_file(url: str, destination: str) -> None:
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response.raise_for_status()
filename = os.pat... | import os
import aiohttp
import shutil
import pytest
from unittest.mock import patch
from solution import download_file, download_files, main
BASE_URL = "http://example.com/"
DEST_DIR = "./test_downloads/"
@pytest.fixture
def setup_and_teardown():
os.makedirs(DEST_DIR, exist_ok=True)
yield
if os.path.exis... | [
{
"docstring": null,
"function_declaration": "def main(urls, destination_dir):",
"function_name": "main",
"parameter_list": "(urls, destination_dir)"
}
] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport aiohttp\nimport aiofiles\nimport os\nfrom typing import List\nimport logging\n\n# Setting up basic logging\nlogging.basicConfig(level=logging.INF... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013790",
"row_id": 13790,
"seed_ids": "[8]"
} | 0.579577 | Docs: Python310_13790 | I | [
"download_file",
"download_files",
"main"
] | 3 | [
[
"download_files",
"download_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | a4907d9c1905737bb791a276e87cb825e5e891d1 | 2f5fb050ca3b7b923827cd02d140f5d1b1164807 | |||
v1.0 | instruct | Docs | Docs: Python310_13886_I | You are working on a shared resource management system using the `asyncio` module's synchronization primitives. Your task is to implement an asynchronous function `coordinate_tasks` that manages access to a shared resource among multiple tasks.
**Function Signature:**
```python
async def coordinate_tasks(num_workers: ... | import asyncio
async def worker(worker_id, task_duration, semaphore):
async with semaphore:
print(f"Worker {worker_id} started working...")
await asyncio.sleep(task_duration)
print(f"Worker {worker_id} finished working.")
async def coordinate_tasks(num_workers: int, task_duration: float):
... | import asyncio
from solution import coordinate_tasks
from io import StringIO
import sys
def test_coordinate_tasks():
# Capture the output
captured_output = StringIO()
sys.stdout = captured_output
async def run_test():
await coordinate_tasks(5, 1)
# Run the asyncio task
asyncio.run... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def worker(worker_id, task_duration, semaphore):\n async with semaphore:\n print(f\"Worker {worker_id} started working...\")\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00013886",
"row_id": 13886,
"seed_ids": "[247]"
} | 0.569702 | Docs: Python310_13886 | I | [
"worker",
"coordinate_tasks"
] | 2 | [
[
"coordinate_tasks",
"worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 50dd3626d85f1c4d470d15bf7ecc1d5fc9aee1d3 | 4375a2a6edc70f1d2ab88c0791bdc099a3092b6b | |||
v1.0 | instruct | Docs | Docs: Python310_13900_I | **Objective:**
Implement a function similar to `tabnanny.check()` that not only detects ambiguous indentations but also counts the total number of whitespace issues in a directory or a file. Your implementation should demonstrate a clear understanding of directory traversal, token processing, and exception handling in... | import os
import tokenize
def count_whitespace_issues(file_path):
issues = 0
with open(file_path, 'r') as f:
tokens = tokenize.generate_tokens(f.readline)
indents = []
for toknum, tokval, _, _, _ in tokens:
if toknum == tokenize.INDENT:
indents.append(tokval)... | import os
import pytest
from solution import custom_check
def test_single_file_with_issues(tmp_path):
content = "def example():\n x = 1\n y = 2\n"
test_file = tmp_path / "example.py"
test_file.write_text(content)
assert custom_check(test_file) == 1
def test_single_file_without_issues(tmp_path... | [
{
"docstring": null,
"function_declaration": "def count_whitespace_issues(file_path):",
"function_name": "count_whitespace_issues",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def custom_check(file_or_dir):",
"function_name": "custom_check",
"... | [
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 os\nimport tokenize\n\ndef count_whitespace_issues(file_path):\n issues = 0\n with open(file_path, 'r') as f:\n tokens = tokenize.generate_tokens(f.... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013900",
"row_id": 13900,
"seed_ids": "[293]"
} | 0.54655 | Docs: Python310_13900 | I | [
"count_whitespace_issues",
"custom_check"
] | 2 | [
[
"custom_check",
"count_whitespace_issues"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b6a343d4e075e3b34cc9898760722af04174ddeb | df0b6faae45807f46a40d8e8812f868dd352825d | |||
v1.0 | instruct | Docs | Docs: Python310_13953_I | #### Objective:
You are required to implement a Python function utilizing the `mailcap` module to find applicable commands for given MIME types from Mailcap files, and enhance the command by generating a secure filename.
#### Problem Statement:
Implement a function `generate_mailcap_command(mime_type: str, key: str, p... | import string
import random
import mailcap
def generate_secure_filename() -> str:
"""Generate a secure temporary filename."""
return ''.join(random.choices(string.ascii_letters + string.digits, k=12))
def generate_mailcap_command(mime_type: str, key: str, params: dict = None) -> tuple:
caps = mailcap.getc... | from solution import generate_mailcap_command
def test_generate_mailcap_command_view():
result = generate_mailcap_command('text/plain', 'view')
assert result is not None
assert isinstance(result, tuple)
assert len(result) == 2
assert isinstance(result[0], str) or result[0] is None
assert isinst... | [
{
"docstring": "Generate a secure temporary filename.",
"function_declaration": "def generate_secure_filename():",
"function_name": "generate_secure_filename",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def generate_mailcap_command(mime_type, key, params=None... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import mailcap\nimport random\nimport string\nimport shlex\n\ndef generate_secure_filename() -> str:\n \"\"\"Generate a secure temporary filename using alphanumeric ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013953",
"row_id": 13953,
"seed_ids": "[399]"
} | 0.482391 | Docs: Python310_13953 | I | [
"generate_secure_filename",
"generate_mailcap_command"
] | 2 | [
[
"generate_mailcap_command",
"generate_secure_filename"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 47a8c04c42dc0404c239fa041c63f61c1dad8e82 | 4690728497cc15f2803e41640daef3ddd3cd0e0d | |||
v1.0 | instruct | Docs | Docs: Python310_13959_I | <|Analysis Begin|>
The given documentation briefly introduces the `asyncio` module, which is a library used for writing concurrent code with the `async/await` syntax. It covers the following points:
- Basic example of creating and running an asynchronous function.
- Purpose and usage of `asyncio` in high-performance a... | import asyncio
import aiohttp
async def fetch_data(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def fetch_data_concurrently(urls: list[str]) -> dict[str, str]:
async def fetch(url):
try:
... | import asyncio
from solution import fetch_data_concurrently
async def test_fetch_data_concurrently():
urls = [
'http://httpbin.org/get',
'http://invalid.url', # This should fail and return None
'http://example.com'
]
expected_results = [
'http://httpbin.org/get', 'http... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"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(url):\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as response:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013959",
"row_id": 13959,
"seed_ids": "[270]"
} | 0.530671 | Docs: Python310_13959 | I | [
"fetch_data",
"fetch_data_concurrently"
] | 2 | [
[
"fetch_data_concurrently",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 1477d9fc866f2344a6403562c0b0a29f7592568d | 8a1e24a4ee579838b569f541d4feb88b239252f7 | |||
v1.0 | instruct | Docs | Docs: Scikit_14035_I | #### Objective
Demonstrate your ability to use scikit-learn's evaluation metrics by implementing a custom scoring function for a regression task. Then, use this custom scorer to evaluate and compare models using cross-validation.
#### Problem Statement
You are given a dataset of house prices with the following feature... | import numpy as np
from sklearn.metrics import mean_absolute_error, r2_score
def custom_scorer(y_true, y_pred):
"""
Custom scoring function that combines the Mean Absolute Error (MAE) and R² score.
Parameters:
y_true (array-like): True target values
y_pred (array-like): Predicted target values... | from solution import custom_scorer, evaluate_models
import numpy as np
import pandas as pd
def test_custom_scorer():
# Test with simple data
y_true = np.array([100, 200, 300])
y_pred = np.array([110, 190, 290])
score = custom_scorer(y_true, y_pred)
# Calculate manually
mae = np.mean(np.abs... | [
{
"docstring": "Custom scoring function that combines the Mean Absolute Error (MAE) and R² score.\n\nParameters:\ny_true (array-like): True target values\ny_pred (array-like): Predicted target values\n\nReturns:\nfloat: Custom score calculated as (1 - MAE/mean(y_true)) * (R² + 1)",
"function_declaration": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.metrics import mean_absolute_error, r2_score\n\ndef custom_scorer(y_true, y_pred):\n \"\"\"\n Custom scoring function that combin... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00014035",
"row_id": 14035,
"seed_ids": "[25]"
} | 0.682877 | Docs: Scikit_14035 | I | [
"custom_scorer",
"evaluate_models"
] | 2 | [
[
"evaluate_models",
"custom_scorer"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 92b337042cf600a779ab8d576945ae2cbd9d7412 | 905a1adb655a0027c436b7c0805b3896ec7b728e | |||
v1.0 | instruct | Docs | Docs: Python310_14116_I | **Question: Asynchronous File Download Manager**
**Background:**
You are tasked with creating an asynchronous file download manager. Using the asyncio library, the manager should be able to:
1. Establish an event loop.
2. Schedule multiple file download tasks concurrently.
3. Provide a status update on the progress of... | import asyncio
import aiohttp
import os
async def download_file(url: str, dest: str) -> None:
"""
Downloads a file from the given URL to the destination dest asynchronously.
"""
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.statu... | import asyncio
import aiohttp
import os
import pytest
from unittest.mock import patch, mock_open
from solution import download_file, download_manager
@pytest.mark.asyncio
async def test_download_file():
url = "http://example.com/file1"
dest = "test_downloads/file1"
with patch("aiohttp.ClientSession.... | [] | [
1,
0,
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 aiohttp\nimport os\n\nasync def download_file(url: str, dest: str) -> None:\n \"\"\"\n Downloads a file from a given URL to a specified des... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00014116",
"row_id": 14116,
"seed_ids": "[101]"
} | 0.568505 | Docs: Python310_14116 | I | [
"download_file",
"download_manager"
] | 2 | [
[
"download_manager",
"download_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 6c338d3a334ce68ae61cf44140a146f8c460973d | 314bd7efed49e326b1d2f31d1d83308b67e6a992 | |||
v1.0 | instruct | Docs | Docs: Python310_14135_I | Title: Task Execution and Aggregation with concurrent.futures
**Problem Statement:**
You are given a list of integers and your goal is to calculate the factorial of each integer using multiple parallel workers such that the computation time is minimized. To achieve this, you will use the `concurrent.futures` module.
... | from typing import List, Optional
from concurrent.futures import ThreadPoolExecutor, as_completed
def factorial(n: int) -> int:
"""
Return the factorial of a given non-negative integer.
"""
if n < 0:
return None
result = 1
for i in range(2, n+1):
result *= i
return result
d... | from solution import compute_factorials
def test_factorials_with_small_numbers():
numbers = [0, 1, 2, 3, 4, 5]
expected = [1, 1, 2, 6, 24, 120]
assert compute_factorials(numbers, max_workers=3) == expected
def test_factorials_with_large_numbers():
numbers = [6, 7, 8, 9, 10]
expected = [720, 5040, ... | [
{
"docstring": "Return the factorial of a given non-negative integer.",
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
},
{
"docstring": "Compute factorials of given non-negative integers using parallel workers.\n\nParameters:\n- numbers: L... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Optional\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef factorial(n: int) -> int:\n \"\"\"\n Return the factoria... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00014135",
"row_id": 14135,
"seed_ids": "[224]"
} | 0.727746 | Docs: Python310_14135 | I | [
"factorial",
"compute_factorials"
] | 2 | [
[
"compute_factorials",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 04c87eac4cf2908852fd9dabd41867c26bcf495e | 19575350aeb59718aa2bd6d89705c7cdb2f638c2 | |||
v1.0 | instruct | Docs | Docs: Python310_14184_I | **Networking and Asynchronous I/O Coding Challenge**
**Objective:**
Implement a simple asynchronous TCP server and client using Python's `asyncio` and `socket` modules.
**Problem Statement:**
1. **Async TCP Server:**
- Create an asynchronous TCP server that listens on a specified port.
- The server should be a... | import asyncio
import socket
async def handle_client(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message} from {addr}")
echo_message = f"Echo: {message}"
writer.write(echo_message.encode())
await writer.... | import asyncio
import pytest
from asyncio import StreamReader, StreamWriter
# Import the solution code
from solution import handle_client, run_server, run_client
@pytest.mark.asyncio
async def test_handle_client():
async def mock_client(reader: StreamReader, writer: StreamWriter):
writer.write(b"Hello, Se... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\n# Asynchronous TCP Server\nasync def handle_client(reader, writer):\n while True:\n data = await reader.read(100)\n if not data:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00014184",
"row_id": 14184,
"seed_ids": "[151]"
} | 0.673274 | Docs: Python310_14184 | I | [
"handle_client",
"run_server",
"run_client"
] | 3 | [
[
"run_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bb6bf782553c87f21f1a996abbf205294f0d4c67 | ca19e4803aec3994db19360b83d758372c64aeac | |||
v1.0 | instruct | Docs | Docs: Python310_14203_I | ## Python Grammar-Based Parsing Task
### Objective:
Your task is to implement a Python function to parse a subset of Python expressions and statements using the provided grammar rules. Specifically, you will be implementing a function that evaluates Python assignment statements and function definitions.
### Task:
You... | import ast
def parse_python_code(code: str) -> dict:
"""
Parses a string representing a Python assignment or function definition
and returns a structured representation of the components.
"""
# Parse the code into an AST
tree = ast.parse(code)
# Handling assignment
if isinstance(tr... | import pytest
from solution import parse_python_code
def test_parse_assignment():
code = "x = 5 + 3"
expected_output = {
"type": "assignment",
"target": "x",
"value": {
"type": "expression",
"elements": ["5", "Add", "3"]
}
}
assert parse_python_co... | [
{
"docstring": "Parses a string representing a Python assignment or function definition\nand returns a structured representation of the components.",
"function_declaration": "def parse_python_code(code):",
"function_name": "parse_python_code",
"parameter_list": "(code)"
},
{
"docstring": nul... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef parse_python_code(code: str) -> dict:\n # Check if the code is an assignment statement\n assignment_pattern = r'^(\\w+)\\s*=\\s*(.+)$'\n match... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00014203",
"row_id": 14203,
"seed_ids": "[89]"
} | 0.587894 | Docs: Python310_14203 | I | [
"parse_python_code",
"parse_expression",
"parse_statement"
] | 3 | [
[
"parse_python_code",
"parse_expression"
],
[
"parse_python_code",
"parse_statement"
],
[
"parse_statement",
"parse_expression"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | b405a1219731a3e597bd3b8aeae37cfa3f0793cd | fe2271062709cbde89bbdfc8fd1e4fef99bd8b77 | |||
v1.0 | instruct | Docs | Docs: Python310_14211_I | ### **Advanced Signal Handling in Python**
### Objective
Write a Python program demonstrating advanced usage of the `signal` module. Your task is to implement a robust signal handling mechanism that can handle multiple specific signals, perform a timed operation, and ensure proper cleanup before the program exits.
#... | import signal
import time
import sys
def cleanup():
print("Performing cleanup operations...")
def sigint_handler(signum, frame):
print("SIGINT received. Cleaning up...")
cleanup()
sys.exit(0)
def sigalrm_handler(signum, frame):
print("SIGALRM: Operation timed out.")
def sigterm_handler(signum, f... | import subprocess
import time
import os
import signal
def test_sigint_handling():
process = subprocess.Popen(["python3", "solution.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
time.sleep(2)
os.kill(process.pid, signal.SIGINT)
stdout, stderr = process.communicate()
assert b"SIGINT received.... | [
{
"docstring": null,
"function_declaration": "def cleanup():",
"function_name": "cleanup",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def sigint_handler(signum, frame):",
"function_name": "sigint_handler",
"parameter_list": "(signum, frame)"
},
{
... | [
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\nimport time\nimport sys\n\ndef cleanup():\n print(\"Performing cleanup operations...\")\n\ndef sigint_handler(signum, frame):\n print(\"SIGINT rece... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00014211",
"row_id": 14211,
"seed_ids": "[253]"
} | 0.533931 | Docs: Python310_14211 | I | [
"cleanup",
"sigint_handler",
"sigalrm_handler",
"sigterm_handler",
"long_running_operation",
"main"
] | 6 | [
[
"long_running_operation",
"cleanup"
],
[
"sigint_handler",
"cleanup"
],
[
"sigterm_handler",
"cleanup"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 5d05a22de16ca851f50b9f112666023b0410de1d | d7b409673598c98c5b9d4f24286cc7595445f80e | |||
v1.0 | instruct | Docs | Docs: Python310_14244_I | #### Objective
Demonstrate your understanding of handling different types of exceptions in asynchronous code by implementing a function that performs multiple asynchronous operations, each designed to potentially raise one of the documented `asyncio` exceptions.
#### Question
Write a function `perform_async_operations... | import asyncio
async def task1(timeout):
try:
await asyncio.wait_for(asyncio.sleep(timeout + 1), timeout)
except asyncio.TimeoutError:
raise asyncio.TimeoutError("Task1 exceeded the time limit.")
async def task2(cancel_task2):
try:
await asyncio.sleep(5)
except asyncio.Cancelle... | import asyncio
import pytest
from solution import perform_async_operations
@pytest.mark.asyncio
async def test_task1_timeout_error():
result = await perform_async_operations(0, False)
assert result['task1_result'] == "Task1 exceeded the time limit."
@pytest.mark.asyncio
async def test_task1_success():
res... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def task1(timeout):\n try:\n await asyncio.wait_for(asyncio.sleep(timeout + 1), timeout)\n except asyncio.TimeoutError:\n ra... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00014244",
"row_id": 14244,
"seed_ids": "[396]"
} | 0.514458 | Docs: Python310_14244 | I | [
"task1",
"task2",
"task3",
"perform_async_operations"
] | 4 | [
[
"perform_async_operations",
"task1"
],
[
"perform_async_operations",
"task2"
],
[
"perform_async_operations",
"task3"
]
] | 3 | [] | false | [
"FakeStream"
] | true | pytest | true | [] | true | 82784eba1e9279e950940a7b650c84de1624edd1 | 16e29fdcfd10d7d58d7a58b440d4d0f1644f0610 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.