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 | complete | Docs | Docs: Python310_617_C | def custom_doctest(module):
""" Custom doctest runner that extracts and runs examples from docstrings.
>>> custom_doctest("example") # Assuming the module example has correctly formatted docstrings
Total examples: 6
Successful examples: 5
Failed examples: 1
Details of failed examples:
... | import re
def custom_doctest(module):
"""
Custom doctest runner that extracts and runs examples from docstrings.
Parameters:
module: A Python module name as a string or a module object.
Returns:
None. Prints a summary report.
"""
if isinstance(module, str):
module = __... | from importlib import import_module
from solution import custom_doctest
def test_custom_doctest():
# Assuming the code defining functions `add` and `divide` is in a module named `solution`
custom_doctest('solution')
# Normally you would capture the output using `capsys` fixture in pytest
# and check if... | [
{
"docstring": "Custom doctest runner that extracts and runs examples from docstrings.\n\nParameters:\nmodule: A Python module name as a string or a module object.\n\nReturns:\nNone. Prints a summary report.",
"function_declaration": "def custom_doctest(module):",
"function_name": "custom_doctest",
... | [
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 re\n\ndef custom_doctest(module):\n \"\"\"\n Custom doctest runner that extracts and runs examples from docstrings.\n \n Parameters:\n module: A P... | trial_gpt4o_0 | {
"original_instruction": "- Advanced `doctest` Implementation\n\n**Objective:** Implement a custom `doctest` runner that enhances some of the capabilities found in the Python Standard Library's `doctest` module.\n\n### Task Description:\nYou are to write a Python function `custom_doctest(module)`, which takes a Pyth... | 0.478249 | Docs: Python310_617 | C | [
"custom_doctest",
"extract_examples",
"get_expected_output",
"execute_example",
"add",
"divide"
] | 6 | [
[
"custom_doctest",
"execute_example"
],
[
"custom_doctest",
"extract_examples"
],
[
"extract_examples",
"get_expected_output"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 1a31371686a2cd44396f30598b5669b8214d76b6 | d438e1fc390de0f9d708bacd8629f17a0f6e7c84 | |||
v1.0 | complete | Docs | Docs: Python310_566_C | import asyncio
async def process_tasks(tasks, max_concurrent_tasks):
"""
Process a list of tasks with a limit on maximum concurrent tasks.
Arguments:
tasks -- list of tuples, each containing (task_id, duration)
max_concurrent_tasks -- maximum number of tasks to process concurrently
For each t... | import asyncio
async def handle_task(task_id, duration):
"""
Simulate handling a single task.
Arguments:
task_id -- unique identifier for the task
duration -- time in seconds for the task to complete
Prints:
- Task started message
- Task completed message after sleeping for the du... | import asyncio
from solution import process_tasks
tasks_test = [(1, 2.0), (2, 3.0), (3, 1.0)]
max_concurrent_tasks_test = 2
def test_process_tasks(capsys):
# Define tasks and max concurrent tasks
tasks = tasks_test
max_concurrent_tasks = max_concurrent_tasks_test
# Run the asynchronous function
a... | [] | [
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 handle_task(task_id, duration):\n \"\"\"\n Simulate handling a single task.\n\n Arguments:\n task_id -- unique identifier for th... | trial_gpt4o_0 | {
"original_instruction": "### Code Assessment Question: Implementing Asynchronous Task Management\n\n#### Objective\nYou are tasked with demonstrating your understanding of the `asyncio` library by writing an asynchronous function that simulates a concurrent task processing system.\n\n#### Problem Statement\nWrite a... | 0.623248 | Docs: Python310_566 | C | [
"handle_task",
"process_tasks"
] | 2 | [
[
"process_tasks",
"handle_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c7b77fe7b9f5b24965c48d2a54465c8b9690f22e | 3e5b80699d920a27b0591da2a9a344aff67b0bbc | |||
v1.0 | complete | Docs | Docs: Python310_369_C | import cProfile
import pstats
import time
import math
def compute_factorials(n):
"""Calculate the factorials of numbers from 1 to n."""
results = []
for i in range(1, n + 1):
result = math.factorial(i)
results.append(result)
return results
def profile_code():
"""Profile the executi... | import math
import cProfile
import pstats
import time
def compute_factorials(n):
results = []
for i in range(1, n + 1):
result = math.factorial(i)
results.append(result)
return results
def profile_code():
profiler = cProfile.Profile()
profiler.enable()
compute_factorials(10000)... | import time
from solution import compute_factorials, custom_timer
def test_compute_factorials():
results = compute_factorials(5)
expected_results = [1, 2, 6, 24, 120]
assert results == expected_results, f"Expected {expected_results}, got {results}"
def test_custom_timer(monkeypatch):
def mock_perf_cou... | [
{
"docstring": null,
"function_declaration": "def compute_factorials(n):",
"function_name": "compute_factorials",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def profile_code():",
"function_name": "profile_code",
"parameter_list": "()"
},
{
"d... | [
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 cProfile\nimport pstats\nimport time\nimport math\n\ndef compute_factorials(n):\n results = []\n for i in range(1, n + 1):\n result = math.factorial... | trial_gpt4o_8 | {
"original_instruction": "**Objective:**\n\nThis coding assessment is designed to evaluate your understanding of the \"cProfile\" module in Python for deterministic profiling. You are required to write code that demonstrates your ability to profile code execution, analyze profiling results, and implement custom prof... | 0.518586 | Docs: Python310_369 | C | [
"compute_factorials",
"profile_code",
"analyze_profiling_results",
"custom_timer",
"profile_with_custom_timer"
] | 5 | [
[
"custom_timer",
"compute_factorials"
],
[
"profile_code",
"compute_factorials"
],
[
"profile_with_custom_timer",
"compute_factorials"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 5c7c6ff9d018c7e1f56a9a075add9ee0dc6fa618 | b3ccc1b12d91b84657b328fc5598c568366354d7 | |||
v1.0 | complete | Docs | Docs: Python310_287_C | import hmac
import hashlib
def sign_message(key: bytes, msg: bytes, digestmod: str) -> str:
""" Sign given message using HMAC.
Args:
key (bytes): The secret key used for the HMAC generation.
msg (bytes): The message to be signed.
digestmod (str): The name of the hash algorithm to use (e.g., 's... | import hmac
import hashlib
def sign_message(key: bytes, msg: bytes, digestmod: str) -> str:
"""
Sign given message using HMAC.
Args:
key (bytes): The secret key used for the HMAC generation.
msg (bytes): The message to be signed.
digestmod (str): The name of the hash algorithm to use (e.g., 's... | import pytest
from solution import sign_message, verify_message
def test_sign_message_sha256():
key = b'secret_key'
msg = b'Important message'
digestmod = 'sha256'
expected_length = 64 # SHA-256 produces a 64-character hex string
signed_digest = sign_message(key, msg, digestmod)
assert len(sig... | [
{
"docstring": "Sign given message using HMAC.\n\nArgs:\nkey (bytes): The secret key used for the HMAC generation.\nmsg (bytes): The message to be signed.\ndigestmod (str): The name of the hash algorithm to use (e.g., 'sha256').\n\nReturns:\nstr: The hexadecimal digest of the signed message.",
"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": "import hmac\nimport hashlib\n\ndef sign_message(key: bytes, msg: bytes, digestmod: str) -> str:\n \"\"\"\n Sign given message using HMAC.\n\n Args:\n key (b... | trial_gpt4o_0 | {
"original_instruction": "Secure HMAC Message Verification\n\nA software application needs to ensure the integrity and authenticity of messages exchanged between a server and client using HMAC. You are required to implement a function in Python that will handle message signing and verification using the HMAC mechani... | 0.787779 | Docs: Python310_287 | C | [
"sign_message",
"verify_message"
] | 2 | [
[
"verify_message",
"sign_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f3143599ed470d62e274ae95042680ce103dee78 | 0d2550e821808fd1b903491cf7a48e46a594470f | |||
v1.0 | complete | Docs | Docs: Python310_455_C | import signal
class TimeoutError(Exception):
pass
def execute_with_timeout(func, args, timeout):
"""
Execute a function with a timeout. If the function does not complete within the specified
timeout, a TimeoutError should be raised.
Args:
func (callable): The target function to execute.
a... | import signal
import time
class TimeoutError(Exception):
pass
def handler(signum, frame):
raise TimeoutError
def execute_with_timeout(func, args, timeout):
"""
Execute a function with a timeout. If the function does not complete within the specified
timeout, a TimeoutError should be raised.
... | import pytest
from solution import execute_with_timeout, TimeoutError
import time
def long_running_func(seconds):
time.sleep(seconds)
return f"Completed after {seconds} seconds"
def test_execute_without_timeout():
assert execute_with_timeout(long_running_func, (2,), 5) == "Completed after 2 seconds"
def ... | [] | [
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 signal\n\nclass TimeoutError(Exception):\n pass\n\ndef execute_with_timeout(func, args, timeout):\n \"\"\"\n Execute a function with a timeout. If the f... | trial_gpt4o_1 | {
"original_instruction": "**Challenging Python Coding Assessment Question: Signal Handling and Timed Execution**\n\n### Problem Statement\nYou are tasked with writing a program that monitors the execution of a potentially long-running function and gracefully handles interruptions caused by signals. The program shoul... | 0.576871 | Docs: Python310_455 | C | [
"handler",
"execute_with_timeout"
] | 2 | [
[
"execute_with_timeout",
"handler"
]
] | 1 | [] | false | [
"TimeoutError"
] | true | pytest | true | [] | true | 337791cd7abc35f2dc8db565bb1b15ba6da1a24c | ee8e5d0d5607f26659a32f84155e68bcc0f1e31b | |||
v1.0 | complete | Docs | Docs: Python310_462_C | import asyncio
async def manage_queues(n: int, m: int, p: int,
standard_tasks: list,
priority_tasks: list,
lifo_tasks: list):
""" Queue Management System that processes tasks of different priorities.
The system reads input tasks an... | import asyncio
async def process_task(task_id, sleep_time):
await asyncio.sleep(sleep_time)
print(f'Completed task {task_id}')
async def manage_queues(n: int, m: int, p: int,
standard_tasks: list,
priority_tasks: list,
lifo_tasks: list... | import asyncio
from solution import manage_queues
def test_single_task():
standard_tasks = [(1, 0.1)]
priority_tasks = []
lifo_tasks = []
asyncio.run(manage_queues(1, 0, 0, standard_tasks, priority_tasks, lifo_tasks))
def test_priority_over_standard():
standard_tasks = [(1, 0.2), (2, 0.1)]
pr... | [] | [
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\nfrom asyncio import PriorityQueue, Queue, LifoQueue\n\nasync def process_task(task_id: int, sleep_time: float):\n await asyncio.sleep(sleep_time)\n ... | trial_gpt4o_2 | {
"original_instruction": "**Queue Management System**\n\nYou will create a Queue Management System that processes tasks of different priorities using asyncio. Your goal is to simulate a real-world scenario where tasks with higher priority should be processed before others. This system will:\n1. Use `asyncio.Priority... | 0.648429 | Docs: Python310_462 | C | [
"process_task",
"manage_queues"
] | 2 | [
[
"manage_queues",
"process_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1899dbd3deddda7531129c9e302fe9d4e8fbc378 | e072fe265161d687a3222027c86c276435d1e234 | |||
v1.0 | complete | Docs | Docs: Python310_518_C | import sqlite3
from typing import Tuple, List
def connect_to_db(db_name: str) -> sqlite3.Connection:
""" Connect to the SQLite database with the given name.
Create a table `inventory` with columns: `name` TEXT, `category` TEXT, `quantity` INTEGER, and `price` TEXT.
Commit changes and return the connection ... | import sqlite3
from typing import Tuple, List
def connect_to_db(db_name: str) -> sqlite3.Connection:
con = sqlite3.connect(db_name)
cur = con.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS inventory (
name TEXT,
category TEXT,
quantity INTEG... | import pytest
import sqlite3
from solution import (connect_to_db, insert_device, fetch_all_devices, update_quantity, delete_device,
define_custom_price_type, insert_device_with_custom_price)
def test_database_operations():
con = connect_to_db(":memory:")
try:
insert_device(con, (... | [] | [
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 sqlite3\nfrom typing import Tuple, List\n\ndef connect_to_db(db_name: str) -> sqlite3.Connection:\n con = sqlite3.connect(db_name)\n cur = con.cursor()\n ... | trial_gpt4o_0 | {
"original_instruction": "### **Python Coding Assessment: Advanced SQLite Operations**\n\n#### **Objective:**\n\nDemonstrate your understanding of the `sqlite3` module by performing complex database operations, including custom type adaptation, transaction control, and secure query execution.\n\n#### **Problem State... | 0.552844 | Docs: Python310_518 | C | [
"connect_to_db",
"insert_device",
"fetch_all_devices",
"update_quantity",
"delete_device",
"define_custom_price_type",
"insert_device_with_custom_price"
] | 7 | [
[
"insert_device_with_custom_price",
"insert_device"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 36783bab7d180a5425636b6b05c57b5ed2f7fc27 | 1ee356f45293f67715d7a11dc1203f5481ae17c9 | |||
v1.0 | complete | Docs | Docs: Pytorch_581_C | def check_mps_device():
"""
Checks if MPS device is available and built.
Returns:
-------
tuple: (bool, str)
A tuple where the first element indicates if MPS is available and the second element is a message.
Examples:
>>> is_available, message = check_mps_device()
>>> isinstan... | import torch
import torch.nn as nn
def check_mps_device():
"""
Checks if MPS device is available and built.
Returns
-------
tuple: (bool, str)
A tuple where the first element indicates if MPS is available and the second element is a message.
"""
if not torch.backends.mps.is_availab... | import pytest
import torch
import torch.nn as nn
from solution import check_mps_device, run_tensor_operations, run_model_on_mps
class MockSimpleNet(nn.Module):
def __init__(self):
super(MockSimpleNet, self).__init__()
self.fc1 = nn.Linear(5, 1)
def forward(self, x):
return self.fc1(x)
... | [
{
"docstring": "Checks if MPS device is available and built.\n\nReturns\n-------\ntuple: (bool, str)\n A tuple where the first element indicates if MPS is available and the second element is a message.",
"function_declaration": "def check_mps_device():",
"function_name": "check_mps_device",
"para... | [
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 torch\nimport torch.nn as nn\n\ndef check_mps_device():\n \"\"\"\n Checks if MPS device is available and built.\n\n Returns\n -------\n tuple: (bo... | trial_gpt4o_0 | {
"original_instruction": "### Question: GPU-Based Operations with PyTorch MPS Backend\n\nYou are given the task to utilize PyTorch's MPS backend to perform tensor operations and run a simple neural network model on a macOS device with Metal Performance Shaders (MPS) capability. Implement the following functions:\n\n... | 0.493564 | Docs: Pytorch_581 | C | [
"check_mps_device",
"run_tensor_operations",
"run_model_on_mps"
] | 3 | [
[
"run_model_on_mps",
"check_mps_device"
],
[
"run_tensor_operations",
"check_mps_device"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | eabf4462bab313b6a7b074c141d4646be2b7d140 | 8b37c2c652a65567cf89e29aa6cbf86e137efa0c | |||
v1.0 | complete | Docs | Docs: Pytorch_724_C | import torch
from typing import Tuple, Dict, Any
def initialize_device(device_index: int) -> None:
"""
Initializes and sets the device to the one specified by device_index.
Args:
- device_index (int): The index of the device to set.
Returns:
- None
"""
pass
def create_stream_... | import torch
from typing import Tuple, Dict, Any
def initialize_device(device_index: int) -> None:
"""
Initializes and sets the device to the one specified by device_index.
Args:
- device_index (int): The index of the device to set.
Returns:
- None
"""
if not torch.cuda.is_ava... | import pytest
from solution import initialize_device, create_stream_and_event, record_and_synchronize_event, memory_management_operations
import torch
def test_initialize_device():
if torch.cuda.is_available():
try:
initialize_device(0)
except Exception as e:
pytest.fail(f"I... | [
{
"docstring": "Initializes and sets the device to the one specified by device_index.\n\nArgs:\n- device_index (int): The index of the device to set.\n\nReturns:\n- None",
"function_declaration": "def initialize_device(device_index):",
"function_name": "initialize_device",
"parameter_list": "(device... | [
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\n\ndef initialize_device(device_index: int) -> None:\n \"\"\"\n Initializes and sets the device to the one specified by device_index.\n \n Args... | trial_gpt4o_2 | {
"original_instruction": "### Question: Efficient Stream and Device Management in PyTorch\n\nYou are required to implement a set of functions that demonstrate efficient management of streams, devices, and memory in PyTorch using the `torch.mtia` module.\n\n#### Functions to Implement\n\n1. **initialize_device**:\n ... | 0.34648 | Docs: Pytorch_724 | C | [
"initialize_device",
"create_stream_and_event",
"record_and_synchronize_event",
"memory_management_operations"
] | 4 | [
[
"create_stream_and_event",
"initialize_device"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 6b0b8f61ac2ea5231afd141f5548811fabdd9e6f | f85234ec6517b28f1207dd5a91f96d92b6dc63cf | |||
v1.0 | complete | Docs | Docs: Scikit_502_C | import numpy as np
import time
from sklearn.linear_model import SGDClassifier
from scipy import sparse
def sparsity_ratio(X):
return 1.0 - np.count_nonzero(X) / float(X.shape[0] * X.shape[1])
def measure_throughput(model, X):
start_time = time.time()
model.predict(X)
end_time = time.time()
through... | import numpy as np
import time
from sklearn.linear_model import SGDClassifier
from sklearn.feature_selection import SelectFromModel
from scipy import sparse
def sparsity_ratio(X):
return 1.0 - np.count_nonzero(X) / float(X.shape[0] * X.shape[1])
def measure_throughput(model, X):
start_time = time.time()
m... | import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import SGDClassifier
from solution import optimize_model_performance
def test_optimize_model_performance():
# Create a simple dataset
X_train, y_train = make_classification(n_samples=1000, n_features=20, n_informative... | [
{
"docstring": null,
"function_declaration": "def sparsity_ratio(X):",
"function_name": "sparsity_ratio",
"parameter_list": "(X)"
},
{
"docstring": null,
"function_declaration": "def measure_throughput(model, X):",
"function_name": "measure_throughput",
"parameter_list": "(model,... | [
0,
1,
0,
1,
0,
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 scipy import sparse\n\ndef sparsity_ratio(X):\n return 1.0 - np.count_nonzero(X... | trial_gpt4o_3 | {
"original_instruction": "**Objective:**\nYou are required to write a Python function that optimizes the prediction latency of a given machine learning model using scikit-learn. Your task involves adjusting model parameters, converting data representations appropriately, and analyzing throughput.\n\n**Problem Statem... | 0.648117 | Docs: Scikit_502 | C | [
"sparsity_ratio",
"measure_throughput",
"optimize_model_performance"
] | 3 | [
[
"optimize_model_performance",
"measure_throughput"
],
[
"optimize_model_performance",
"sparsity_ratio"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy",
"sklearn"
] | false | 74f17f42451b0ecd92146c277fc684225dddb59b | db151c5b2d51701b1a78f08c827edae8df0ba024 | |||
v1.0 | complete | Docs | Docs: Python310_673_C | import hashlib
def generate_file_hashes(file_path):
"""
Generate SHA256 and BLAKE2b hashes for the given file.
:param file_path: The path to the file to be hashed
:return: A dictionary with 'sha256' and 'blake2b' keys containing the hexadecimal hash digests
"""
pass
def verify_file_hashe... | import hashlib
def generate_file_hashes(file_path):
"""
Generate SHA256 and BLAKE2b hashes for the given file.
:param file_path: The path to the file to be hashed
:return: A dictionary with 'sha256' and 'blake2b' keys containing the hexadecimal hash digests
"""
sha256_hash = hashlib.sha256... | import pytest
from solution import generate_file_hashes, verify_file_hashes
def test_generate_file_hashes(tmp_path):
test_file = tmp_path / "test.txt"
test_file.write_text("Hello World")
hashes = generate_file_hashes(str(test_file))
assert hashes is not None
assert 'sha256' in hashes
asse... | [
{
"docstring": "Generate SHA256 and BLAKE2b hashes for the given file.\n\n:param file_path: The path to the file to be hashed\n:return: A dictionary with 'sha256' and 'blake2b' keys containing the hexadecimal hash digests",
"function_declaration": "def generate_file_hashes(file_path):",
"function_name":... | [
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 hashlib\n\ndef generate_file_hashes(file_path):\n \"\"\"\n Generates SHA256 and BLAKE2b hashes for the given file.\n\n Args:\n - file_path (str): The... | trial_gpt4o_1 | {
"original_instruction": "### Question: Implement a Secure File Integrity Verifier\n\n**Objective:**\nYou need to implement a Python program that verifies the integrity of files using SHA256 and BLAKE2b hash algorithms. The program will generate and verify hash values to ensure that the files have not been tampered ... | 0.694689 | Docs: Python310_673 | C | [
"generate_file_hashes",
"verify_file_hashes"
] | 2 | [
[
"verify_file_hashes",
"generate_file_hashes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 964ac1e5e13c6d674b098e6109e80bb3e4d9acf9 | 9d477f304c2854f759fa2bed269e84075cf45967 | |||
v1.0 | complete | Docs | Docs: Python310_974_C | from typing import List, Dict
def process_files_concurrently(file_paths: List[str]) -> List[Dict[str, int]]:
""" Process multiple files concurrently to count the number of words and lines.
>>> process_files_concurrently(['file1.txt', 'file2.txt', 'file3.txt'])
[{'file': 'file1.txt', 'word_count': 100, 'lin... | import concurrent.futures
from typing import List, Dict
def count_words_and_lines(file_path: str) -> Dict[str, int]:
try:
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
word_count = sum(len(line.split()) for line in lines)
line_count = len(... | import os
from solution import process_files_concurrently
def create_test_file(file_name, content):
with open(file_name, 'w', encoding='utf-8') as f:
f.write(content)
def remove_test_file(file_name):
if os.path.exists(file_name):
os.remove(file_name)
def test_process_files_concurrently():
... | [
{
"docstring": null,
"function_declaration": "def count_words_and_lines(file_path):",
"function_name": "count_words_and_lines",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def process_files_concurrently(file_paths):",
"function_name": "process_fil... | [
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 concurrent.futures\nfrom typing import List, Dict\n\ndef process_file(file_path: str) -> Dict[str, int]:\n \"\"\"\n Processes a single file to count the nu... | trial_gpt4o_9 | {
"original_instruction": "### Parallel File Processing with `concurrent.futures`\n\n#### Objective\nImplement a function `process_files_concurrently` to demonstrate your understanding of the `concurrent.futures` module. This function will process multiple files concurrently, where each file's content is processed to... | 0.657739 | Docs: Python310_974 | C | [
"count_words_and_lines",
"process_files_concurrently"
] | 2 | [
[
"process_files_concurrently",
"count_words_and_lines"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 60aa8d1605cbc779bb16623e732310ad6a69c3ff | 0db4ae55009484b7668578c3f85db2d10a43a8b1 | |||
v1.0 | complete | Docs | Docs: Python310_808_C | import asyncio
from typing import List, Tuple
class Task:
def __init__(self, priority: int, description: str):
self.priority = priority
self.description = description
def __lt__(self, other):
""" Compare tasks based on their priority (lower numbers indicate higher priority) """
... | import asyncio
import time
from typing import List, Tuple
class Task:
def __init__(self, priority: int, description: str):
self.priority = priority
self.description = description
def __lt__(self, other):
return self.priority < other.priority
async def worker(name: str, queue: asyn... | import asyncio
import time
from solution import Task, task_scheduler
def test_task_ordering():
task1 = Task(1, "Task 1")
task2 = Task(2, "Task 2")
task3 = Task(3, "Task 3")
assert (task1 < task2) == True
assert (task2 < task3) == True
assert (task3 < task1) == False
async def test_task_sc... | [] | [
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 time\n\nclass Task:\n def __init__(self, priority, description):\n self.priority = priority\n self.description = description\n\n... | trial_gpt4o_1 | {
"original_instruction": "You are tasked with designing a simplified task scheduling system using the `asyncio` queues in Python 3.10. Your goal is to create a system that manages tasks with different priorities and ensures that higher priority tasks are handled first.\n\n**Requirements:**\n\n1. Implement a `Task` c... | 0.613521 | Docs: Python310_808 | C | [
"worker",
"task_scheduler",
"main"
] | 3 | [
[
"task_scheduler",
"worker"
]
] | 1 | [] | false | [
"Task"
] | true | pytest | true | [] | true | 7092e703a410ea569e2f9567f0102e5f6c4ff314 | 1d6e16292fb1ebf6043d1ac105d6469e144cffaa | |||
v1.0 | complete | Docs | Docs: Python310_898_C | import gc
def create_cyclic_reference(num):
# Helper function to create cyclic references
class Cycle:
pass
head = Cycle()
current = head
# Create a cycle of objects
for _ in range(num):
current.next = Cycle()
current = current.next
current.next = head # Form a c... | import gc
def create_cyclic_reference(num):
# Helper function to create cyclic references
class Cycle:
pass
head = Cycle()
current = head
# Create a cycle of objects
for _ in range(num):
current.next = Cycle()
current = current.next
current.next = head # Form a c... | import pytest
from gc import set_debug, collect, get_stats, get_count, DEBUG_LEAK
from solution import gc_utility
def test_gc_utility_with_valid_input():
result = gc_utility(10)
assert 'collections' in result
assert 'collected' in result
assert 'uncollectable' in result
assert isinstance(result['co... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import gc\n\ndef create_cyclic_reference(num):\n class Cycle:\n pass\n\n head = Cycle()\n current = head\n\n for _ in range(num - 1):\n next_c... | trial_gpt4o_2 | {
"original_instruction": "#### Objective\n\nTo assess your understanding of the `gc` module in Python, particularly focusing on enabling/disabling garbage collection, inspecting objects for reference cycles, and gathering garbage collection statistics.\n\n#### Problem Statement\n\nIn this task, you will implement a ... | 0.472827 | Docs: Python310_898 | C | [
"create_cyclic_reference",
"gc_utility"
] | 2 | [
[
"gc_utility",
"create_cyclic_reference"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4798200ee16b879a5ebb4c4062f9575f6e5f2932 | 019b704ef5c5bb1b8a4465a9dd33d755ad859850 | |||
v1.0 | complete | Docs | Docs: Python310_537_C | import pickle
import sqlite3
from typing import Any
class Person:
def __init__(self, name: str, age: int, email: str):
self.name = name
self.age = age
self.email = email
def serialize_person(person: Person) -> bytes:
""" Serializes a Person object to a byte stream using pickle.
>>>... | import pickle
import sqlite3
class Person:
def __init__(self, name: str, age: int, email: str):
self.name = name
self.age = age
self.email = email
def serialize_person(person: Person) -> bytes:
"""
Serializes a Person object to a byte stream using pickle.
"""
return pickle.... | import sqlite3
import pytest
from solution import Person, serialize_person, deserialize_person, save_person_to_db, load_person_from_db
def test_serialize_deserialize_person():
person = Person(name="Jane Doe", age=25, email="jane.doe@example.com")
serialized = serialize_person(person)
deserialized = deseria... | [] | [
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 pickle\nimport sqlite3\n\nclass Person:\n def __init__(self, name: str, age: int, email: str):\n self.name = name\n self.age = age\n self... | trial_gpt4o_0 | {
"original_instruction": "#### Background\nYou are tasked with creating a program that demonstrates your ability to persist Python objects using the `pickle` module and interact with a SQLite database using the `sqlite3` module. Your program should involve serializing objects to save the application state and storin... | 0.54858 | Docs: Python310_537 | C | [
"serialize_person",
"deserialize_person",
"save_person_to_db",
"load_person_from_db"
] | 4 | [
[
"load_person_from_db",
"deserialize_person"
],
[
"save_person_to_db",
"serialize_person"
]
] | 2 | [] | false | [
"Person"
] | true | pytest | true | [] | true | 2cebe80a7bb04349e6328cbb0561370aa88fe04f | b49f3bf2304c0e4fdcf1b76ae288c220434c6fea | |||
v1.0 | complete | Docs | Docs: Python310_1040_C | from typing import List, Tuple, Optional
import aiohttp
import asyncio
async def fetch_multiple_urls(urls: List[str]) -> List[Tuple[str, Optional[str], Optional[Exception]]]:
""" Fetch multiple URLs concurrently with robust exception handling.
>>> urls = ["http://example.com", "https://httpbin.org/delay/3"]
... | from typing import List, Tuple, Optional
import aiohttp
import asyncio
async def fetch_url(session, url):
try:
async with session.get(url, timeout=5) as response:
content = await response.text()
return url, content, None
except (aiohttp.ClientError, asyncio.TimeoutError, asyncio... | import asyncio
import pytest
from solution import fetch_multiple_urls
@pytest.mark.asyncio
async def test_fetch_multiple_urls_success():
urls = [
"http://httpbin.org/get",
"http://httpbin.org/ip",
]
results = await fetch_multiple_urls(urls)
for url, content, exception in results:
... | [] | [
0,
0,
1
] | 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, Tuple, Optional\nimport aiohttp\nimport asyncio\nfrom aiohttp import ClientResponseError, ClientError, ClientTimeout\n\nasync def fetch_multipl... | trial_gpt4o_2 | {
"original_instruction": "### Asyncio Exception Handling Task\n\n#### Objective:\nWrite a Python function to handle multiple asyncio tasks, ensuring robust exception handling for common asyncio exceptions.\n\n#### Task:\nImplement an asynchronous function `fetch_multiple_urls(urls: List[str]) -> List[Tuple[str, Opti... | 0.552559 | Docs: Python310_1040 | C | [
"fetch_url",
"fetch_multiple_urls"
] | 2 | [
[
"fetch_multiple_urls",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | fa8f2e118dd7e06e13966cd16942a14b495d1b9c | 297e0c6130751fa978669f6b8ae2b80a9a8796ca | |||
v1.0 | complete | Docs | Docs: Python310_498_C | import os
LOG_FILE = "memory.log"
def log(message):
with open(LOG_FILE, "a") as f:
f.write(message + "\n")
def my_malloc(size):
"""Allocate a block of memory of the given size.
>>> array = my_malloc(100)
>>> isinstance(array, bytearray)
True
>>> with open(LOG_FILE) as f:
... '... | # We will implement the custom allocator in pure Python for simulation
# purposes since we do not have the capability to use the Python/C API
# directly here. Note that this will only serve as a conceptual mock-up.
import os
LOG_FILE = "memory.log"
def log(message):
with open(LOG_FILE, "a") as f:
f.writ... | import os
def setup_function():
if os.path.exists("memory.log"):
os.remove("memory.log")
def teardown_function():
if os.path.exists("memory.log"):
os.remove("memory.log")
def test_create_and_manage_array():
setup_function()
create_and_manage_array()
with open("memory.log... | [
{
"docstring": null,
"function_declaration": "def log(message):",
"function_name": "log",
"parameter_list": "(message)"
},
{
"docstring": null,
"function_declaration": "def my_malloc(size):",
"function_name": "my_malloc",
"parameter_list": "(size)"
},
{
"docstring": null,... | [
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.125 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Custom memory allocator implementation\n# Note: To implement the custom allocator and Python extension in Python,\n# we would normally use a C extension via a setup s... | trial_gpt4o_3 | {
"original_instruction": "### Python Memory Management: Custom Allocator Implementation\n\n**Objective:**\nDemonstrate your understanding of Python's memory management by implementing a custom memory allocator for a specific allocator domain and ensuring its correct usage with Python's memory management functions.\n... | 0.455085 | Docs: Python310_498 | C | [
"log",
"my_malloc",
"my_calloc",
"my_realloc",
"my_free",
"create_and_manage_array"
] | 6 | [
[
"create_and_manage_array",
"my_free"
],
[
"create_and_manage_array",
"my_malloc"
],
[
"create_and_manage_array",
"my_realloc"
],
[
"my_calloc",
"log"
],
[
"my_free",
"log"
],
[
"my_malloc",
"log"
],
[
"my_realloc",
"log"
]
] | 7 | [] | false | [] | false | pytest | false | [] | true | 14bbafde73fad1fc21f9c3e862052e05d3918b41 | 6ea13b61e911b14e40270d590aa09b8846bb1f42 | |||
v1.0 | complete | Docs | Docs: Python310_1050_C | from typing import List
def is_prime(n: int) -> bool:
""" Check if a number is prime.
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> is_prime(5)
True
"""
pass
def process_numbers(numbers: List[int]) -> int:
""" Process a list of numbers: filter, tra... | from typing import List
from functools import reduce
import operator
def is_prime(n: int) -> bool:
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def process_numbers(numbers: List[int]) -> int:
primes = filter(is_prime, nu... | from solution import is_prime, process_numbers
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert is_prime(13)
assert not is_prime(14)
assert not is_prime(1)
def test_process_numbers():
assert process_numbers([10, 15, 3, 11, 7, 2... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def process_numbers(numbers):",
"function_name": "process_numbers",
"parameter_list": "(numbers)"
}
] | [
0,
0,
1
] | 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\nfrom functools import reduce\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Checks if a number is prime or not.\n \"\"\"\n if n <= 1:\... | trial_gpt4o_2 | {
"original_instruction": "### Question: Advanced Filtering and Transformation with Functional Programming Modules\n\nYou are tasked with processing a list of numerical values using advanced functional programming techniques. Specifically, you need to perform a sequence of operations to filter, transform, and aggrega... | 0.777583 | Docs: Python310_1050 | C | [
"is_prime",
"process_numbers"
] | 2 | [
[
"process_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 540f4210b9db1b1f86a75a06fcb2508a3217ad28 | 3fbccbb3f3c984601141d42496372d658a4234a1 | |||
v1.0 | complete | Docs | Docs: Python310_1216_C | import asyncio
import aiohttp
from urllib.parse import urlparse
async def fetch_content(url):
"""Fetch content from URL asynchronously."""
# Implementation here
pass
async def save_content(url, content):
"""Save content to a file named after the domain of the URL."""
# Implementation here
pass... | import asyncio
import aiohttp
from urllib.parse import urlparse
# Example list of URLs
urls = [
'http://example.com',
'http://example.org',
'http://example.net'
]
async def fetch_content(url):
"""Fetch content from URL asynchronously."""
try:
async with aiohttp.ClientSession() as session:
... | import asyncio
import pytest
from unittest.mock import patch, mock_open
from solution import fetch_content, save_content, main
@pytest.mark.asyncio
async def test_fetch_content_success():
url = "http://example.com"
content = "Example Domain"
async def mock_get(*args, **kwargs):
class MockRespo... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport aiohttp\nfrom urllib.parse import urlparse\n\nasync def fetch_content(url):\n \"\"\"Fetch content from URL asynchronously.\"\"\"\n timeout ... | trial_gpt4o_2 | {
"original_instruction": "### Concurrent Web Scraper using `asyncio`\n\n#### Objective:\nImplement a concurrent web scraper using `asyncio` that fetches the content of a list of URLs and saves each page's content to a file named after the domain of the URL.\n\n#### Requirements:\n1. Your solution must use `asyncio` ... | 0.577036 | Docs: Python310_1216 | C | [
"fetch_content",
"save_content",
"main",
"fetch_and_save"
] | 4 | [
[
"fetch_and_save",
"fetch_content"
],
[
"fetch_and_save",
"save_content"
]
] | 2 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 1a6e9d7e3a319f83da1161d9a53abf3dc123e50c | cec2e4e2a3421ca930e60a4288886589f2f7fd20 | |||
v1.0 | complete | Docs | Docs: Python310_1021_C | import asyncio
from typing import List, Tuple, Dict
async def run_commands(commands: List[str]) -> Tuple[Dict[str, str], Dict[str, int]]:
""" Executes multiple shell commands asynchronously, collects their output, and manages their lifecycle.
Args:
commands (List[str]): A list of shell commands to run.... | import asyncio
from typing import List, Tuple, Dict
async def run_command(command: str):
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
stdout = stdout.d... | import asyncio
from solution import run_commands
def test_run_commands():
commands = ["echo Hello", "ls /nonexistent_directory", "sleep 1; echo Done"]
expected_output = {
"echo Hello": "Hello",
"ls /nonexistent_directory": "",
"sleep 1; echo Done": "Done"
}
expected_exit_codes =... | [] | [
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, Dict\n\nasync def run_command(command: str) -> Tuple[str, int]:\n process = await asyncio.create_subprocess_shell(\n ... | trial_gpt4o_1 | {
"original_instruction": "### Asyncio Subprocesses: A Practical Exercise\n\nYou are tasked with implementing a function that executes multiple shell commands asynchronously, collects their output, and manages their lifecycle. This will test your understanding of Python's asyncio subprocess module.\n\n#### Task\n\nIm... | 0.638623 | Docs: Python310_1021 | C | [
"run_command",
"run_commands"
] | 2 | [
[
"run_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4dd34b0020fa6508a5c1018ee54b8d1a6cff23b5 | 1352e2aa96e1f32dc5dda7e04801db743e340148 | |||
v1.0 | complete | Docs | Docs: Python310_834_C | import os
from _io import TextIOWrapper
def process_paths_and_interactivity(paths):
"""
This function takes a list of paths and performs the following operations:
1. Converts each path to its file system representation.
2. Checks if the file stream associated with each path is interactive.
Par... | import os
from _io import TextIOWrapper
def pyos_fspath(path):
"""
Mock implementation of PyOS_FSPath for converting path to filesystem representation.
In a real setup, this would be part of the python310 package.
"""
return os.fspath(path)
def py_fd_is_interactive(fp):
"""
Mock implementa... | from solution import process_paths_and_interactivity
def test_process_paths_valid_paths():
# Assuming these paths are valid paths in a real file system environment
paths = ["/dev/tty", "/non/interactive/file.txt"]
result = process_paths_and_interactivity(paths)
assert result["/dev/tty"][0] == "/dev/tty... | [
{
"docstring": "Mock implementation of PyOS_FSPath for converting path to filesystem representation.\nIn a real setup, this would be part of the python310 package.",
"function_declaration": "def pyos_fspath(path):",
"function_name": "pyos_fspath",
"parameter_list": "(path)"
},
{
"docstring":... | [
0,
0,
0,
0,
1,
0,
1,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport sys\nfrom typing import List, Dict, Tuple\n\ndef process_paths_and_interactivity(paths: List[str]) -> Dict[str, Tuple[str, bool]]:\n \"\"\"\n Th... | trial_gpt4o_9 | {
"original_instruction": "**Objective:**\nImplement a function that processes a list of paths, determines their file system representation, and checks if they are interactive streams, utilizing functions available in the python310 package.\n\n**Function:**\n```python\ndef process_paths_and_interactivity(paths):\n ... | 0.608738 | Docs: Python310_834 | C | [
"pyos_fspath",
"py_fd_is_interactive",
"process_paths_and_interactivity"
] | 3 | [
[
"process_paths_and_interactivity",
"py_fd_is_interactive"
],
[
"process_paths_and_interactivity",
"pyos_fspath"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3fa76563c222a2b93f529fa114e20f589756de2b | f10729b055005ba47d5bd4216f03cff45f7fc5b1 | |||
v1.0 | complete | Docs | Docs: Python310_796_C | import socket
from typing import Tuple, List
def create_server_socket(port: int) -> socket.socket:
""" Create an INET, STREAMing server socket, bind it to the provided port on
localhost, and set it to listen for incoming connections.
"""
pass
def accept_new_connection(server_socket: socket.socket) -... | import socket
from typing import Tuple, List
import select
def create_server_socket(port: int) -> socket.socket:
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('localhost', port))
server_socket.li... | import socket
import pytest
from solution import create_server_socket, accept_new_connection, broadcast_message, handle_client_message
@pytest.fixture
def server_socket():
return create_server_socket(12345)
def test_create_server_socket():
server_socket = create_server_socket(12345)
assert isinstance(serv... | [
{
"docstring": null,
"function_declaration": "def create_server_socket(port):",
"function_name": "create_server_socket",
"parameter_list": "(port)"
},
{
"docstring": null,
"function_declaration": "def accept_new_connection(server_socket):",
"function_name": "accept_new_connection",
... | [
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 socket\nimport select\n\ndef create_server_socket(port: int) -> socket.socket:\n \"\"\"\n Create an INET, STREAMing server socket, bind it to the provided ... | trial_gpt4o_1 | {
"original_instruction": "### Advanced Python Coding Challenge: Multi-Client Chat Server\n\n#### Problem Statement\nYou are required to implement a multi-client chat server using Python's `socket` and `select` modules. The server should handle multiple clients simultaneously, allowing them to communicate with each o... | 0.725193 | Docs: Python310_796 | C | [
"create_server_socket",
"accept_new_connection",
"broadcast_message",
"handle_client_message",
"main"
] | 5 | [
[
"handle_client_message",
"broadcast_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 745801e5569f3dd7e44e7b94beff09981aace232 | 174ed117eeb7886e1b53cbfc6f7a5b5e1fe6df41 | |||
v1.0 | complete | Docs | Docs: Pytorch_1095_C | import torch
import torch.nn as nn
import torch.func as func
class MyModel(nn.Module):
""" Simple neural network model with Linear layers """
def __init__(self):
super(MyModel, self).__init__()
self.layer1 = nn.Linear(3, 2)
self.layer2 = nn.Linear(2, 2)
def forward(self, x: tor... | import torch
import torch.nn as nn
import torch.func as func
# Define your model
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.layer1 = nn.Linear(3, 2)
self.layer2 = nn.Linear(2, 2)
def forward(self, x):
x = self.layer1(x)
x = se... | import torch
from torch import nn
from solution import MyModel, model_function, compute_jacobian
def test_model_initialization():
model = MyModel()
assert isinstance(model, nn.Module)
assert len(list(model.named_parameters())) > 0
def test_model_function_output_shape():
model = MyModel()
x = torch... | [] | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.func as func\n\n# Define the simple neural network model MyModel using torch.nn.Module\nclass MyModel(nn.Module):\n ... | trial_gpt4o_7 | {
"original_instruction": "**Question:**\n\nIn this coding assessment, you are required to implement and utilize PyTorch's `torch.func` API to demonstrate your understanding of function transforms and utilities for working with `torch.nn.Module`.\n\n### Task Description\n\n1. **Model Definition and Parameter Extracti... | 0.639031 | Docs: Pytorch_1095 | C | [
"model_function",
"compute_jacobian"
] | 2 | [
[
"compute_jacobian",
"model_function"
]
] | 1 | [] | false | [
"MyModel"
] | true | pytest | true | [
"torch"
] | false | 7e48a07ec58b107b7f7be16f4acefe4a763e6726 | ddd6d1caa9346fe38087a314998476e1f26fffd5 | |||
v1.0 | complete | Docs | Docs: Python310_1252_C | import multiprocessing
from typing import List, Tuple
def compute_task(task: Tuple[int, int, str]) -> str:
""" Helper function to compute the result of a single task."""
pass
def process_tasks(tasks: List[Tuple[int, int, str]]) -> List[str]:
""" Process a list of computational tasks in parallel using mult... | import multiprocessing
from typing import List, Tuple
def compute_task(task: Tuple[int, int, str]) -> str:
a, b, operation = task
if operation == 'add':
result = a + b
elif operation == 'subtract':
result = a - b
elif operation == 'multiply':
result = a * b
elif operation ==... | from solution import process_tasks
def test_process_tasks_basic_operations():
tasks = [
(1, 2, 'add'),
(6, 3, 'subtract'),
(4, 2, 'multiply')
]
assert process_tasks(tasks) == [
'1 add 2 = 3',
'6 subtract 3 = 3',
'4 multiply 2 = 8'
]
def test_process_task... | [
{
"docstring": null,
"function_declaration": "def compute_task(task):",
"function_name": "compute_task",
"parameter_list": "(task)"
},
{
"docstring": null,
"function_declaration": "def process_tasks(tasks):",
"function_name": "process_tasks",
"parameter_list": "(tasks)"
}
] | [
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 multiprocessing import Pool\nfrom typing import List, Tuple\n\ndef compute_task(task: Tuple[int, int, str]) -> str:\n a, b, operation = task\n if operation =... | trial_gpt4o_1 | {
"original_instruction": "**Problem Statement**\n\nYou are required to implement a parallelized solution to process a list of tasks using the `multiprocessing` module. Each task involves some computation, and you need to ensure that the results of these computations are collected and processed in a synchronized mann... | 0.748929 | Docs: Python310_1252 | C | [
"compute_task",
"process_tasks"
] | 2 | [
[
"process_tasks",
"compute_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b5f60d421869043443e58269c14cbc0aeeafa907 | 9f4b454ab400680ae482f39ab39b174ed84b5aed | |||
v1.0 | complete | Docs | Docs: Python310_1345_C | def closure_cell_example():
""" Simulate the behavior of closure using Python310 Cell objects' functionalities.
Returns:
Callable: A tuple containing two functions - `incrementer` and `current_value`.
>>> increment, current = closure_cell_example()
>>> current()
0
>>> increment... | # As PyCell_New, PyCell_Get, and PyCell_Set are part of the CPython API, we will simulate the functionality in pure Python.
def PyCell_New(obj):
""" Simulate the creation of a new cell containing the object 'obj' """
class Cell:
def __init__(self, value):
self.value = value
... | from solution import closure_cell_example
def test_initial_value():
increment, current = closure_cell_example()
assert current() == 0
def test_increment_once():
increment, current = closure_cell_example()
increment()
assert current() == 1
def test_increment_multiple_times():
increment, curren... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Let's create a function that demonstrates the use of cell objects. Since `PyCell_New`, `PyCell_Get`,\n# `PyCell_Set` are hypothetical or direct references to the C AP... | trial_gpt4o_1 | {
"original_instruction": "### Python310 Cell Objects - Coding Assessment Question\n\n#### Objective:\nDemonstrate the use of Python310 Cell objects to manage and manipulate shared variables across multiple scopes.\n\n#### Problem Statement:\nWrite a Python function `closure_cell_example()` that simulates the behavio... | 0.479066 | Docs: Python310_1345 | C | [
"PyCell_New",
"PyCell_Get",
"PyCell_Set",
"closure_cell_example"
] | 4 | [
[
"closure_cell_example",
"PyCell_Get"
],
[
"closure_cell_example",
"PyCell_New"
],
[
"closure_cell_example",
"PyCell_Set"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 1aa6717c225b168f1b73b99424ba919f00bb4e70 | 617ea8a8f2d0c237a45792b43e6131e026854ef3 | |||
v1.0 | complete | Docs | Docs: Python310_678_C | from xmlrpc.server import SimpleXMLRPCServer
def setup_xmlrpc_server():
"""
Implement an XML-RPC server using the xmlrpc.server module that performs the following:
1. Create an instance of SimpleXMLRPCServer.
2. Register several built-in Python functions such as pow, abs, and max.
3. Implement and ... | from xmlrpc.server import SimpleXMLRPCServer
import threading
# Custom function
def concatenate_strings(s1, s2):
return s1 + s2
# Class for additional operations
class MathOperations:
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def run_server():
# Setting... | import xmlrpc.client
import pytest
# Connect to the server
proxy = xmlrpc.client.ServerProxy('http://localhost:8080')
def test_pow():
assert proxy.pow(2, 3) == 8
def test_abs():
assert proxy.abs(-10) == 10
def test_max():
assert proxy.max(1, 5, 3) == 5
def test_concatenate_strings():
assert proxy.c... | [] | [
0,
0,
0,
1,
0,
0,
0,
0,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from xmlrpc.server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler\n\n# Function to concatenate two strings\ndef concatenate_strings(s1, s2):\n return s1 + s2\... | trial_gpt4o_8 | {
"original_instruction": "### Task\n\nYou are required to implement an XML-RPC server using the `xmlrpc.server` module that performs the following:\n\n1. Create an instance of `SimpleXMLRPCServer`.\n2. Register several built-in Python functions such as `pow`, `abs`, and `max`.\n3. Implement and register a custom fun... | 0.383532 | Docs: Python310_678 | C | [
"concatenate_strings",
"run_server"
] | 2 | [
[
"run_server",
"concatenate_strings"
]
] | 1 | [] | false | [
"MathOperations"
] | true | pytest | false | [] | true | b056791c64e995a77ec065649aba73f98e0868db | c56a6201aca0b462f3ed77011d34c76850e3274e | |||
v1.0 | complete | Docs | Docs: Python310_1261_C | import grp
def get_group_by_id(group_id: int):
"""Retrieve the group entry by group ID.
>>> get_group_by_id(1234)
('example', '', 1234, ['user1', 'user2'])
>>> get_group_by_id(9999)
None
"""
pass
def get_group_by_name(group_name: str):
"""Retrieve the group entry by group name.
>>>... | import grp
def get_group_by_id(group_id):
"""
Retrieve the group entry by group ID.
"""
try:
group = grp.getgrgid(group_id)
return group
except KeyError:
return None
def get_group_by_name(group_name):
"""
Retrieve the group entry by group name.
"""
try:
... | import pytest
from solution import get_group_by_id, get_group_by_name, list_all_groups, add_user_to_group, remove_user_from_group
def test_get_group_by_id_existing_group(monkeypatch):
def mock_getgrgid(group_id):
return ('example', '', group_id, ['user1', 'user2'])
monkeypatch.setattr('grp.getgrgid', m... | [
{
"docstring": "Retrieve the group entry by group ID.",
"function_declaration": "def get_group_by_id(group_id):",
"function_name": "get_group_by_id",
"parameter_list": "(group_id)"
},
{
"docstring": "Retrieve the group entry by group name.",
"function_declaration": "def get_group_by_name... | [
0,
0,
0,
0,
0,
0,
0,
1,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import grp\n\ndef get_group_by_id(group_id):\n \"\"\"\n Returns the group entry for the given group_id.\n If no group is found, returns None.\n \"\"\"\n ... | trial_gpt4o_8 | {
"original_instruction": "### Group Management Script\n\nYou are tasked with creating a Python script that interacts with the Unix group database using the `grp` module. The script should perform the following operations:\n\n1. **Retrieve Group by ID**:\n - Create a function `get_group_by_id(group_id)` that takes ... | 0.464931 | Docs: Python310_1261 | C | [
"get_group_by_id",
"get_group_by_name",
"list_all_groups",
"add_user_to_group",
"remove_user_from_group"
] | 5 | [
[
"add_user_to_group",
"get_group_by_name"
],
[
"remove_user_from_group",
"get_group_by_name"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8e4e2136449f17d0a5331ab625f0c3544743ac3e | 72a7b75bcae1a3b1819442282d71e83e3bddd80c | |||
v1.0 | complete | Docs | Docs: Pytorch_1539_C | import torch
def manipulate_tensors(fill_memory: bool) -> torch.Tensor:
"""
Create an uninitialized tensor of size (3, 3) with the option to fill uninitialized memory deterministically.
Args:
fill_memory (bool): If True, fill uninitialized memory deterministically.
Returns:
torch.Tensor: The r... | import torch
def manipulate_tensors(fill_memory: bool) -> torch.Tensor:
"""
Create and return an uninitialized tensor of size (3, 3),
with the option to fill uninitialized memory deterministically.
"""
if fill_memory:
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.b... | from solution import manipulate_tensors
def test_tensor_with_fill_uninitialized_memory_true():
tensor = manipulate_tensors(True)
assert tensor.size() == (3, 3)
assert torch.backends.cudnn.deterministic is True
def test_tensor_with_fill_uninitialized_memory_false():
tensor = manipulate_tensors(False)
... | [
{
"docstring": "Create and return an uninitialized tensor of size (3, 3), \nwith the option to fill uninitialized memory deterministically.",
"function_declaration": "def manipulate_tensors(fill_memory):",
"function_name": "manipulate_tensors",
"parameter_list": "(fill_memory)"
},
{
"docstri... | [
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 torch\n\ndef manipulate_tensors(fill_memory: bool) -> torch.Tensor:\n \"\"\"\n Create and return an uninitialized tensor of size (3, 3), \n with the opt... | trial_gpt4o_0 | {
"original_instruction": "**Challenging PyTorch Coding Question: Deterministic Tensor Initialization**\n\n### Objective\nYour task is to write code that demonstrates an understanding of deterministic algorithm settings and uninitialized memory handling in PyTorch. You will manipulate tensors, enabling and disabling ... | 0.442931 | Docs: Pytorch_1539 | C | [
"manipulate_tensors",
"check_uninitialized_memory"
] | 2 | [
[
"check_uninitialized_memory",
"manipulate_tensors"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 073df83a2dc3da189f94df37d49025ae00f22ffb | d9262a1e8f178d47036aeb87e8fd8e4c479f51ff | |||
v1.0 | complete | Docs | Docs: Python310_1334_C | import asyncio
async def single_task(index: int) -> int:
"""Perform a simple I/O-bound operation using asyncio.
Args:
index (int): Index of the task.
Returns:
int: The same index after a short sleep.
"""
await asyncio.sleep(1)
return index
async def platform_aware... | import asyncio
import platform
async def single_task(index: int) -> int:
await asyncio.sleep(1)
return index
async def platform_aware_async_task(n: int) -> list:
if n < 1 or n > 1000:
raise ValueError("n must be between 1 and 1000")
tasks = [single_task(i) for i in range(n)]
current_p... | import pytest
import asyncio
from solution import platform_aware_async_task, single_task
@pytest.mark.asyncio
async def test_single_task():
result = await single_task(5)
assert result == 5
@pytest.mark.asyncio
async def test_platform_aware_async_task_small():
results = await platform_aware_async_task(5)
... | [] | [
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 platform\n\nasync def single_task(index: int) -> int:\n await asyncio.sleep(1)\n return index\n\nasync def platform_aware_async_task(n: int... | trial_gpt4o_0 | {
"original_instruction": "#### Background\nYou are required to demonstrate a solid understanding of Python's asyncio module and its limitations on different platforms. Particularly, you need to showcase handling asynchronous tasks keeping in mind the constraints mentioned in the provided documentation.\n\n#### Probl... | 0.522676 | Docs: Python310_1334 | C | [
"single_task",
"platform_aware_async_task"
] | 2 | [
[
"platform_aware_async_task",
"single_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1f619b583b748442dc912b5a248fa3a7eee7f578 | 36a718a4796583ac70f4ffc4b85503d3dc0e1361 | |||
v1.0 | complete | Docs | Docs: Python310_1495_C | async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
""" Handle individual client connection
- Receive data from the client
- Transform the received message to upper case
- Send the transformed message back to the client
- Close the connection gracefully
"""
asyn... | import asyncio
async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} from {addr!r}")
response = message.upper()
print(f"Send: {res... | import asyncio
import pytest
from solution import start_server, start_client
@pytest.mark.asyncio
async def test_server_client_interaction():
server_task = asyncio.create_task(start_server())
# Wait a moment for the server to start
await asyncio.sleep(1)
client_task = asyncio.create_task(star... | [] | [
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: asyncio.StreamReader, writer: asyncio.StreamWriter):\n data = await reader.read(100)\n message = data.decode()\n... | trial_gpt4o_0 | {
"original_instruction": "### Asynchronous TCP Server-Client Model\n\n#### Objective\nDesign and implement an asynchronous TCP server-client model using the asyncio package.\n\n#### Description\nYou are required to implement two components: an asynchronous TCP server and an asynchronous TCP client. The server will r... | 0.56872 | Docs: Python310_1495 | C | [
"handle_client",
"start_server",
"start_client"
] | 3 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9f2aaa98c3f98a73474c1e750a3d224e26d79a50 | 63f83291d6a2e85a4c806cc9f55e8fe38224b0a2 | |||
v1.0 | complete | Docs | Docs: Python310_1652_C | import contextvars
import asyncio
# Declare the ContextVar to store user session data
# user_session = ...
def get_user_session():
"""
Retrieve the current user session.
"""
pass
def update_user_session(data: dict):
"""
Update the user session with the provided data.
"""
pass
async d... | import contextvars
import asyncio
# Declare the ContextVar to store user session data
user_session = contextvars.ContextVar("user_session", default={})
def get_user_session():
"""
Retrieve the current user session.
"""
return user_session.get()
def update_user_session(data: dict):
"""
Update ... | import pytest
import asyncio
from solution import get_user_session, update_user_session, handle_request
def test_get_user_session_empty():
"""
Test that getting user session initially returns an empty dictionary.
"""
assert get_user_session() == {}
def test_update_user_session():
"""
Test that... | [
{
"docstring": "Retrieve the current user session.",
"function_declaration": "def get_user_session():",
"function_name": "get_user_session",
"parameter_list": "()"
},
{
"docstring": "Update the user session with the provided data.",
"function_declaration": "def update_user_session(data):... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import contextvars\nimport asyncio\n\n# Declare the ContextVar to store user session data\nuser_session = contextvars.ContextVar(\"user_session\", default={})\n\ndef ge... | trial_gpt4o_2 | {
"original_instruction": "#### Objective\nThe goal of this exercise is to test your understanding and ability to work with context variables in Python, specifically utilizing the `contextvars` module to manage state in asynchronous and concurrent code.\n\n#### Problem Statement\nCreate a Python function that uses co... | 0.474366 | Docs: Python310_1652 | C | [
"get_user_session",
"update_user_session",
"handle_request",
"main"
] | 4 | [
[
"handle_request",
"get_user_session"
],
[
"handle_request",
"update_user_session"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d011cdbdbdc8c3ab4ed2689dfb7964c0687bf867 | c97f9b63f34a4f31afea9ac6afdb12c7592106e2 | |||
v1.0 | complete | Docs | Docs: Python310_1115_C | from typing import List
def validate_subnets(subnets: List[str]) -> List[str]:
""" Validate a list of subnets and return a list of valid subnet strings.
Invalid subnets should be ignored.
>>> validate_subnets(["192.168.0.0/24", "invalid_subnet", "10.0.0.0/8"]) ["192.168.0.0/24", "10.0.0.0/8"]
>>> vali... | import ipaddress
def validate_subnets(subnets):
valid_subnets = []
for subnet in subnets:
try:
ipaddress.ip_network(subnet, strict=False)
valid_subnets.append(subnet)
except ValueError:
continue
return valid_subnets
def is_ip_in_subnets(ip, subnets):
... | from solution import validate_subnets, is_ip_in_subnets, summarize_subnets, total_unique_ips
def test_validate_subnets():
assert validate_subnets(["192.168.0.0/24", "invalid_subnet", "10.0.0.0/8"]) == ["192.168.0.0/24", "10.0.0.0/8"]
assert validate_subnets(["256.256.256.256/32"]) == []
def test_is_ip_in_subn... | [
{
"docstring": null,
"function_declaration": "def validate_subnets(subnets):",
"function_name": "validate_subnets",
"parameter_list": "(subnets)"
},
{
"docstring": null,
"function_declaration": "def is_ip_in_subnets(ip, subnets):",
"function_name": "is_ip_in_subnets",
"parameter_... | [
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 ipaddress\n\ndef validate_subnets(subnets):\n valid_subnets = []\n for subnet in subnets:\n try:\n ipaddress.ip_network(subnet)\n ... | trial_gpt4o_5 | {
"original_instruction": "You are tasked with developing a network analysis tool that can process a list of subnets and perform various network calculations. Specifically, you need to:\n1. Validate the subnets.\n2. Identify if a given address falls within any of the given subnets.\n3. Summarize the given subnets to ... | 0.654865 | Docs: Python310_1115 | C | [
"validate_subnets",
"is_ip_in_subnets",
"summarize_subnets",
"total_unique_ips"
] | 4 | [
[
"total_unique_ips",
"validate_subnets"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 94421d68ab426f46f905a51dfc265791506d656b | bf6810d4bd96dd3a6ba0878e50692c32bf1f2c77 | |||
v1.0 | complete | Docs | Docs: Pandas_1101_C | import pandas as pd
def load_data(file_path: str) -> pd.DataFrame:
"""
Loads data from a CSV file into a pandas DataFrame.
Parameters:
- file_path: str, path to the CSV file
Returns:
- pd.DataFrame: DataFrame containing the loaded data
"""
pass
def clean_data(df: pd.DataFrame... | import pandas as pd
def load_data(file_path: str) -> pd.DataFrame:
"""
Loads data from a CSV file into a pandas DataFrame.
Parameters:
- file_path: str, path to the CSV file
Returns:
- pd.DataFrame: DataFrame containing the loaded data
"""
return pd.read_csv(file_path)
def cl... | from solution import load_data, clean_data, total_sales_by_product_and_store, top_product_by_store, daily_avg_quantity
import pandas as pd
from io import StringIO
def test_load_data():
data = """Date,Store,Product,Quantity,Revenue
2021-01-01,StoreA,Product1,10,100
2021-01-02,StoreB,Product2,20,200
"""
... | [
{
"docstring": "Loads data from a CSV file into a pandas DataFrame.\n\nParameters:\n- file_path: str, path to the CSV file\n\nReturns:\n- pd.DataFrame: DataFrame containing the loaded data",
"function_declaration": "def load_data(file_path):",
"function_name": "load_data",
"parameter_list": "(file_p... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\n\ndef load_data(file_path: str) -> pd.DataFrame:\n \"\"\"\n Load the data from the CSV file into a Pandas DataFrame.\n \"\"\"\n return ... | trial_gpt4o_7 | {
"original_instruction": "### Pandas Coding Challenge\n\n**Objective:** Validate students' understanding of pandas by having them perform a series of data operations on a given dataset.\n\n#### Problem Statement\n\nYou are provided with a dataset in CSV format containing the sales records of a retail store. The CSV ... | 0.764951 | Docs: Pandas_1101 | C | [
"load_data",
"clean_data",
"total_sales_by_product_and_store",
"top_product_by_store",
"daily_avg_quantity"
] | 5 | [
[
"top_product_by_store",
"total_sales_by_product_and_store"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | 52030f557011fbd2d6a37a798be7b82b8a25022d | 403a105bb98e67c6be2f708bf112d12430c6610e | |||
v1.0 | complete | Docs | Docs: Python310_1052_C | import asyncio
from typing import List, Tuple
async def process_task_queue(task_list: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
""" Process a queue of tasks concurrently using asyncio.
Each task is represented as a tuple (duration, task_id), where duration
is the time in seconds the task takes to e... | import asyncio
from typing import List, Tuple
async def worker(queue: asyncio.Queue, results: List[Tuple[int, int]]):
while True:
task = await queue.get()
if task is None:
break
duration, task_id = task
await asyncio.sleep(duration)
results.append((task_id, int(a... | import asyncio
import pytest
from solution import process_task_queue
@pytest.mark.asyncio
async def test_process_task_queue():
task_list = [(2, 1), (3, 2), (1, 3)]
result = await process_task_queue(task_list)
completion_times = [r[1] for r in result]
# Checking order based on completion times
... | [] | [
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(name: int, queue: asyncio.Queue, results: List[Tuple[int, int]]):\n while True:\n # Get a t... | trial_gpt4o_2 | {
"original_instruction": "### Asyncio Task Queue Implementation\n\n**Objective**: Demonstrate your understanding of the `asyncio` package by implementing a function that manages a queue of tasks to be executed asynchronously.\n\n**Task Description**:\nWrite an asynchronous function `process_task_queue(task_list: Lis... | 0.603153 | Docs: Python310_1052 | C | [
"worker",
"process_task_queue"
] | 2 | [
[
"process_task_queue",
"worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2dfb311e97d6c198966541dbe175dfa1e9fc1065 | 6f339eadc19ca75cbdcc78e7997af5ba062ea196 | |||
v1.0 | complete | Docs | Docs: Scikit_1722_C | from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from scipy.sparse import csr_matrix
import time
def train_model():
""" Load the dataset, train the model and return the trained model along with test data.
"""
p... | from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from scipy.sparse import csr_matrix
import time
def train_model():
# Load the dataset
diabetes = load_diabetes()
X, y = diabetes.data, diabetes.target
# Spl... | import pytest
from solution import train_model, measure_baseline_latency, optimize_bulk_predictions, optimize_sparse_input, measure_latency
def test_train_model():
model, X_test = train_model()
assert model is not None
assert X_test.shape[0] > 0
def test_measure_baseline_latency():
model, X_test = t... | [
{
"docstring": null,
"function_declaration": "def train_model():",
"function_name": "train_model",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def measure_baseline_latency(model, X_test):",
"function_name": "measure_baseline_latency",
"parameter_list":... | [
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 time\nfrom sklearn.datasets import load_diabetes\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom s... | trial_gpt4o_9 | {
"original_instruction": "Optimize Prediction Performance with Scikit-learn\n\n#### Objective:\nThe goal of this task is to assess the student's ability to optimize model prediction latency and throughput using Scikit-learn. The task involves measuring performance metrics, handling data representation, and configuri... | 0.626171 | Docs: Scikit_1722 | C | [
"train_model",
"measure_baseline_latency",
"optimize_bulk_predictions",
"optimize_sparse_input",
"measure_latency"
] | 5 | [
[
"measure_latency",
"measure_baseline_latency"
],
[
"measure_latency",
"optimize_bulk_predictions"
],
[
"measure_latency",
"optimize_sparse_input"
],
[
"measure_latency",
"train_model"
]
] | 4 | [] | false | [] | false | pytest | true | [
"scipy",
"sklearn"
] | false | b6bb82d184a36a2064a2868147721b7a084df0ae | eda995df329ee33d186c7814d6d93f03122d4ea1 | |||
v1.0 | complete | Docs | Docs: Python310_1011_C | import asyncio
async def run_commands(commands: list[str]) -> dict[str, dict[str, str]]:
""" Run multiple shell commands concurrently, capture their outputs, and handle possible errors.
Args:
commands (list[str]): A list of shell command strings to be executed concurrently.
Returns:
dict[... | import asyncio
async def run_command(command: str) -> dict[str, str]:
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
return {
"stdout": stdo... | import asyncio
from solution import run_commands
def test_run_commands_echo():
commands = ["echo 'Hello, World!'"]
result = asyncio.run(run_commands(commands))
assert result == {
"echo 'Hello, World!'": {
"stdout": "Hello, World!",
"stderr": ""
}
}
def test_run_... | [] | [
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 run_command(command):\n process = await asyncio.create_subprocess_shell(\n command,\n stdout=asyncio.subprocess.PIPE,\n ... | trial_gpt4o_1 | {
"original_instruction": "### Advanced Python Asyncio Subprocess Management\nIn this assessment, you will demonstrate your understanding of asyncio's subprocess management by implementing a function that runs multiple shell commands concurrently, captures their outputs, and handles possible errors.\n\n#### Task:\nWr... | 0.663418 | Docs: Python310_1011 | C | [
"run_command",
"run_commands"
] | 2 | [
[
"run_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | abe67853e3c32bc08074124cd4e9bb11aadabeb5 | f8110cb3b7035c3818245bceb424b84a653bab83 | |||
v1.0 | complete | Docs | Docs: Python310_1513_C | import cProfile
import functools
def factorial(n):
"""Calculate the factorial of a given number.
>>> factorial(5)
120
>>> factorial(0)
1
"""
if n == 0:
return 1
else:
return n * factorial(n-1)
def profile_function(func):
"""
Decorator to profile a function and p... | import cProfile
import functools
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def profile_function(func):
"""
Decorator to profile a function and print its execution time.
"""
@functools.wraps(func)
def wrapper_profile_function(*args, **kwargs):
... | from solution import factorial, factorial_optimized
def test_factorial_base_case():
assert factorial(0) == 1
assert factorial_optimized(0) == 1
def test_factorial_small_numbers():
assert factorial(5) == 120
assert factorial_optimized(5) == 120
def test_factorial_larger_numbers():
assert factorial... | [
{
"docstring": null,
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
},
{
"docstring": "Decorator to profile a function and print its execution time.",
"function_declaration": "def profile_function(func):",
"function_name": "profile_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nimport cProfile\n\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)\n\ndef profile_function(func):\n de... | trial_gpt4o_1 | {
"original_instruction": "### Debugging and Profiling with Python\n\n#### Background:\nYou are given a Python script that computes the factorial of a number, but it has a performance bottleneck. Your task is to identify the bottleneck and optimize the code for better performance using Python's profiling tools.\n\n##... | 0.575227 | Docs: Python310_1513 | C | [
"factorial",
"profile_function",
"main",
"factorial_optimized",
"main_optimized"
] | 5 | [
[
"main_optimized",
"factorial_optimized"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3c38ebd46af14c7c510e76a3250be197a8c0fdef | b8241f44b1979273f2efb448d9dc04a5ef4bd5d9 | |||
v1.0 | complete | Docs | Docs: Pytorch_1418_C | import os
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
def setup(rank, world_size, file_store_path):
os.environ['MASTER_ADDR'] = '127.0.0.1'
os.environ['MASTER_PORT'] = '29500'
dist.init_process_group(
backend='gloo',
init_method=f'file://{... | import os
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
import torch.multiprocessing as mp
def setup(rank, world_size, file_store_path):
os.environ['MASTER_ADDR'] = '127.0.0.1'
os.environ['MASTER_PORT'] = '29500'
dist.init_process_group(
backend='gl... | import pytest
import torch.multiprocessing as mp
from solution import run_distributed_training
def init_process(rank, world_size, file_store_path, epochs):
run_distributed_training(file_store_path, world_size, rank, epochs)
@pytest.mark.skip(reason="Requires multi-process setup and specific file store path")
def ... | [
{
"docstring": null,
"function_declaration": "def setup(rank, world_size, file_store_path):",
"function_name": "setup",
"parameter_list": "(rank, world_size, file_store_path)"
},
{
"docstring": null,
"function_declaration": "def cleanup():",
"function_name": "cleanup",
"parameter... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nclass SimpleNet(nn.Module):\n ... | trial_gpt4o_9 | {
"original_instruction": "#### Objective\nThe purpose of this task is to test the student's ability to set up, manage, and utilize PyTorch's `torch.distributed` package for distributed training. The student should demonstrate their understanding of initializing a process group, performing collective operations, and ... | 0.533341 | Docs: Pytorch_1418 | C | [
"setup",
"cleanup",
"run_distributed_training"
] | 3 | [
[
"run_distributed_training",
"cleanup"
],
[
"run_distributed_training",
"setup"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 42684055cb3104de7eff5d42260b92b435ef7599 | 66064133ccaef8163dfc8e2c0a99eb5a2d76e026 | |||
v1.0 | complete | Docs | Docs: Python310_1954_C | import asyncio
import logging
# Enable debug-level logging for asyncio
logging.basicConfig(level=logging.DEBUG)
async def fetch_data(i):
"""Simulate fetching data with a 1-second delay."""
await asyncio.sleep(1)
print(f"Data {i} fetched")
return f"data_{i}"
async def process_data(data):
"""Take t... | import asyncio
import logging
# Enable debug-level logging for asyncio
logging.basicConfig(level=logging.DEBUG)
async def fetch_data(i):
await asyncio.sleep(1)
print(f"Data {i} fetched")
return f"data_{i}"
async def process_data(data):
await asyncio.sleep(2)
print(f"{data} processed")
return ... | import asyncio
import logging
from unittest.mock import patch, call
# Assuming the solution is in a module named solution
from solution import fetch_data, process_data, save_data, handle_task, main
def test_fetch_data():
async def run_test():
result = await fetch_data(1)
assert result == "data_1"
... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport logging\n\n# Enable debug-level logging\nlogging.basicConfig(level=logging.DEBUG)\n\nasync def fetch_data(i):\n await asyncio.sleep(1)\n pr... | trial_gpt4o_1 | {
"original_instruction": "**Advanced asyncio Debugging and Concurrency Challenge**\n\n### Objective\n\nYour task is to demonstrate a detailed understanding of the `asyncio` package by creating a program that handles several asynchronous tasks. You will use `asyncio` debug mode to catch common issues and ensure the p... | 0.577823 | Docs: Python310_1954 | C | [
"fetch_data",
"process_data",
"save_data",
"handle_task",
"main"
] | 5 | [
[
"handle_task",
"fetch_data"
],
[
"handle_task",
"process_data"
],
[
"handle_task",
"save_data"
]
] | 3 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | b98c61791a3259f3c619a1a30dfe47f94373b500 | db2152392eff4e5d92dadceac548b9598aa57675 | |||
v1.0 | complete | Docs | Docs: Pytorch_1766_C | import torch
from torch.autograd import gradcheck
def f_real(x):
""" Calculate the function f(x) = x^3 + 5x^2 + 2x + 1 for a real-valued input tensor.
>>> f_real(torch.tensor([1.0]))
tensor([9.])
"""
pass
def f_complex(z):
""" Calculate the function f(z) = z^3 + 5z^2 + 2z + 1 for a complex-val... | import torch
from torch.autograd import Function, gradcheck
# Implement the real-valued function
def f_real(x):
return x**3 + 5*x**2 + 2*x + 1
# Implement the complex-valued function
def f_complex(z):
return z**3 + 5*z**2 + 2*z + 1
# Gradient check function
def verify_gradients():
x_real = torch.randn(1,... | def test_gradcheck_real():
# Check if the gradients for the real-valued function are correct
x_real = torch.randn(1, dtype=torch.double, requires_grad=True)
result_real = gradcheck(f_real, (x_real,), eps=1e-6, atol=1e-4)
assert result_real, "Gradient check failed for the real-valued function"
def t... | [
{
"docstring": null,
"function_declaration": "def f_real(x):",
"function_name": "f_real",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def f_complex(z):",
"function_name": "f_complex",
"parameter_list": "(z)"
},
{
"docstring": null,
"functi... | [
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 torch\nfrom torch.autograd import Function, gradcheck\n\n# Implement the real-valued function\ndef f_real(x):\n return x**3 + 5*x**2 + 2*x + 1\n\n# Implement ... | trial_gpt4o_0 | {
"original_instruction": "<|Analysis Begin|>\n\nUpon reading the provided PyTorch documentation on \"Gradcheck mechanics\", it's clear that it delves into the internals and intricacies of the `gradcheck` and `gradgradcheck` functionalities in PyTorch. This includes both real-to-real and complex-to-real functions, an... | 0.48226 | Docs: Pytorch_1766 | C | [
"f_real",
"f_complex",
"verify_gradients"
] | 3 | [
[
"verify_gradients",
"f_complex"
],
[
"verify_gradients",
"f_real"
]
] | 2 | [] | false | [] | false | pytest | false | [
"torch"
] | false | 089c56e1d35c16cf647647c7eafe52c6940ba2aa | e7f1d62a0d2ed111c95226e03da744a844e9594e | |||
v1.0 | complete | Docs | Docs: Python310_1601_C | import aifc
def open_aiff(file_path: str):
""" Opens an AIFF file and returns the file object.
"""
return aifc.open(file_path, 'rb')
def get_audio_params(aiff_file):
""" Retrieves and prints the audio parameters from the AIFF file object.
Returns a tuple of the parameters including number of chann... | import aifc
import struct
def open_aiff(file_path):
"""
Opens an AIFF file and returns the file object.
"""
return aifc.open(file_path, 'rb')
def get_audio_params(aiff_file):
"""
Retrieves and prints the audio parameters from the AIFF file object.
Returns a tuple of the parameters.
"""... | import pytest
import struct
from solution import analyze_aiff, open_aiff, get_audio_params, read_frames, compute_average_amplitude
def test_get_audio_params(monkeypatch):
class MockAIFFFile:
def getnchannels(self): return 2
def getsampwidth(self): return 2
def getframerate(self): return 441... | [
{
"docstring": "Opens an AIFF file and returns the file object.",
"function_declaration": "def open_aiff(file_path):",
"function_name": "open_aiff",
"parameter_list": "(file_path)"
},
{
"docstring": "Retrieves and prints the audio parameters from the AIFF file object.\nReturns a tuple of the... | [
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 aifc\nimport struct\n\ndef open_aiff(file_path):\n try:\n return aifc.open(file_path, 'rb')\n except Exception as e:\n raise IOError(f\"Error... | trial_gpt4o_5 | {
"original_instruction": "**Python Coding Assessment**\n\n### Question: AIFF File Manipulation and Analysis\n\nYou are provided with a set of audio files in AIFF format, and your task is to implement a function that extracts specific audio data and performs simple audio analysis. Follow the steps below:\n\n1. **Open... | 0.593909 | Docs: Python310_1601 | C | [
"open_aiff",
"get_audio_params",
"read_frames",
"compute_average_amplitude",
"analyze_aiff"
] | 5 | [
[
"analyze_aiff",
"compute_average_amplitude"
],
[
"analyze_aiff",
"get_audio_params"
],
[
"analyze_aiff",
"open_aiff"
],
[
"analyze_aiff",
"read_frames"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | d5fab8795682c439ee7dfd2af7049b8aacf2a2d6 | 193f387edba2cde21bf8f78684422329cb5adce1 | |||
v1.0 | complete | Docs | Docs: Python310_1806_C | from xmlrpc.server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
import math
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
def add(x, y):
""" Returns the sum of x and y. """
pass
def subtract(x, y):
""" Returns the result of x minus y. """
pass
def multiply(x, ... | from xmlrpc.server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
import math
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return... | import xmlrpc.client
import pytest
import math
@pytest.fixture(scope="module")
def client():
return xmlrpc.client.ServerProxy('http://localhost:9000')
def test_add(client):
assert client.add(5, 3) == 8
assert client.add(-2, 2) == 0
def test_subtract(client):
assert client.subtract(10, 5) == 5
ass... | [] | [
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": "from xmlrpc.server import SimpleXMLRPCServer\nimport math\n\ndef add(x, y):\n return x + y\n\ndef subtract(x, y):\n return x - y\n\ndef multiply(x, y):\n retur... | trial_gpt4o_5 | {
"original_instruction": "**Objective:** Demonstrate your understanding of the `xmlrpc.server` module by implementing a simple XML-RPC server that provides calculator functionalities.\n\n**Task:**\n\n1. **Create a SimpleXMLRPCServer** running on `localhost` and port `9000`.\n2. **Register the following functions**:\... | 0.393088 | Docs: Python310_1806 | C | [
"add",
"subtract",
"multiply",
"divide",
"run_server"
] | 5 | [
[
"run_server",
"add"
],
[
"run_server",
"divide"
],
[
"run_server",
"multiply"
],
[
"run_server",
"subtract"
]
] | 4 | [] | false | [
"RequestHandler",
"AdvancedCalculator"
] | true | pytest | false | [] | true | 6769b5535822cb1c159f436bfce5bc8e640c9b24 | 6802752c12c5db27fac6e5bcf1b398a768896b86 | |||
v1.0 | complete | Docs | Docs: Pytorch_1809_C | import os
import torch.distributed.rpc as rpc
def init_rpc_framework(master_addr='localhost', master_port='29500', rank=0, world_size=3):
"""Initializes the RPC framework."""
os.environ['MASTER_ADDR'] = master_addr
os.environ['MASTER_PORT'] = master_port
rpc.init_rpc(f"worker{rank}", rank=rank, world_s... | import os
import torch.distributed.rpc as rpc
def init_rpc_framework(master_addr='localhost', master_port='29500', rank=0, world_size=3):
os.environ['MASTER_ADDR'] = master_addr
os.environ['MASTER_PORT'] = master_port
rpc.init_rpc(f"worker{rank}", rank=rank, world_size=world_size)
def remote_square(x):
... | import os
import pytest
from subprocess import Popen, PIPE
import time
def spawn_worker(rank, script):
env = os.environ.copy()
env['RANK'] = str(rank)
return Popen(['python', script], env=env)
def test_rpc_framework():
workers = []
for rank in range(3):
worker = spawn_worker(rank, 'solutio... | [
{
"docstring": null,
"function_declaration": "def init_rpc_framework(master_addr='localhost', master_port='29500', rank=0, world_size=3):",
"function_name": "init_rpc_framework",
"parameter_list": "(master_addr='localhost', master_port='29500', rank=0, world_size=3)"
},
{
"docstring": null,
... | [
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 os\nimport torch.distributed.rpc as rpc\n\ndef init_rpc_framework(rank, master_addr='localhost', master_port='29500', world_size=3):\n os.environ['MASTER_ADDR... | trial_gpt4o_1 | {
"original_instruction": "### Distributed RPC Framework Coding Assessment\n\n**Objective:**\nYou are tasked with designing a simple distributed system using PyTorch's Distributed RPC Framework. Your goal is to set up an environment with three workers where one worker acts as a master and the other two workers perfor... | 0.509563 | Docs: Pytorch_1809 | C | [
"init_rpc_framework",
"remote_square",
"distribute_tasks_and_collect_results",
"shutdown_rpc_framework"
] | 4 | [
[
"distribute_tasks_and_collect_results",
"remote_square"
]
] | 1 | [] | false | [] | false | pytest | false | [
"torch"
] | false | f4dd9cf2a9f95bc317e50763076876e63a826b4b | 6baa8f62ff09c9f9904401de4fa2f6b062f9543d | |||
v1.0 | complete | Docs | Docs: Python310_2064_C | import asyncio
import aiohttp
import platform
async def fetch_webpage_urls(urls: list) -> dict:
""" Fetch the content of each URL concurrently using asyncio and return a dictionary.
Args:
urls (list): A list of strings where each string is a URL.
Returns:
dict: A dictionary where the key ... | import asyncio
import aiohttp
import platform
async def fetch_url(session, url):
try:
async with session.get(url) as response:
return await response.text()
except:
return None
async def fetch_webpage_urls(urls: list) -> dict:
async with aiohttp.ClientSession() as session:
... | import asyncio
from solution import fetch_webpage_urls
def test_fetch_webpage_urls():
urls = [
'http://example.com',
'http://example.org',
'http://example.net'
]
loop = asyncio.get_event_loop()
result = loop.run_until_complete(fetch_webpage_urls(urls))
assert 'http://example... | [] | [
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_content(url):\n try:\n async with aiohttp.ClientSession() as session:\n async with session.get(ur... | trial_gpt4o_2 | {
"original_instruction": "#### Background\nThe `asyncio` module in Python provides a framework for writing single-threaded, concurrent code using the `async/await` syntax. This module provides a way to work with event loops, which handle the execution of asynchronous tasks and IO operations.\n\n#### Task\nImplement ... | 0.639174 | Docs: Python310_2064 | C | [
"fetch_url",
"fetch_webpage_urls",
"main"
] | 3 | [
[
"fetch_webpage_urls",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 497917a7376fc37d94f69f19deb7061874e44b48 | 1cea8347a92884cee67452badfc838c2642a8dea | |||
v1.0 | complete | Docs | Docs: Python310_1142_C | import os
import zipfile
def zip_directory_structure(input_directory: str, output_zipfile: str, compression_method: str) -> None:
"""Creates a ZIP file from the specified directory using the specified compression method.
Args:
input_directory (str): The path to the directory that needs to be zippe... | import os
import zipfile
import filecmp
def zip_directory_structure(input_directory: str, output_zipfile: str, compression_method: str) -> None:
compression_methods = {
"ZIP_STORED": zipfile.ZIP_STORED,
"ZIP_DEFLATED": zipfile.ZIP_DEFLATED,
"ZIP_BZIP2": zipfile.ZIP_BZIP2,
"ZIP_LZMA"... | import os
import shutil
import pytest
from solution import zip_directory_structure, extract_and_verify_zip
def setup_test_directory():
os.makedirs("test_directory/subdir", exist_ok=True)
with open("test_directory/file1.txt", "w") as f:
f.write("This is a test file.")
with open("test_directory/subdi... | [
{
"docstring": null,
"function_declaration": "def zip_directory_structure(input_directory, output_zipfile, compression_method):",
"function_name": "zip_directory_structure",
"parameter_list": "(input_directory, output_zipfile, compression_method)"
},
{
"docstring": null,
"function_declar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport zipfile\nimport filecmp\n\ndef zip_directory_structure(input_directory: str, output_zipfile: str, compression_method: str) -> None:\n compression_m... | trial_gpt4o_0 | {
"original_instruction": "**ZIP File Operations**\n\n**Objective**: To assess your understanding and ability to use the `zipfile` module in Python for handling ZIP file operations.\n\n**Problem Statement**:\n\nYou are asked to write a Python function `zip_directory_structure` that takes the following inputs:\n\n1. `... | 0.810127 | Docs: Python310_1142 | C | [
"zip_directory_structure",
"extract_and_verify_zip",
"compare_directories"
] | 3 | [
[
"extract_and_verify_zip",
"compare_directories"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9665fbb1a71ff3ab9df50d7a3d5be92a8ef49b34 | 7fc344655f2bab97e9e5f5dbdad3a8f7a00d5f1d | |||
v1.0 | complete | Docs | Docs: Python310_703_C | import csv
from collections import Counter
def process_books_file(input_file: str, output_file: str) -> None:
"""
Processes a CSV file containing book information and generates a summary text file.
:param input_file: path to the input CSV file
:param output_file: path to the output summary text fi... | import csv
from collections import Counter
def process_books_file(input_file: str, output_file: str) -> None:
"""
Processes a CSV file containing book information and generates a summary text file.
"""
books = []
genres = Counter()
authors = set()
valid_isbns = []
with open(input_f... | import os
from solution import process_books_file
def setup_function():
# Write a temporary CSV file for testing
with open('test_data.csv', 'w') as f:
f.write(
"title,author,isbn,year,genre\n"
"The Great Gatsby,F. Scott Fitzgerald,978074327356,1925,Fiction\n"
"To Kil... | [
{
"docstring": "Processes a CSV file containing book information and generates a summary text file.",
"function_declaration": "def process_books_file(input_file, output_file):",
"function_name": "process_books_file",
"parameter_list": "(input_file, output_file)"
},
{
"docstring": "Checks if ... | [
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 csv\nfrom collections import Counter\n\ndef is_valid_isbn(isbn: str) -> bool:\n if len(isbn) != 10 or not isbn.isdigit():\n return False\n \n tot... | trial_gpt4o_8 | {
"original_instruction": "**Question: Comprehensive Data Processing and File Manipulation**\n\n**Background:**\n\nYou have been provided with a `.csv` file named `data.csv` which contains information about a collection of books. Each row in the file contains details about one book: its title, author, ISBN number, pu... | 0.572662 | Docs: Python310_703 | C | [
"process_books_file",
"is_valid_isbn"
] | 2 | [
[
"process_books_file",
"is_valid_isbn"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5b380ffb5cb504eb9a07868083bd4989bc7c93b3 | 3ff47a01c352efa90def2e28453c8ba230694b97 | |||
v1.0 | complete | Docs | Docs: Python310_1577_C | import cProfile
import timeit
def my_function(data):
""" Perfrom computations on a list of data.
Each item is processed by squaring it 1000 times and summing the results."""
result = []
for item in data:
processed_item = process(item)
result.append(processed_item)
return result
def... | import cProfile
import timeit
def my_function(data):
result = []
for item in data:
processed_item = process(item)
result.append(processed_item)
return result
def process(item):
sum = 0
for i in range(1000):
sum += item ** 2
return sum
# Optimized process function
def o... | from solution import my_function, optimized_my_function
def test_consistency():
data = [1, 2, 3, 4, 5]
assert my_function(data) == optimized_my_function(data)
def test_empty_input():
data = []
assert my_function(data) == optimized_my_function(data)
def test_single_element():
data = [3]
assert... | [
{
"docstring": null,
"function_declaration": "def my_function(data):",
"function_name": "my_function",
"parameter_list": "(data)"
},
{
"docstring": null,
"function_declaration": "def process(item):",
"function_name": "process",
"parameter_list": "(item)"
},
{
"docstring":... | [
0,
0,
0,
1,
1,
0,
0,
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 cProfile\nimport timeit\nfrom functools import lru_cache\n\ndef my_function(data):\n result = []\n for item in data:\n processed_item = process(item... | trial_gpt4o_9 | {
"original_instruction": "Profiling and Optimizing Python Code\n\n**Objective**: Demonstrate your understanding of Python's profiling and timing tools by using the `cProfile` and `timeit` modules to analyze and optimize the performance of a given Python function.\n\n**Instructions**:\n\n1. **Function Implementation*... | 0.558414 | Docs: Python310_1577 | C | [
"my_function",
"process",
"optimized_process",
"optimized_my_function",
"profile_my_function",
"profile_optimized_my_function",
"time_my_function",
"time_optimized_my_function"
] | 8 | [
[
"my_function",
"process"
],
[
"optimized_my_function",
"optimized_process"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ff2c58230c938525644d422a0774f454bd846eb6 | 5a7de70cf17e3f6a485f0b89585bd4000bd39e4f | |||
v1.0 | complete | Docs | Docs: Python310_1424_C | import ossaudiodev
def audio_manager(operation: str, format: int, channels: int, rate: int, duration: int = 10) -> None:
""" Manage audio recording and playback or live pass-through based on the operation specified.
operation: A string, either "record_playback" or "pass_through".
format: An integer, specif... | import ossaudiodev
import sys
def audio_manager(operation: str, format: int, channels: int, rate: int, duration: int = 10) -> None:
try:
if operation == "record_playback":
data = record_audio(format, channels, rate, duration)
play_audio(data, format, channels, rate)
elif ope... | def test_audio_manager_record_playback():
try:
audio_manager("record_playback", ossaudiodev.AFMT_S16_LE, 2, 44100, 5)
except Exception as e:
assert False, f"Exception raised: {e}"
def test_audio_manager_pass_through():
try:
audio_manager("pass_through", ossaudiodev.AFMT_S16_LE, 2, 4... | [
{
"docstring": null,
"function_declaration": "def audio_manager(operation, format, channels, rate, duration=10):",
"function_name": "audio_manager",
"parameter_list": "(operation, format, channels, rate, duration=10)"
},
{
"docstring": null,
"function_declaration": "def record_audio(form... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import ossaudiodev\nimport sys\nimport time\n\ndef record_audio(format: int, channels: int, rate: int, duration: int) -> bytes:\n try:\n dsp_in = ossaudiodev.... | trial_gpt4o_9 | {
"original_instruction": "**Problem Statement:**\n\nCreate a Python program using the `ossaudiodev` module to perform one of the following operations based on user input:\n1. **Record and playback**: Record audio from the default input device, save it to a file, and then play back the recorded audio from the file.\n... | 0.483779 | Docs: Python310_1424 | C | [
"audio_manager",
"record_audio",
"play_audio",
"pass_through_audio"
] | 4 | [
[
"audio_manager",
"pass_through_audio"
],
[
"audio_manager",
"play_audio"
],
[
"audio_manager",
"record_audio"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 851113bd7b9c8fb88c449038f118fc4c30acbb2d | b51605cd89304fbd5aa62e7ac22ba87da0f9a2cb | |||
v1.0 | complete | Docs | Docs: Pytorch_2289_C | import torch
from torch.autograd import Function
class CustomMulAddFunction(Function):
@staticmethod
def forward(ctx, x, y):
"""Forward pass: calculate x * y + y"""
ctx.save_for_backward(x, y)
raise NotImplementedError
@staticmethod
def backward(ctx, grad_output):
"""Ba... | import torch
from torch.autograd import Function
class CustomMulAddFunction(Function):
@staticmethod
def forward(ctx, x, y):
"""Forward pass: calculate x * y + y"""
ctx.save_for_backward(x, y)
return x * y + y
@staticmethod
def backward(ctx, grad_output):
"""Backward pa... | import torch
from solution import custom_mul_add, test_custom_operation_with_grad_check
def test_forward_pass():
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = torch.tensor([0.5, 2.5, 3.5], requires_grad=True)
expected_output = x * y + y
output = custom_mul_add(x, y)
assert torch.allclos... | [] | [
1,
0,
0,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.autograd.function import Function\n\n# Define custom operation using autograd Function\nclass CustomMulAdd(Function):\... | trial_gpt4o_8 | {
"original_instruction": "### Custom Operator with Gradient Check in PyTorch\n\n#### Objective:\nYou are required to create a custom operation using PyTorch's `torch.library` module. This operation will perform element-wise multiplication and addition on two tensors. Your task is to:\n1. Define and register the cust... | 0.504417 | Docs: Pytorch_2289 | C | [
"custom_mul_add",
"test_custom_operation_with_grad_check"
] | 2 | [
[
"test_custom_operation_with_grad_check",
"custom_mul_add"
]
] | 1 | [] | false | [
"CustomMulAddFunction"
] | true | pytest | true | [
"torch"
] | false | 8cc31584269daef5a47c05e71dc25ec4a559c3e5 | 03b6f3bad773852ba3a31705af738dc357da0e80 | |||
v1.0 | complete | Docs | Docs: Python310_1299_C | import os
import concurrent.futures
def parallel_sum(directory: str) -> dict:
""" Processes all text files in the given directory in parallel to compute the sum of integers in each file.
Args:
directory (str): The path to the directory containing the text files.
Returns:
dict: A dicti... | import os
import concurrent.futures
def sum_integers_in_file(file_path):
"""
Sums the integers in a given file.
"""
total = 0
try:
with open(file_path, 'r') as file:
for line in file:
total += int(line.strip())
except Exception as e:
print(f"Error pro... | import os
import tempfile
from solution import parallel_sum
def create_test_files(directory, files_content):
for file_name, content in files_content.items():
with open(os.path.join(directory, file_name), 'w') as f:
f.write(content)
def test_parallel_sum_basic():
with tempfile.TemporaryDire... | [
{
"docstring": "Sums the integers in a given file.",
"function_declaration": "def sum_integers_in_file(file_path):",
"function_name": "sum_integers_in_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Processes all text files in the given directory in parallel to compute the sum of i... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef process_file(filepath):\n try:\n with open(filepath, 'r') as file:\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question: Parallel File Processing Using `concurrent.futures`\n\nYou are given a directory containing multiple text files. Each text file contains a list of integers, one integer per line. You need to write a Python function that processes these files in parallel to compute the sum of i... | 0.567434 | Docs: Python310_1299 | C | [
"sum_integers_in_file",
"parallel_sum"
] | 2 | [
[
"parallel_sum",
"sum_integers_in_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a9f6e68e022f9884c1bb5cc502f0b0b9c89bd66b | fd2c0b201f3985b5574849d0c80ab2716ec20fc5 | |||
v1.0 | complete | Docs | Docs: Python310_1706_C | import signal
import time
def computation():
for i in range(10):
print(f'Computing step {i}...')
time.sleep(1)
def handler(signum, frame):
""" Handle signals to gracefully interrupt the computation. """
raise OSError("Signal received")
def simulation(timeout: int) -> None:
"""
Sim... | import signal
import time
def computation():
for i in range(10):
print(f'Computing step {i}...')
time.sleep(1)
def handler(signum, frame):
if signum == signal.SIGINT:
print("Computation interrupted by user!")
elif signum == signal.SIGALRM:
print("Computation timed out!")
... | import pytest
import signal
import os
from solution import simulation
def test_computation_finished_successfully(capfd):
pid = os.fork()
if pid == 0:
simulation(15)
os._exit(0)
else:
os.waitpid(pid, 0)
out, err = capfd.readouterr()
assert "Computation finished succes... | [
{
"docstring": null,
"function_declaration": "def computation():",
"function_name": "computation",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def handler(signum, frame):",
"function_name": "handler",
"parameter_list": "(signum, frame)"
},
{
"d... | [
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 signal\nimport time\n\ndef computation():\n for i in range(10):\n print(f'Computing step {i}...')\n time.sleep(1)\n\ndef handler(signum, frame):... | trial_gpt4o_0 | {
"original_instruction": "## Signal Handling and Inter-process Communication in Python\n\n### Objective\nYour task is to create a simulation where you need to manage signal handling to gracefully handle interruptions and timed events. This will demonstrate your understanding of the `signal` module and appropriate ha... | 0.598211 | Docs: Python310_1706 | C | [
"computation",
"handler",
"simulation"
] | 3 | [
[
"simulation",
"computation"
],
[
"simulation",
"handler"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b4f5c949b9bb685cca6dd8826114e665f4c00dc5 | efe863b036850c533d9f6c5bf0e86f62831ae565 | |||
v1.0 | complete | Docs | Docs: Python310_2277_C | import _thread
import time
def multi_threaded_sum():
""" Perform multi-threaded increment of a global counter with proper lock management.
Ensures that the counter is incremented by 1, 100,000 times each by two threads.
Returns:
int: The final value of the counter after both threads have completed... | import _thread
import time
# Initialize a global counter and a lock
counter = 0
lock = _thread.allocate_lock()
def increment_counter():
global counter
for _ in range(100000):
with lock:
counter += 1
def multi_threaded_sum():
global counter
counter = 0 # Reset counter for each fun... | from solution import multi_threaded_sum
def test_multi_threaded_sum_correctness():
result = multi_threaded_sum()
assert result == 200000, f"Expected 200000 but got {result}"
def test_multi_threaded_sum_multiple_runs():
for _ in range(10): # Run the test multiple times to ensure consistency
result... | [
{
"docstring": null,
"function_declaration": "def increment_counter():",
"function_name": "increment_counter",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def multi_threaded_sum():",
"function_name": "multi_threaded_sum",
"parameter_list": "()"
}
] | [
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 _thread\nimport time\n\n# Global counter\ncounter = 0\n\n# Lock for thread safety\ncounter_lock = _thread.allocate_lock()\n\ndef increment_counter():\n global... | trial_gpt4o_2 | {
"original_instruction": "### Python Threading and Lock Management\n\nYou are required to implement a function `multi_threaded_sum` that performs the following operations using the low-level `_thread` module to demonstrate your understanding of threading and lock management:\n\n1. Create two threads that both attemp... | 0.563639 | Docs: Python310_2277 | C | [
"increment_counter",
"multi_threaded_sum"
] | 2 | [
[
"multi_threaded_sum",
"increment_counter"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 62557a37bd41c26a298234233bc1af8451be9683 | f118e0d7204adcff988874ffbbc8c3a141f2ca37 | |||
v1.0 | complete | Docs | Docs: Pandas_1024_C | import pandas as pd
def get_date_range_data(df, start_date, end_date):
"""
Returns rows between start_date and end_date inclusive.
>>> data = {'date': pd.to_datetime(['2021-01-01', '2021-01-02', '2021-01-03']), 'country': ['A', 'A', 'A'], 'new_cases': [1, 2, 3], 'new_deaths': [0, 1, 1]}
>>> df = p... | import pandas as pd
def get_date_range_data(df, start_date, end_date):
"""
Returns rows between start_date and end_date inclusive.
"""
mask = (df['date'] >= start_date) & (df['date'] <= end_date)
return df.loc[mask]
def get_new_cases_by_country(df):
"""
Returns the total new cases for each... | import pandas as pd
import pytest
from solution import get_date_range_data, get_new_cases_by_country, get_most_affected_country, pivot_countries_data, add_weekly_data_column
@pytest.fixture
def sample_data():
data = {
'date': pd.to_datetime(['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-01', '2021-01-... | [
{
"docstring": "Returns rows between start_date and end_date inclusive.",
"function_declaration": "def get_date_range_data(df, start_date, end_date):",
"function_name": "get_date_range_data",
"parameter_list": "(df, start_date, end_date)"
},
{
"docstring": "Returns the total new cases for ea... | [
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 pandas as pd\n\ndef get_date_range_data(df, start_date, end_date):\n \"\"\"\n Returns the rows of the DataFrame between the start_date and end_date (inclus... | trial_gpt4o_2 | {
"original_instruction": "**COVID-19 Data Analysis with pandas**\n\nYou are given a CSV file `covid19_data.csv` containing COVID-19 data with the following columns:\n- `date`: The date of the record in `YYYY-MM-DD` format.\n- `country`: The country for which the record applies.\n- `new_cases`: The number of new COVI... | 0.606349 | Docs: Pandas_1024 | C | [
"get_date_range_data",
"get_new_cases_by_country",
"get_most_affected_country",
"pivot_countries_data",
"add_weekly_data_column"
] | 5 | [
[
"get_most_affected_country",
"get_new_cases_by_country"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | 6a1d20c52f27b1c07be29edae8b53225995c9754 | 2d417b870065a19042d46936edbd5aa8f6776cab | |||
v1.0 | complete | Docs | Docs: Python310_1541_C | import codecs
def register_reverse_codec():
""" Register the custom reverse codec and error handler. """
pass
class ReverseIncrementalEncoder(codecs.IncrementalEncoder):
""" Incremental encoder that reverses the string. """
pass
class ReverseIncrementalDecoder(codecs.IncrementalDecoder):
""" Incr... | import codecs
class ReverseIncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return input[::-1]
class ReverseIncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return input[::-1]
def question_mark_replace(exc):
if isinst... | import codecs
from solution import register_reverse_codec
def test_encode():
register_reverse_codec()
input_text = "Hello, World!"
encoded_text = codecs.encode(input_text, 'reverse_codec')
assert encoded_text == "!dlroW ,olleH"
def test_decode():
register_reverse_codec()
encoded_text = "!dlroW... | [] | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import codecs\n\nclass ReverseCodec(codecs.Codec):\n def encode(self, input, errors='strict'):\n return input[::-1].encode('utf-8', errors), len(input)\n\n ... | trial_gpt4o_6 | {
"original_instruction": "### Custom Codec Handling and Incremental Encoding/Decoding Assessment\n\nYou are tasked with creating a custom encoding-decoding system that handles a specific use case. You need to define a custom codec with a special incremental encoding and decoding scheme and custom error handling.\n\n... | 0.572555 | Docs: Python310_1541 | C | [
"question_mark_replace",
"reverse_codec",
"register_reverse_codec"
] | 3 | [
[
"register_reverse_codec",
"question_mark_replace"
],
[
"register_reverse_codec",
"reverse_codec"
]
] | 2 | [] | false | [
"ReverseIncrementalEncoder",
"ReverseIncrementalDecoder"
] | true | pytest | true | [] | true | 94acd496d7c1a62dbab2823c39455849922d9945 | b2316b537a4a09df21e7e339e20d565b4941fbc5 | |||
v1.0 | complete | Docs | Docs: Python310_2565_C | import atexit
def cleanup_a():
""" Prints a message indicating that cleanup_a is being executed """
print("Executing cleanup_a")
def cleanup_b():
""" Prints a message indicating that cleanup_b is being executed """
print("Executing cleanup_b")
def cleanup_c():
""" Prints a message indicating that... | import atexit
def cleanup_a():
print("Executing cleanup_a")
def cleanup_b():
print("Executing cleanup_b")
def cleanup_c():
print("Executing cleanup_c")
def cleanup_with_exception():
raise Exception("Exception in cleanup_with_exception")
# Wrapper function for cleanup_with_exception to handle except... | import subprocess
def test_cleanup_functions_order():
# Run the script in a subprocess to capture the output
result = subprocess.run(['python3', 'solution.py'], capture_output=True, text=True)
output = result.stdout.splitlines()
# Check if the correct output is produced in reverse order of registratio... | [
{
"docstring": null,
"function_declaration": "def cleanup_a():",
"function_name": "cleanup_a",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def cleanup_b():",
"function_name": "cleanup_b",
"parameter_list": "()"
},
{
"docstring": null,
"func... | [
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 atexit\n\ndef cleanup_a():\n print(\"Executing cleanup_a\")\n\ndef cleanup_b():\n print(\"Executing cleanup_b\")\n\ndef cleanup_c():\n print(\"Executing... | trial_gpt4o_2 | {
"original_instruction": "### Coding Assessment: Exit Handlers\n\n#### Objective:\nWrite a Python program that demonstrates the use of the `atexit` module to register multiple cleanup functions, handle their execution order, and manage exceptions that occur during the execution of these cleanup functions.\n\n#### Sp... | 0.490921 | Docs: Python310_2565 | C | [
"cleanup_a",
"cleanup_b",
"cleanup_c",
"cleanup_with_exception",
"cleanup_with_exception_handler"
] | 5 | [
[
"cleanup_with_exception_handler",
"cleanup_with_exception"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | b88d39d89e3784cd9fa8c397d1db0c2e1e37173d | c468ca8faa2ffea6154579778582bf108caf73c0 | |||
v1.0 | complete | Docs | Docs: Python310_2513_C | import asyncio
async def network_server(host: str, port: int):
"""A coroutine function to handle network connections on the specified host and port.
Args:
host (str): The hostname or IP address to bind the server.
port (int): The port to bind the server.
"""
# Implementation here
... | import asyncio
async def network_server(host, port):
"""
Coroutine function to handle network connections.
"""
server = await asyncio.start_server(handle_client, host, port)
async with server:
await server.serve_forever()
async def handle_client(reader, writer):
"""
Handle client c... | import asyncio
import pytest
from asyncio import StreamReader, StreamWriter
import socket
from solution import network_server, schedule_tasks
@pytest.fixture
def event_loop():
"""
Create and provide a new event loop for each test function.
"""
loop = asyncio.new_event_loop()
yield loop
loop.cl... | [
{
"docstring": null,
"function_declaration": "def task_callback(msg):",
"function_name": "task_callback",
"parameter_list": "(msg)"
}
] | [
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 network_server(host, port):\n \"\"\"\n Coroutine function to handle network connections.\n \"\"\"\n server = await asyncio.start... | trial_gpt4o_0 | {
"original_instruction": "You are tasked with designing an asynchronous event-driven application using Python's `asyncio` library. The application should perform the following operations:\n\n1. Schedule and run multiple asynchronous tasks.\n2. Wait for and handle network connections.\n3. Use low-level event loop ope... | 0.59854 | Docs: Python310_2513 | C | [
"network_server",
"handle_client",
"schedule_tasks",
"main"
] | 4 | [
[
"network_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7c91a4589cb6053fe08308fef2cc37bdb3eba76a | 32c7228e9092d2709972ebe3898a451876dd82d8 | |||
v1.0 | complete | Docs | Docs: Python310_2780_C | import asyncio
async def start_http_server(host: str, port: int):
"""
Starts an HTTP server that listens on the specified host and port.
Parameters:
- host: A string representing the IP address to listen to.
- port: An integer representing the port number to bind to.
The server should... | import asyncio
async def handle_client(reader, writer):
"""
Handles an HTTP request from a client.
"""
data = await reader.read(1024)
message = data.decode()
addr = writer.get_extra_info('peername')
headers = message.split('\r\n')
request_line = headers[0].split(' ')
if len(re... | import asyncio
import socket
import pytest
from solution import start_http_server
@pytest.fixture(scope='module')
def event_loop():
loop = asyncio.new_event_loop()
yield loop
loop.close()
@pytest.fixture(scope='module')
async def http_server(event_loop):
server_task = event_loop.create_task(start_h... | [] | [
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 handle_client(reader, writer):\n data = await reader.read(1024)\n message = data.decode()\n addr = writer.get_extra_info('peername'... | trial_gpt4o_1 | {
"original_instruction": "### Advanced Python Networking with `asyncio` Streams\n\n**Problem Statement:**\n\nYou are tasked with creating a simple HTTP server using the asyncio streams API. The server should be capable of handling multiple client requests concurrently and responding with a basic HTML response. Your ... | 0.624526 | Docs: Python310_2780 | C | [
"handle_client",
"start_http_server"
] | 2 | [
[
"start_http_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 42efd7864d4f23e454596820424f8c8f7b3c3d31 | b559b41135dacc5b9ff0af3748e55902cbd5ccc8 | |||
v1.0 | complete | Docs | Docs: Pytorch_782_C | import subprocess
from pathlib import Path
def run_command(command):
"""Run a shell command and return its output."""
result = subprocess.run(command, shell=True, capture_output=True, text=True)
return result.output
def profile_model(script_name):
"""Profile the given model using TorchInductor and ret... | import subprocess
import re
from pathlib import Path
def run_command(command):
result = subprocess.run(command, shell=True, capture_output=True, text=True)
return result.stdout
def profile_model(script_name):
command = f'TORCHINDUCTOR_UNIQUE_KERNEL_NAMES=1 TORCHINDUCTOR_BENCHMARK_KERNEL=1 python {script_n... | from solution import extract_forward_graph_path, extract_time_consuming_kernel, analyze_performance
def test_extract_forward_graph_path():
profile_output = "Some logs... Forward graph module saved at: fwd.py ... More logs"
assert extract_forward_graph_path(profile_output) == "fwd.py"
def test_extract_time_con... | [
{
"docstring": null,
"function_declaration": "def run_command(command):",
"function_name": "run_command",
"parameter_list": "(command)"
},
{
"docstring": null,
"function_declaration": "def profile_model(script_name):",
"function_name": "profile_model",
"parameter_list": "(script_... | [
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 subprocess\nimport re\n\ndef profile_model():\n command = \"TORCHINDUCTOR_UNIQUE_KERNEL_NAMES=1 TORCHINDUCTOR_BENCHMARK_KERNEL=1 python -u mixnet_l.py --backe... | trial_gpt4o_1 | {
"original_instruction": "### PyTorch Coding Challenge: GPU Profiling with TorchInductor\n\n#### Objective:\nDemonstrate your understanding of PyTorch's TorchInductor GPU profiling by analyzing the performance of a given model. The task will involve breaking down model execution times into individual kernel times, a... | 0.53053 | Docs: Pytorch_782 | C | [
"run_command",
"profile_model",
"extract_forward_graph_path",
"benchmark_forward_graph",
"extract_time_consuming_kernel",
"benchmark_kernel",
"analyze_performance",
"main"
] | 8 | [
[
"benchmark_forward_graph",
"run_command"
],
[
"benchmark_kernel",
"run_command"
],
[
"profile_model",
"run_command"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 5b41554a938423f83ff5c250dc364c7decd0ac56 | 613a33d5a4816e761116cde73f5c808e7bf021c3 | |||
v1.0 | complete | Docs | Docs: Scikit_1461_C | from typing import List, Dict
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.metrics import mean_absolute_error, mean... | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.pr... | from solution import preprocess_data, forecast_sales
import pandas as pd
import pytest
# Generate sample data for testing
data = {
'store_id': [1, 1, 2, 2],
'item_id': [1, 2, 1, 2],
'date': ['2021-01-01', '2021-01-02', '2021-01-01', '2021-01-02'],
'sales': [20.0, 30.5, np.nan, 25.0]
}
test_df = pd.Data... | [
{
"docstring": null,
"function_declaration": "def preprocess_data(df):",
"function_name": "preprocess_data",
"parameter_list": "(df)"
},
{
"docstring": null,
"function_declaration": "def forecast_sales(data_path):",
"function_name": "forecast_sales",
"parameter_list": "(data_path... | [
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 pandas as pd\nfrom sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV\nfrom sklearn.preprocessing import StandardScaler, OneHotEncode... | trial_gpt4o_2 | {
"original_instruction": "**Question:**\n\nYou are provided with a dataset of historical sales data and various features about items and stores. Your task is to build a predictive model to forecast future sales using any suitable supervised learning technique(s) from the scikit-learn library.\n\n**Dataset Descriptio... | 0.820849 | Docs: Scikit_1461 | C | [
"preprocess_data",
"forecast_sales"
] | 2 | [
[
"forecast_sales",
"preprocess_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 368a1fd32cb7016cc18ee3171380f705be336c5f | 8d0e032999d3eba0fa203a40cab00ad1dbb860e7 | |||
v1.0 | complete | Docs | Docs: Python310_2588_C | import unicodedata
def normalized_unicode(input_string: str) -> str:
"""
Normalize a given string to 'NFD' (Normalization Form D).
Args:
input_string (str): The string to be normalized.
Returns:
str: The normalized string.
>>> normalized_unicode("Café")
'Café'
>>> normal... | import unicodedata
def normalized_unicode(input_string: str) -> str:
"""
Normalize a given string to 'NFD' (Normalization Form D).
Args:
input_string (str): The string to be normalized.
Returns:
str: The normalized string.
"""
return unicodedata.normalize('NFD', input_string)
... | from solution import normalized_unicode, compare_normalized_strings
def test_normalized_unicode_simple():
assert normalized_unicode("Café") == "Café" # 'é' -> 'e' + combining acute accent
def test_normalized_unicode_already_normalized():
assert normalized_unicode("Café") == "Café" # Already decomposed
d... | [
{
"docstring": "Normalize a given string to 'NFD' (Normalization Form D).\n\nArgs:\ninput_string (str): The string to be normalized.\n\nReturns:\nstr: The normalized string.",
"function_declaration": "def normalized_unicode(input_string):",
"function_name": "normalized_unicode",
"parameter_list": "(... | [
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 unicodedata\n\ndef normalized_unicode(input_string: str) -> str:\n \"\"\"\n Normalize a given string to 'NFD' (Normalization Form D).\n \n Args:\n ... | trial_gpt4o_0 | {
"original_instruction": "### Unicode Normalization in Python\n\n**Objective:**\nWrite a Python function `normalized_unicode` that normalizes a given string to the 'NFD' (Normalization Form D) normalization form, which means decomposing combined characters into their canonical equivalents.\n\n**Details:**\nThe task ... | 0.655043 | Docs: Python310_2588 | C | [
"normalized_unicode",
"compare_normalized_strings"
] | 2 | [
[
"compare_normalized_strings",
"normalized_unicode"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 35d3cf141e980645832a29eb0962c3922ca15c25 | 782af112291a38659fced1bd486105435684e21e | |||
v1.0 | complete | Docs | Docs: Pandas_2329_C | import pandas as pd
import os
from typing import List
def load_columns(file_path: str, columns: List[str]) -> pd.DataFrame:
"""
Load specific columns from a given parquet file.
Args:
file_path (str): The path to the parquet file.
columns (List[str]): The list of column names to load.
... | import pandas as pd
import os
def load_columns(file_path, columns):
"""
Load specific columns from a given parquet file.
"""
return pd.read_parquet(file_path, columns=columns)
def optimize_memory(df):
"""
Optimize the memory usage of the DataFrame by converting data types.
"""
# Conver... | import pandas as pd
import os
import pytest
from unittest import mock
from solution import load_columns, optimize_memory, process_in_chunks
def test_load_columns():
with mock.patch('pandas.read_parquet', return_value=pd.DataFrame({
"name": ["a", "b", "c"],
"id": [1, 2, 3],
"x": [1.0, 2.0, 3... | [
{
"docstring": "Load specific columns from a given parquet file.",
"function_declaration": "def load_columns(file_path, columns):",
"function_name": "load_columns",
"parameter_list": "(file_path, columns)"
},
{
"docstring": "Optimize the memory usage of the DataFrame by converting data types... | [
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 os\nfrom glob import glob\n\ndef load_columns(file_path, columns):\n \"\"\"\n Load specific columns from a parquet file.\n \n Ar... | trial_gpt4o_9 | {
"original_instruction": "#### Context\nYou are provided with a folder containing multiple parquet files where each file represents time-series data of different years. Each file contains columns such as `name`, `id`, `x`, and `y`. The purpose of this task is to effectively load and process these large datasets by o... | 0.531952 | Docs: Pandas_2329 | C | [
"load_columns",
"optimize_memory",
"process_in_chunks"
] | 3 | [
[
"process_in_chunks",
"load_columns"
],
[
"process_in_chunks",
"optimize_memory"
]
] | 2 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | a08b05ce2c359c970422a73c9c03f9a4b9c1bba4 | 93f412b6cbd86c047b1f44244b2feb7dc2fdd914 | |||
v1.0 | complete | Docs | Docs: Python310_2595_C | from typing import List, Union
def parallel_factorial(numbers: List[int], use_threads: bool = True, max_workers: int = None) -> List[Union[int, str]]:
"""Computes the factorial of a list of numbers in parallel.
Args:
- numbers: List[int] - List of non-negative integers for which to compute the factori... | from typing import List, Union
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import math
def factorial(n: int) -> Union[int, str]:
"""
Computes the factorial of a non-negative integer n.
Returns "Invalid input" if n is negative.
"""
if n < 0:
return "Invalid input"
... | from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from solution import parallel_factorial
def test_parallel_factorial_with_valid_numbers():
# Testing with valid numbers
numbers = [5, 0, 7, 1]
expected = [120, 1, 5040, 1]
assert parallel_factorial(numbers, use_threads=True, max_work... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Union\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nimport math\n\ndef factorial(n: int) -> Union[int, str]:\n \"... | trial_gpt4o_0 | {
"original_instruction": "**Objective**:\nImplement a function that calculates the factorial of a list of numbers in parallel using the `concurrent.futures` module. Your implementation needs to handle exceptions, manage the lifecycle of the executor properly, and return the results in the same order as the input lis... | 0.815881 | Docs: Python310_2595 | C | [
"factorial",
"parallel_factorial"
] | 2 | [
[
"parallel_factorial",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5c095a17a00d9e9618fadd18d5134e313732ce85 | 51e484fb698f1ab4d52c317429482dc3730519d6 | |||
v1.0 | complete | Docs | Docs: Pytorch_2829_C | import torch
from torch.func import vmap, grad
def batch_mse_gradient(predictions: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
"""
Compute the gradient of the MSE loss with respect to the predictions for each example in the batch.
>>> predictions = torch.tensor([[0.0, 1.0], [2.0, 3.0]], requires_... | import torch
from torch.func import vmap, grad
def mse_loss(pred, target):
return torch.mean((pred - target) ** 2)
def batch_mse_gradient(predictions: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
"""
Compute the gradient of the MSE loss with respect to the predictions for each example in the batc... | import torch
from solution import batch_mse_gradient
def test_batch_mse_gradient_simple_case():
predictions = torch.tensor([[0.0, 1.0], [2.0, 3.0]], requires_grad=True)
targets = torch.tensor([[0.5, 1.5], [2.5, 3.5]])
gradients = batch_mse_gradient(predictions, targets)
expected_gradients = torch.tenso... | [
{
"docstring": null,
"function_declaration": "def mse_loss(pred, target):",
"function_name": "mse_loss",
"parameter_list": "(pred, target)"
},
{
"docstring": "Compute the gradient of the MSE loss with respect to the predictions for each example in the batch.",
"function_declaration": "de... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.func import vmap, grad\n\ndef mse_loss(pred, target):\n return torch.mean((pred - target) ** 2)\n\ndef batch_mse_gradient(predictions: torch... | trial_gpt4o_7 | {
"original_instruction": "### PyTorch Coding Assessment Question\n\n**Objective:**\nDemonstrate your understanding of PyTorch's torch.func operations and limitations by implementing a function that applies vectorized computations and gradients using pure function transformations.\n\n**Problem Statement:**\n\nImpleme... | 0.561402 | Docs: Pytorch_2829 | C | [
"mse_loss",
"batch_mse_gradient"
] | 2 | [
[
"batch_mse_gradient",
"mse_loss"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 45f8770689e2fa3fc3c71e31ab16e09bbb66015e | 95d9c3d3f345e3b24f155396869428157a74c7c0 | |||
v1.0 | complete | Docs | Docs: Python310_2381_C | from __future__ import print_function
import sys
import io
def read_and_process_file(filename):
""" Read a file, process its content to find unique words.
>>> read_and_process_file('testfile.txt')
{'hello', 'world', 'testing'}
"""
with io.open(filename, 'r', encoding='utf-8') as file:
conte... | from __future__ import print_function # To use print() as a function in Python 2
import sys
import io
def read_and_process_file(filename):
with io.open(filename, 'r', encoding='utf-8') as file: # Handles file in text mode with UTF-8 encoding
content = file.read()
results = process_content(content... | from solution import read_and_process_file, process_content
def test_process_content():
content = "hello world\nhello testing"
result = process_content(content)
assert result == {"hello", "world", "testing"}
def test_read_and_process_file(tmp_path):
d = tmp_path / "sub"
d.mkdir()
p = d / "test... | [
{
"docstring": null,
"function_declaration": "def read_and_process_file(filename):",
"function_name": "read_and_process_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def process_content(content):",
"function_name": "process_content",
"para... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from __future__ import print_function # To use print() as a function in Python 2\nimport sys\nimport io\n\ndef read_and_process_file(filename):\n with io.open(filen... | trial_gpt4o_0 | {
"original_instruction": "**Question: Porting Code for Compatibility with Python 2 and 3**\n\n**Objective:**\nYou are given a piece of code written in Python 2. Your task is to port it to be compatible with both Python 2 and Python 3. This will require you to handle text and binary data correctly, adjust for divisio... | 0.552124 | Docs: Python310_2381 | C | [
"read_and_process_file",
"process_content",
"main"
] | 3 | [
[
"read_and_process_file",
"process_content"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e67123424be7bd32f5816a99ee4492b69a4179cb | 925a6fb3d62a02e257884d2c7f6795f90b2b3e32 | |||
v1.0 | complete | Docs | Docs: Python310_2524_C | import json
import importlib
import importlib.metadata
from typing import List, Dict
def read_json_config(config_path: str) -> List[Dict[str, str]]:
"""
Reads the JSON configuration file and returns a list of modules information.
"""
try:
with open(config_path, 'r') as file:
config_... | import json
import importlib
import importlib.metadata
from typing import List, Dict
def read_json_config(config_path: str) -> List[Dict[str, str]]:
"""
Reads the JSON configuration file and returns a list of modules information.
"""
try:
with open(config_path, 'r') as file:
config_... | import pytest
import json
from unittest.mock import patch, mock_open
from solution import dynamic_import, module_metadata
# Sample data as string
sample_json = json.dumps({
"modules": [
{
"name": "json",
"package": "json",
"version": "0.1"
},
{
... | [
{
"docstring": "Reads the JSON configuration file and returns a list of modules information.",
"function_declaration": "def read_json_config(config_path):",
"function_name": "read_json_config",
"parameter_list": "(config_path)"
},
{
"docstring": "Reads the module configuration from a JSON fi... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import importlib\nimport json\nimport subprocess\nfrom typing import Dict\n\ndef dynamic_import(config_path: str):\n \"\"\"\n Reads the module configuration file ... | trial_gpt4o_6 | {
"original_instruction": "### Dynamic Module Import and Metadata Handling\n\nJavaScript Object Notation (JSON) is a common format for storing and exchanging data. For this problem, you are required to create a Python utility that can dynamically import modules based on instructions given in a JSON file and access me... | 0.702188 | Docs: Python310_2524 | C | [
"read_json_config",
"dynamic_import",
"module_metadata"
] | 3 | [
[
"dynamic_import",
"read_json_config"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 90da1c8d86989937497606116a5559237e070a94 | 730dcd43e977cadcc3e9af1c016dd96a2a69922e | |||
v1.0 | complete | Docs | Docs: Python310_1728_C | def custom_acquire():
"""Simulate acquiring a custom resource."""
resource = "custom_resource"
print(f"Acquired {resource}")
return resource
def custom_release(resource):
"""Simulate releasing a custom resource."""
print(f"Released {resource}")
def manage_resources(resource_configs: list[dict]... | def custom_acquire():
"""
Simulate acquiring a custom resource.
"""
resource = "custom_resource"
print(f"Acquired {resource}")
return resource
def custom_release(resource):
"""
Simulate releasing a custom resource.
"""
print(f"Released {resource}")
def manage_resources(resource... | import tempfile
from solution import manage_resources, custom_acquire, custom_release
def test_manage_resources_files():
with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
path = tmpfile.name
resource_configs = [
{"type": "file", "action": "open", "path": path},
]
results =... | [
{
"docstring": "Simulate acquiring a custom resource.",
"function_declaration": "def custom_acquire():",
"function_name": "custom_acquire",
"parameter_list": "()"
},
{
"docstring": "Simulate releasing a custom resource.",
"function_declaration": "def custom_release(resource):",
"func... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from contextlib import ExitStack\n\ndef custom_acquire():\n resource = \"custom_resource\"\n print(f\"Acquired {resource}\")\n return resource\n\ndef custom_re... | trial_gpt4o_1 | {
"original_instruction": "**Objective**: Assess the understanding and application of context managers using the `contextlib` module, specifically `ExitStack`.\n\n#### Problem Statement\n\nPlease write a function `manage_resources` that handles multiple resource management scenarios using a combination of context man... | 0.44573 | Docs: Python310_1728 | C | [
"custom_acquire",
"custom_release",
"manage_resources"
] | 3 | [
[
"manage_resources",
"custom_acquire"
],
[
"manage_resources",
"custom_release"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e12ab10ce43fd09ecd33021fadddea1394387b59 | 944233a3ea88e0bc1cd3d8ef19383f2b9bfd5797 | |||
v1.0 | complete | Docs | Docs: Python310_2166_C | def merge_and_query(dict1, dict2, keys):
""" Merge two dictionaries and retrieve key-value pairs based on given conditions.
Args:
dict1 (dict): The first dictionary.
dict2 (dict): The second dictionary.
keys (list): A list of keys to query in the final merged dictionary.
Returns:
list:... | def merge_dicts(dict1, dict2):
"""
Recursively merges dict2 into dict1.
"""
for key in dict2:
if key in dict1 and isinstance(dict1[key], dict) and isinstance(dict2[key], dict):
merge_dicts(dict1[key], dict2[key])
else:
dict1[key] = dict2[key]
return dict1
def... | from solution import merge_and_query
def test_merge_and_query_with_simple_dicts():
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
keys = ['a', 'b', 'c', 'd']
assert merge_and_query(dict1, dict2, keys) == [1, 3, 4, None]
def test_merge_and_query_with_nested_dicts():
dict1 = {'a': 1, 'b': {'x': 2... | [
{
"docstring": "Recursively merges dict2 into dict1.",
"function_declaration": "def merge_dicts(dict1, dict2):",
"function_name": "merge_dicts",
"parameter_list": "(dict1, dict2)"
},
{
"docstring": "Merges dict2 into dict1 and retrieves the values for the keys specified in keys 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": "def merge_and_query(dict1, dict2, keys):\n \"\"\"\n Merge dict2 into dict1 and create a list of values for the specified keys.\n \n If a key exists in both ... | trial_gpt4o_2 | {
"original_instruction": "#### Objective:\nImplement a function that merges two dictionaries with specific constraints and retrieves key-value pairs based on given conditions.\n\n#### Problem Statement:\nYou are required to implement a Python function `merge_and_query(dict1, dict2, keys)` that takes in three paramet... | 0.584204 | Docs: Python310_2166 | C | [
"merge_dicts",
"merge_and_query"
] | 2 | [
[
"merge_and_query",
"merge_dicts"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 83ce63929846f70a93919ea15b9b9bdae2227ad8 | b56e25dda7bd5632c4d005e66253df70ba173b62 | |||
v1.0 | complete | Docs | Docs: Python310_2587_C | import struct
from typing import Tuple, Any
def pack_data(format_str: str, data: Tuple[Any, ...]) -> bytes:
"""
Packs a tuple of values into a bytes object according to the given format string.
:param format_str: A format string.
:param data: A tuple of values.
:return: Packed bytes object.
... | import struct
def pack_data(format_str, data):
"""
Packs a tuple of values into a bytes object according to the given format string.
:param format_str: A format string.
:param data: A tuple of values.
:return: Packed bytes object.
:raises struct.error: If the format or data is incorrect.
... | from solution import pack_data, unpack_data, read_struct, write_struct
def test_pack_data():
assert pack_data('>hhl', (1, 2, 3)) == b'\x00\x01\x00\x02\x00\x00\x00\x03'
assert pack_data('<I', (1,)) == b'\x01\x00\x00\x00'
def test_unpack_data():
assert unpack_data('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03'... | [
{
"docstring": "Packs a tuple of values into a bytes object according to the given format string.\n\n:param format_str: A format string.\n:param data: A tuple of values.\n:return: Packed bytes object.\n:raises struct.error: If the format or data is incorrect.",
"function_declaration": "def pack_data(format_... | [
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 struct\n\ndef pack_data(format_str, data):\n \"\"\"\n Packs a tuple of values into a bytes object according to the given format string.\n \n :param f... | trial_gpt4o_0 | {
"original_instruction": "#### Objective:\nDemonstrate your understanding of the Python `struct` module by implementing functions that handle packing and unpacking of structured binary data.\n\n#### Task:\n1. Implement a function `pack_data(format_str, data)` that takes a format string and a tuple of values, and ret... | 0.55142 | Docs: Python310_2587 | C | [
"pack_data",
"unpack_data",
"read_struct",
"write_struct"
] | 4 | [
[
"read_struct",
"unpack_data"
],
[
"write_struct",
"pack_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 98e10b2ad54f1fca30d6ed2f2e3c8c0581b6b93f | 63b8c439db0e9ff5f83817c6ee9074201d99adc5 | |||
v1.0 | complete | Docs | Docs: Python310_2743_C | def compute_statistics(data):
"""
Computes statistical measures from a dataset.
"""
import math
statistics = {
'mean': sum(data) / len(data),
'variance': sum((x - sum(data) / len(data)) ** 2 for x in data) / len(data),
'std_dev': math.sqrt(sum((x - sum(data) / len(data)) ** 2... | import math
import cProfile
import pstats
import io
def compute_statistics(data):
"""
Computes statistical measures from a dataset.
"""
statistics = {
'mean': sum(data) / len(data),
'variance': sum((x - sum(data) / len(data)) ** 2 for x in data) / len(data),
'std_dev': math.sqrt... | import pytest
from solution import compute_statistics, optimized_compute_statistics
# Test cases for the original implementation
def test_compute_statistics_mean():
data = [1, 2, 3, 4, 5]
stats = compute_statistics(data)
assert stats['mean'] == 3.0
def test_compute_statistics_variance():
data = [1, 2,... | [
{
"docstring": "Computes statistical measures from a dataset.",
"function_declaration": "def compute_statistics(data):",
"function_name": "compute_statistics",
"parameter_list": "(data)"
},
{
"docstring": null,
"function_declaration": "def profile_and_analyze(data):",
"function_name"... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def compute_statistics(data):\n import math\n mean = sum(data) / len(data)\n sum_squared_diff = sum((x - mean) ** 2 for x in data)\n variance = sum_squared_... | trial_gpt4o_1 | {
"original_instruction": "<|Analysis Begin|>\n\nThe provided documentation details the usage of the `cProfile` and `profile` modules used for deterministic profiling in Python. These tools are essential for understanding the performance characteristics of a Python program by providing detailed statistics about funct... | 0.597353 | Docs: Python310_2743 | C | [
"compute_statistics",
"profile_and_analyze",
"optimized_compute_statistics"
] | 3 | [
[
"profile_and_analyze",
"compute_statistics"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3ecacb3a3ecaff03bd31e46a6bcd9837f63c3e5a | 798a22b7d866fa62611bbb2f4d02fa0d0cb0cf54 | |||
v1.0 | complete | Docs | Docs: Python310_2310_C | import asyncio
async def fetch_url(url):
"""Fetch content from the given URL."""
# Simulate fetching data from URL
await asyncio.sleep(1)
return f"Fetched data from {url}"
async def process_data(data):
"""Process the fetched data."""
# Simulate data processing
await asyncio.sleep(1)
re... | import asyncio
import aiohttp
async def fetch_url(url):
"""
Fetch content from the given URL.
"""
async with aiohttp.ClientSession() as session:
try:
async with session.get(url) as response:
data = await response.text()
return data
except Exce... | import asyncio
from solution import async_scraper, fetch_url, process_data
async def test_fetch_url():
result = await fetch_url("http://example.com")
assert isinstance(result, str)
async def test_process_data():
result = await process_data("Sample data")
assert result == "Processed data: Sample data"
... | [] | [
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 aiohttp\n\nasync def fetch_url(url):\n \"\"\"\n Asynchronously fetch the content of the URL.\n \"\"\"\n try:\n async with aioh... | trial_gpt4o_1 | {
"original_instruction": "### Asynchronous Web Scraper\n\n**Objective**: Implement an asynchronous web scraper that fetches data from multiple URLs concurrently and processes the fetched data without blocking the event loop.\n\n**Requirements**:\n1. Create an asynchronous function `fetch_url` that takes a URL and fe... | 0.623516 | Docs: Python310_2310 | C | [
"fetch_url",
"process_data",
"async_scraper"
] | 3 | [
[
"async_scraper",
"fetch_url"
],
[
"async_scraper",
"process_data"
]
] | 2 | [
"process_data"
] | false | [] | false | pytest | true | [
"aiohttp"
] | false | fd409201f33c5b7c69f9b59b3493c168e56729c4 | c9869228fe36e52ff7ad651d7f52c5f548109f18 | |||
v1.0 | complete | Docs | Docs: Python310_1877_C | from wsgiref.util import shift_path_info
from wsgiref.headers import Headers
from wsgiref.simple_server import make_server
def app1(environ, start_response):
"""WSGI application that modifies and prints PATH_INFO and SCRIPT_NAME."""
# Implementation here
pass
def app2(environ, start_response):
"""WSGI... | from wsgiref.util import shift_path_info
from wsgiref.headers import Headers
from wsgiref.simple_server import make_server
def app1(environ, start_response):
# Modify PATH_INFO
shifted = shift_path_info(environ)
status = '200 OK'
response_headers = Headers([('Content-Type', 'text/plain')])
response... | from wsgiref.util import setup_testing_defaults
from io import BytesIO
from solution import app1, app2, simple_app_router
def start_response_mock(status, headers, exc_info=None):
start_response_mock.status = status
start_response_mock.headers = headers
start_response_mock.exc_info = exc_info
def test_app1... | [
{
"docstring": null,
"function_declaration": "def app1(environ, start_response):",
"function_name": "app1",
"parameter_list": "(environ, start_response)"
},
{
"docstring": null,
"function_declaration": "def app2(environ, start_response):",
"function_name": "app2",
"parameter_list... | [
0,
0,
1,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl",
"solution_code": "from wsgiref.util import shift_path_info\nfrom wsgiref.headers import Headers\nfrom wsgiref.simple_server import make_server\n\ndef app1(enviro... | trial_gpt4o_3 | {
"original_instruction": "### WSGI Environment Manipulation and Server Implementation\n\n**Objective:**\n\nDesign a WSGI application that demonstrates the following abilities:\n\n1. **Environment Inspection and Manipulation:**\n - Inspect and modify the WSGI environment.\n - Implement a feature that modifies `PA... | 0.62283 | Docs: Python310_1877 | C | [
"app1",
"app2",
"simple_app_router"
] | 3 | [
[
"simple_app_router",
"app1"
],
[
"simple_app_router",
"app2"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b9ade48c50bb1e48135569b66abf0d3f390e99b9 | 1dc05776d0c6e083ffcef99407a6d75c77fcc3a1 | |||
v1.0 | complete | Docs | Docs: Python310_2748_C | import hashlib
def verify_file_integrity(input_file_path: str, hash_algorithm: str, expected_hash: str) -> bool:
"""
Verifies the integrity of a file by comparing its hash value with an expected hash.
Parameters:
input_file_path (str): The path to the input file.
hash_algorithm (str): The name... | import hashlib
def verify_file_integrity(input_file_path: str, hash_algorithm: str, expected_hash: str) -> bool:
"""
Verifies the integrity of a file by comparing its hash value with an expected hash.
Parameters:
input_file_path (str): The path to the input file.
hash_algorithm (str): The name of ... | import pytest
import tempfile
import os
from solution import generate_file_hash, verify_file_integrity
def test_generate_file_hash_sha256():
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(b"sample text for hashing")
temp_file_path = temp_file.name
expected_has... | [
{
"docstring": "Verifies the integrity of a file by comparing its hash value with an expected hash.\n\nParameters:\ninput_file_path (str): The path to the input file.\nhash_algorithm (str): The name of the hash algorithm to use (e.g., 'sha256', 'blake2b').\nexpected_hash (str): The expected hash value in hexade... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\n\ndef verify_file_integrity(input_file_path: str, hash_algorithm: str, expected_hash: str) -> bool:\n \"\"\"\n Verifies the integrity of a file by... | trial_gpt4o_2 | {
"original_instruction": "**Problem Statement: Data Integrity Verification Utility**\n\n**Objective:**\nCreate a Python utility that verifies the integrity of files using secure hash algorithms provided by the `hashlib` module. This utility should be able to generate and verify hash values for files using different ... | 0.73379 | Docs: Python310_2748 | C | [
"verify_file_integrity",
"generate_file_hash"
] | 2 | [
[
"verify_file_integrity",
"generate_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b7c0c00d9f8a3f60fb0280f76c78a7225cbfc578 | 1183eb3be1bb5db26ab19aac5a89a9a4a8489488 | |||
v1.0 | complete | Docs | Docs: Python310_3148_C | import asyncio
from typing import List
async def async_network_client(server_address: str, port: int, messages: List[str]) -> List[str]:
""" Implement an asynchronous network client that connects to a given server,
sends data, and collects responses concurrently using asyncio.
Args:
server_address (st... | import asyncio
from typing import List
async def send_message(reader, writer, message: str) -> str:
writer.write(message.encode())
await writer.drain()
response = await reader.read(100)
return response.decode()
async def async_network_client(server_address: str, port: int, messages: List[str]) -> Lis... | import asyncio
from solution import async_network_client
from unittest import mock
import pytest
@pytest.mark.asyncio
async def test_async_network_client():
server_address = '127.0.0.1'
port = 8080
messages = ['message1', 'message2', 'message3']
expected_responses = ['response1', 'response2', 'response... | [] | [
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 send_message(reader, writer, message: str) -> str:\n writer.write(message.encode())\n await writer.drain()\n\... | trial_gpt4o_0 | {
"original_instruction": "### Question: Asynchronous Network Client\n\nYou are to implement an asynchronous network client using the `asyncio` library. This client will connect to a given server, send data, and collect responses concurrently.\n\n#### Requirements:\n1. Implement an asynchronous function `async_networ... | 0.592899 | Docs: Python310_3148 | C | [
"send_message",
"async_network_client"
] | 2 | [
[
"async_network_client",
"send_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bfbf69fc045154dd5e46372994fefcc044be83dd | 9119c23bf47f5b9a519d667fd2c507f36772d107 | |||
v1.0 | complete | Docs | Docs: Python310_3227_C | import random
import tracemalloc
def simulate_memory_leak():
leaking_list = []
for _ in range(10000):
leaking_list.append(random.randint(1, 1000))
return sum(leaking_list)
def generate_memory_report():
"""
Generates a detailed report about memory usage and potential leaks using the tracema... | import random
import tracemalloc
def simulate_memory_leak():
leaking_list = []
for _ in range(10000):
leaking_list.append(random.randint(1, 1000))
return sum(leaking_list)
def generate_memory_report():
# Simulate memory usage and take snapshots
snapshot1 = tracemalloc.take_snapshot()
s... | import tracemalloc
from solution import simulate_memory_leak, generate_memory_report
def test_generate_memory_report():
"""
Test the generate_memory_report function to ensure that the output meets the required format and is accurate.
"""
# Temporarily capture the output
import io
import sys
... | [
{
"docstring": null,
"function_declaration": "def simulate_memory_leak():",
"function_name": "simulate_memory_leak",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def generate_memory_report():",
"function_name": "generate_memory_report",
"parameter_list"... | [
0,
0,
0,
1,
0,
1,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport tracemalloc\n\ndef simulate_memory_leak():\n leaking_list = []\n for _ in range(10000):\n leaking_list.append(random.randint(1, 1000)... | trial_gpt4o_6 | {
"original_instruction": "### Python Coding Assessment: Memory Allocation Debugging\n\n#### Objective:\nYou are required to use the `tracemalloc` module to identify memory leak patterns in a given Python application.\n\n#### Background:\nYou are provided with a Python application that simulates a memory leak. Your t... | 0.483078 | Docs: Python310_3227 | C | [
"simulate_memory_leak",
"generate_memory_report"
] | 2 | [
[
"generate_memory_report",
"simulate_memory_leak"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 68decc33056a9e32ba35d9a47005c50d19a5821f | 4cc81fb54c572f2da78adc6484496bf9440ea53f | |||
v1.0 | complete | Docs | Docs: Pytorch_3466_C | import torch
def custom_function(x):
"""
Computes the custom function f(x) = x^3 - 2x^2 + x.
Args:
x (torch.Tensor): Input tensor with requires_grad=True.
Returns:
torch.Tensor: Output of the function.
"""
def validate_gradient(x):
"""
Validates the gradient computation of the cu... | import torch
def custom_function(x):
"""
Computes the custom function f(x) = x^3 - 2x^2 + x.
Args:
x (torch.Tensor): Input tensor with requires_grad=True.
Returns:
torch.Tensor: Output of the function.
"""
return x**3 - 2*x**2 + x
def validate_gradient(x):
"""
Validates the g... | import pytest
import torch
from solution import custom_function, validate_gradient
def test_custom_function_output():
x = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float64, requires_grad=True)
expected = x**3 - 2*x**2 + x
assert torch.allclose(custom_function(x), expected, atol=1e-6), "custom_function outp... | [
{
"docstring": "Computes the custom function f(x) = x^3 - 2x^2 + x.\n\nArgs:\nx (torch.Tensor): Input tensor with requires_grad=True.\n\nReturns:\ntorch.Tensor: Output of the function.",
"function_declaration": "def custom_function(x):",
"function_name": "custom_function",
"parameter_list": "(x)"
... | [
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 torch\n\ndef custom_function(x):\n \"\"\"\n Computes the function f(x) = x^3 - 2x^2 + x.\n Args:\n - x (torch.Tensor): Input tensor.\n \n Retur... | trial_gpt4o_1 | {
"original_instruction": "### PyTorch Gradient Check and Validation\n\n**Objective:** \nImplement and validate gradient computation for a custom PyTorch function using `gradcheck` and `gradgradcheck`.\n\n**Problem Statement:** \nYou are given a custom function implemented in PyTorch. Your task is to write a function... | 0.471272 | Docs: Pytorch_3466 | C | [
"custom_function",
"validate_gradient"
] | 2 | [
[
"validate_gradient",
"custom_function"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 2e71233e1d414473fcda4f973df4ddbcfe5f5b42 | 20f3d49f9c1b4cfc7bfb3570f1663a7427ed833f | |||
v1.0 | complete | Docs | Docs: Pytorch_2582_C | import torch
import torch.distributed as dist
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel as DDP
import torch.optim as optim
# Custom compression function
def compress_gradients(tensor, factor=0.1):
"""Compresses the gradient tensor by scaling it down by a fixed factor.
Arg... | import torch
import torch.distributed as dist
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel as DDP
import torch.multiprocessing as mp
import torch.optim as optim
# Custom compression function
def compress_gradients(tensor, factor=0.1):
"""
Compresses the gradient tensor by scaling... | from solution import compress_gradients
def test_compression_factor():
tensor = torch.tensor([1.0, 2.0, 3.0])
compressed = compress_gradients(tensor, factor=0.1)
expected = torch.tensor([0.1, 0.2, 0.3])
assert torch.allclose(compressed, expected)
def test_custom_comm_hook():
# This function is to ... | [] | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.distributed as dist\nimport torch.nn as nn\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nimport torch.multiprocessing as mp\... | trial_gpt4o_6 | {
"original_instruction": "### PyTorch Distributed Training with Custom Communication Hook\n\n#### Background\nDistributed Data Parallel (DDP) in PyTorch allows model training to be distributed across multiple GPUs, accelerating the training process. To optimize communication among distributed nodes, PyTorch provides... | 0.594097 | Docs: Pytorch_2582 | C | [
"compress_gradients",
"custom_comm_hook",
"train",
"main"
] | 4 | [
[
"custom_comm_hook",
"compress_gradients"
]
] | 1 | [] | false | [
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | 7c6321ea0c373a82822d3a139159c0cdca32bd33 | d9234e4bd6643827d609508493698d1bed6cb293 | |||
v1.0 | complete | Docs | Docs: Python310_3039_C | def sum_for_loop(n):
"""
Function to compute the sum of first n integers using a for loop.
>>> sum_for_loop(1)
1
>>> sum_for_loop(5)
15
>>> sum_for_loop(100)
5050
>>> sum_for_loop(1000)
500500
"""
pass
def sum_list_comprehension(n):
"""
Function to compute the su... | def sum_for_loop(n):
total = 0
for i in range(1, n + 1):
total += i
return total
def sum_list_comprehension(n):
return sum([i for i in range(1, n + 1)])
def sum_arithmetic_series(n):
return n * (n + 1) // 2
import timeit
def compare_execution_times(n):
loop_time = timeit.timeit(lambd... | from solution import sum_for_loop, sum_list_comprehension, sum_arithmetic_series, compare_execution_times
def test_sum_for_loop():
assert sum_for_loop(1) == 1
assert sum_for_loop(5) == 15
assert sum_for_loop(100) == 5050
assert sum_for_loop(1000) == 500500
def test_sum_list_comprehension():
assert... | [
{
"docstring": null,
"function_declaration": "def sum_for_loop(n):",
"function_name": "sum_for_loop",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def sum_list_comprehension(n):",
"function_name": "sum_list_comprehension",
"parameter_list": "(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": "def sum_for_loop(n):\n total = 0\n for i in range(1, n + 1):\n total += i\n return total\n\ndef sum_list_comprehension(n):\n return sum([i for i in r... | trial_gpt4o_0 | {
"original_instruction": "<|Analysis Begin|>\n\nThe `timeit` Python module provides a simple way to measure the execution time of small code snippets. It includes both a Command-Line Interface and a Python API. The key functionalities of this module are:\n\n1. **Timeit Function**: \n - `timeit.timeit(stmt, setup, ... | 0.668788 | Docs: Python310_3039 | C | [
"sum_for_loop",
"sum_list_comprehension",
"sum_arithmetic_series",
"compare_execution_times"
] | 4 | [
[
"compare_execution_times",
"sum_arithmetic_series"
],
[
"compare_execution_times",
"sum_for_loop"
],
[
"compare_execution_times",
"sum_list_comprehension"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | defbe7b7350e1edfb4ce675c97496b7dc7989737 | 36ccd34303cb7d29529759d7f5a40e582e304a2a | |||
v1.0 | complete | Docs | Docs: Python310_3101_C | import asyncio
import random
async def handle_request(client_id, processing_time, lock):
""" Simulate processing a client request with a given processing time
and synchronize access to a shared resource using a lock.
"""
await asyncio.sleep(processing_time)
async with lock:
print(f"Client ... | import asyncio
import random
async def handle_request(client_id, processing_time, lock):
await asyncio.sleep(processing_time)
async with lock:
print(f"Client {client_id} processed in {processing_time} seconds")
return client_id
async def client_requests(num_clients, max_time):
queue =... | import asyncio
from solution import client_requests
def test_client_requests_order():
num_clients = 5
max_time = 2
result = asyncio.run(client_requests(num_clients, max_time))
assert len(result) == num_clients
assert set(result) == set(range(num_clients))
def test_client_requests_empty():
num_... | [] | [
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\n\nasync def handle_request(client_id, processing_time, lock):\n await asyncio.sleep(processing_time)\n async with lock:\n pr... | trial_gpt4o_0 | {
"original_instruction": "### Asyncio Task Scheduling and Synchronization in Python\n\nYou are tasked with creating an asynchronous program using Python's `asyncio` package to simulate a scenario where multiple clients request services from a server. The server should be able to handle these requests concurrently wh... | 0.539729 | Docs: Python310_3101 | C | [
"handle_request",
"client_requests"
] | 2 | [
[
"client_requests",
"handle_request"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ef761a31b13f51af081fc22965ad4203aae46c77 | 6a7bfdf8225dd54469665ce6faae8c9e43c0a0d7 | |||
v1.0 | complete | Docs | Docs: Python310_2882_C | import concurrent.futures
import re
def download_url(url):
"""
Simulated function to download URL content.
In a real scenario, you would fetch the content using `requests` or similar libraries.
"""
import time
import random
time.sleep(random.uniform(0.1, 0.5)) # Simulate network delay
... | import concurrent.futures
import re
def download_url(url):
"""
Simulated function to download URL content.
In a real scenario, you would fetch the content using `requests` or similar libraries.
"""
import time
import random
time.sleep(random.uniform(0.1, 0.5)) # Simulate network delay
... | from solution import download_contents
import os
def setup_module(module):
"""Setup any state specific to the execution of the given module."""
urls = [
"http://example.com/page1",
"http://example.com/page2",
"http://example.com/page3"
]
for url in urls:
filename = re.s... | [
{
"docstring": "Simulated function to download URL content.\nIn a real scenario, you would fetch the content using `requests` or similar libraries.",
"function_declaration": "def download_url(url):",
"function_name": "download_url",
"parameter_list": "(url)"
},
{
"docstring": "Replace specia... | [
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 concurrent.futures\nimport re\n\ndef download_url(url):\n \"\"\"\n Simulated function to download URL content.\n In a real scenario, you would fetch the... | trial_gpt4o_0 | {
"original_instruction": "**Question: Implementing Parallel Task Execution with `concurrent.futures`**\n\n**Objective:** To assess your understanding of the `concurrent.futures` module by implementing a solution that uses parallel task execution for a given problem.\n\n**Problem Statement:**\n\nYou are given a list ... | 0.576687 | Docs: Python310_2882 | C | [
"download_url",
"sanitize_filename",
"save_content_to_file",
"download_contents"
] | 4 | [
[
"download_contents",
"download_url"
],
[
"download_contents",
"save_content_to_file"
],
[
"save_content_to_file",
"sanitize_filename"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | afc12fdd827c8e257c8cefef744b27637d7357f4 | a812dc421af70db98b6f499df841483ee80b690f | |||
v1.0 | complete | Docs | Docs: Python310_3633_C | import timeit
def compare_sum_methods(numbers: list[int], repetitions: int) -> dict:
""" Compare the execution times of different approaches for finding the sum of all integers in a list.
>>> numbers = [i for i in range(1000)]
>>> repetitions = 3
>>> result = compare_sum_methods(numbers, repetitio... | import timeit
def sum_by_for_loop(numbers):
total = 0
for num in numbers:
total += num
return total
def sum_by_built_in(numbers):
return sum(numbers)
def sum_by_list_comprehension(numbers):
return sum([num for num in numbers])
def compare_sum_methods(numbers: list[int], repetitions: int)... | from solution import compare_sum_methods
def test_compare_sum_methods():
numbers = [i for i in range(1000)]
repetitions = 3
result = compare_sum_methods(numbers, repetitions)
assert "for_loop" in result
assert "built_in_sum" in result
assert "list_comprehension_sum" in result
assert r... | [
{
"docstring": null,
"function_declaration": "def sum_by_for_loop(numbers):",
"function_name": "sum_by_for_loop",
"parameter_list": "(numbers)"
},
{
"docstring": null,
"function_declaration": "def sum_by_built_in(numbers):",
"function_name": "sum_by_built_in",
"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 timeit\n\ndef sum_with_for_loop(numbers):\n total = 0\n for number in numbers:\n total += number\n return total\n\ndef sum_with_builtin_sum(numbe... | trial_gpt4o_2 | {
"original_instruction": "#### Objective:\nWrite a Python function that compares the execution times of different approaches for solving a problem using the `timeit` module.\n\n#### Problem Description:\nYou are given a list of integers. Your task is to write three different functions to find the sum of all integers... | 0.579743 | Docs: Python310_3633 | C | [
"sum_by_for_loop",
"sum_by_built_in",
"sum_by_list_comprehension",
"compare_sum_methods"
] | 4 | [
[
"compare_sum_methods",
"sum_by_built_in"
],
[
"compare_sum_methods",
"sum_by_for_loop"
],
[
"compare_sum_methods",
"sum_by_list_comprehension"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 26b621d6a2c24586b46e9c4069355a1fd7686c92 | c2eb4c7824751749212f08a5edc5227f035262fc | |||
v1.0 | complete | Docs | Docs: Python310_3021_C | import asyncio
from typing import List
async def process_files(input_files: List[str], output_file: str) -> None:
"""
An asynchronous function that reads data from multiple files concurrently,
processes each file's data by reversing the lines of text and converting them to uppercase,
and writes the pro... | import asyncio
from typing import List
async def read_and_process_file(filename: str) -> str:
"""
Asynchronously reads a file, processes its content by reversing and uppercasing each line.
:param filename: Name of the file to read.
:return: Processed content of the file as a single string.
"""... | import asyncio
import os
from solution import process_files
import pytest
@pytest.fixture(scope="module")
def setup_files():
"""
Setup function to create test files for processing.
"""
filenames = ['test_file1.txt', 'test_file2.txt']
contents = ["Hello\nWorld", "Foo\nBar"]
for filename, c... | [] | [
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 asyncio\nfrom typing import List\n\nasync def read_and_process_file(filename: str) -> str:\n \"\"\"\n Reads, reverses the lines, converts to uppercase, and... | trial_gpt4o_1 | {
"original_instruction": "### Asynchronous File Processing with Coroutines\n\n#### Objective\n\nCreate an asynchronous file processing system using Python’s coroutines. Your task is to implement a function that reads data from multiple files concurrently, processes each file's data, and writes the processed data to ... | 0.622265 | Docs: Python310_3021 | C | [
"read_and_process_file",
"process_files"
] | 2 | [
[
"process_files",
"read_and_process_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiofiles"
] | false | 0022240dff76c64ca1f4001723b6ea75878293f0 | 2cea23e744e3477589c9e15b4d3c953c3dd94740 | |||
v1.0 | complete | Docs | Docs: Python310_3544_C | import cProfile
import pstats
def heavy_computation(n):
import time
start = time.time()
for i in range(n):
for _ in range(10000):
sum(range(100))
end = time.time()
print(f"Computation finished in {end - start:.2f} seconds")
def profile_heavy_computation():
"""
Profiles ... | import cProfile
import pstats
def heavy_computation(n):
import time
start = time.time()
for i in range(n):
for _ in range(10000):
sum(range(100))
end = time.time()
print(f"Computation finished in {end - start:.2f} seconds")
def profile_heavy_computation():
"""
Profiles ... | def test_profile_heavy_computation():
profile_heavy_computation()
import os
assert os.path.exists('profile_results.prof')
def test_analyze_profile_results(capsys):
analyze_profile_results()
captured = capsys.readouterr()
assert "ncalls" in captured.out
assert "tottime" in captured.out
a... | [
{
"docstring": null,
"function_declaration": "def heavy_computation(n):",
"function_name": "heavy_computation",
"parameter_list": "(n)"
},
{
"docstring": "Profiles the heavy_computation function and saves the results to 'profile_results.prof'.",
"function_declaration": "def profile_heavy... | [
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 cProfile\nimport pstats\nimport time\n\ndef heavy_computation(n):\n start = time.time()\n for i in range(n):\n for _ in range(10000):\n s... | trial_gpt4o_2 | {
"original_instruction": "### Coding Assessment: Profiling and Analyzing Python Code Execution\n\n#### Objective:\nYour task is to demonstrate your comprehension of Python's `cProfile` and `pstats` modules by profiling a Python function and analyzing the results.\n\n#### Problem Statement:\nYou are provided with a P... | 0.489514 | Docs: Python310_3544 | C | [
"heavy_computation",
"profile_heavy_computation",
"analyze_profile_results"
] | 3 | [
[
"profile_heavy_computation",
"heavy_computation"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 98c2ea6e1c24f9940df56e5c7811edeb60ab67b5 | 00e797725f383c9da3011c4cc28ca0bb25c98a73 | |||
v1.0 | complete | Docs | Docs: Python310_2996_C | def create_bytes_from_string(s: str) -> bytes:
"""
Takes a string s and returns a bytes object that is a copy of the string's content.
>>> create_bytes_from_string("Hello") == b'Hello'
>>> create_bytes_from_string("") == b''
"""
# Your implementation here
pass
def get_bytes_size(b: bytes) -... | def create_bytes_from_string(s: str) -> bytes:
"""
Takes a string s and returns a bytes object that is a copy of the string's content.
"""
return s.encode() # Using the encode method to convert string to bytes
def get_bytes_size(b: bytes) -> int:
"""
Takes a bytes object b and returns its siz... | from solution import create_bytes_from_string, get_bytes_size, concat_bytes, resize_bytes
def test_create_bytes_from_string():
assert create_bytes_from_string("Hello") == b'Hello'
assert create_bytes_from_string("") == b''
assert create_bytes_from_string("123") == b'123'
def test_get_bytes_size():
ass... | [
{
"docstring": "Takes a string s and returns a bytes object that is a copy of the string's content.",
"function_declaration": "def create_bytes_from_string(s):",
"function_name": "create_bytes_from_string",
"parameter_list": "(s)"
},
{
"docstring": "Takes a bytes object b and returns its siz... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def create_bytes_from_string(s: str) -> bytes:\n \"\"\"\n This function takes a string s and returns a bytes object \n that is a copy of the string's content.\... | trial_gpt4o_2 | {
"original_instruction": "#### Objective\n\nYour task is to implement several functions that simulate some of the operations provided by the `PyBytes_*` set of functions for managing bytes objects in Python. This exercise will test your understanding of bytes manipulation, handling size constraints, and ensuring mem... | 0.534954 | Docs: Python310_2996 | C | [
"create_bytes_from_string",
"get_bytes_size",
"concat_bytes",
"resize_bytes"
] | 4 | [
[
"concat_bytes",
"get_bytes_size"
],
[
"resize_bytes",
"get_bytes_size"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 601d7b3eb5a19cd1748bd8e51778863198992c8a | e1211fc750d1738eae1e3d7a1bcd4264c092a771 | |||
v1.0 | complete | Docs | Docs: Python310_3452_C | from typing import List, Tuple
async def run_multiple_commands(commands: List[str]) -> List[Tuple[str, int, str, str]]:
"""
Execute multiple shell commands asynchronously and return their details.
Args:
commands (List[str]): A list of shell commands to be executed.
Returns:
List[Tuple[str, in... | import asyncio
from typing import List, Tuple
async def run_command(cmd: str) -> Tuple[str, int, str, str]:
"""
Execute a command asynchronously and return its details.
"""
proc = await asyncio.create_subprocess_shell(cmd,
stdout=asyncio.subprocess.PIPE... | import asyncio
from solution import run_multiple_commands
async def test_run_multiple_commands():
commands = ["echo 'test'", "sleep 1; echo 'hello'", "python -c 'print(42)'", "invalid_command"]
results = await run_multiple_commands(commands)
assert len(results) == 4
# Testing echo command
... | [] | [
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 run_command(cmd: str) -> Tuple[str, int, str, str]:\n proc = await asyncio.create_subprocess_shell(\n ... | trial_gpt4o_2 | {
"original_instruction": "#### Objective\n\nYou are required to write an asynchronous Python function that spawns multiple subprocesses, monitors their execution, and collects their outputs. The goal is for you to demonstrate your understanding of the asyncio subprocess API in Python 3.10.\n\n#### Problem Statement\... | 0.761122 | Docs: Python310_3452 | C | [
"run_command",
"run_multiple_commands"
] | 2 | [
[
"run_multiple_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cb1f29fb765bfcb1512bf6d08604a4cc9ea49276 | 9fd38f8f90d6aa3634b79c71a206648115dee471 | |||
v1.0 | complete | Docs | Docs: Python310_2690_C | import cProfile
import pstats
def fib_recursive(n):
"""Calculate the nth Fibonacci number using recursion.
>>> fib_recursive(0)
0
>>> fib_recursive(1)
1
>>> fib_recursive(10)
55
"""
if n <= 1:
return n
else:
return fib_recursive(n - 1) + fib_recursive(n - 2)
def... | import cProfile
import pstats
import io
def fib_recursive(n):
if n <= 1:
return n
else:
return fib_recursive(n - 1) + fib_recursive(n - 2)
def fib_iterative(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
def profile_fib_functions():
# Profile recursive app... | from solution import fib_recursive, fib_iterative, profile_fib_functions, analyze_profiles
def test_fib_recursive():
assert fib_recursive(0) == 0
assert fib_recursive(1) == 1
assert fib_recursive(10) == 55
def test_fib_iterative():
assert fib_iterative(0) == 0
assert fib_iterative(1) == 1
asse... | [
{
"docstring": null,
"function_declaration": "def fib_recursive(n):",
"function_name": "fib_recursive",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def fib_iterative(n):",
"function_name": "fib_iterative",
"parameter_list": "(n)"
},
{
"docstri... | [
0,
0,
0,
1,
0,
0,
1,
0,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cProfile\nimport pstats\n\ndef fib_recursive(n):\n if n <= 1:\n return n\n else:\n return fib_recursive(n - 1) + fib_recursive(n - 2)\n\ndef ... | trial_gpt4o_6 | {
"original_instruction": "#### Objective\nDemonstrate your understanding of the `cProfile` and `pstats` modules by implementing a profiling function and analyzing the profiling results.\n\n#### Problem Statement\n\nYou are given a Python script that calculates the nth Fibonacci number using both an iterative and rec... | 0.626792 | Docs: Python310_2690 | C | [
"fib_recursive",
"fib_iterative",
"profile_fib_functions",
"analyze_profiles"
] | 4 | [
[
"profile_fib_functions",
"fib_iterative"
],
[
"profile_fib_functions",
"fib_recursive"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9b94d71463965fb95dacd72306f9067103040ba9 | 8dd39fefc2798fd6f071faa6233ce0d6e7ce9b3e | |||
v1.0 | complete | Docs | Docs: Seaborn_3026_C | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
def plot_facet_grid(data):
"""Create a `FacetGrid` that shows histograms of the `amount` spent, broken down by `category` and `age_group`.
Use `spends_often` as the `hue` parameter to differentiate between frequent an... | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# Create the dataset
data = {
'person_id': range(1, 101),
'category': ['food', 'transport', 'entertainment']*33 + ['food'],
'amount': np.random.uniform(5, 100, 100),
'age_group': np.random.choice(['18-25', '26-... | from solution import plot_facet_grid, plot_pair_grid, plot_custom_pair_grid
import pandas as pd
import numpy as np
def test_data_preparation():
data = {
'person_id': range(1, 101),
'category': ['food', 'transport', 'entertainment']*33 + ['food'],
'amount': np.random.uniform(5, 100, 100),
... | [
{
"docstring": null,
"function_declaration": "def plot_facet_grid(data):",
"function_name": "plot_facet_grid",
"parameter_list": "(data)"
},
{
"docstring": null,
"function_declaration": "def plot_pair_grid(data):",
"function_name": "plot_pair_grid",
"parameter_list": "(data)"
}... | [
0,
1,
1,
0,
1,
0,
0,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# Assuming the dataset is created as specified\ndata = {\n 'person... | trial_gpt4o_8 | {
"original_instruction": "### Question: Advanced Data Visualization with Seaborn\nYou are provided with a dataset that contains information about individuals' expenses on different categories like food, transport, and entertainment. Your task is to create a series of plots to visualize this data, highlighting relati... | 0.72384 | Docs: Seaborn_3026 | C | [
"plot_facet_grid",
"plot_pair_grid",
"custom_scatter_plot",
"plot_custom_pair_grid"
] | 4 | [
[
"plot_custom_pair_grid",
"custom_scatter_plot"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"pandas",
"seaborn"
] | false | d9770d285e0e368b430a797a8a430563d0f5aedd | 36e0182d032d83a8c95e3dba1bb434ddf2e5be0a | |||
v1.0 | complete | Docs | Docs: Python310_2642_C | import contextvars
# Define context variables
request_id_var = contextvars.ContextVar('request_id')
request_logs_var = contextvars.ContextVar('request_logs')
def log_request_id(request_id: str) -> None:
"""Set the request ID context variable."""
request_id_var.set(request_id)
request_logs_var.set([])
def... | import contextvars
# Define context variables
request_id_var = contextvars.ContextVar('request_id')
request_logs_var = contextvars.ContextVar('request_logs')
def log_request_id(request_id: str) -> None:
request_id_var.set(request_id)
request_logs_var.set([])
def log_message(message: str) -> None:
logs = ... | from solution import process_request, log_request_id, log_message, get_logs
def test_process_request():
request_id = "req-12345"
actions = [
"Starting request processing",
"Fetching user data",
"Processing data",
"Finishing request"
]
expected_logs = [
"[req-1234... | [
{
"docstring": null,
"function_declaration": "def log_request_id(request_id):",
"function_name": "log_request_id",
"parameter_list": "(request_id)"
},
{
"docstring": null,
"function_declaration": "def log_message(message):",
"function_name": "log_message",
"parameter_list": "(mes... | [
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 contextvars\n\n# Declare context variables\nrequest_id_var = contextvars.ContextVar('request_id')\nlog_accumulator_var = contextvars.ContextVar('log_accumulator'... | trial_gpt4o_8 | {
"original_instruction": "### Question: Context-Aware Asynchronous Logging System\n\nYou are tasked with implementing a context-aware logging system for an asynchronous web server using Python's `contextvars` module. The logging system should manage per-request logs, ensuring that log entries are isolated and preser... | 0.596157 | Docs: Python310_2642 | C | [
"log_request_id",
"log_message",
"get_logs",
"process_request"
] | 4 | [
[
"process_request",
"get_logs"
],
[
"process_request",
"log_message"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a003417732f81d1fdb71759b67c1f56c409b7e13 | f238dd682c97ac0cea52b18ae34990ba5dec37b4 | |||
v1.0 | complete | Docs | Docs: Python310_3385_C | import asyncio
from typing import List
async def download_files(urls: List[str], timeout: int, buffer_size: int) -> None:
"""
Asynchronous File Downloader with Exception Handling.
This function downloads files from multiple URLs and saves them locally.
Args:
urls (List[str]): A list of f... | import asyncio
import aiohttp
from typing import List
async def download_file(url: str, idx: int, timeout: int, buffer_size: int):
filename = f"file_{idx}.dat"
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=timeout) as response:
respo... | import pytest
import asyncio
from unittest.mock import patch, mock_open
from solution import download_files
@pytest.mark.asyncio
async def test_download_files_success():
urls = [
"https://example.com/file1",
"https://example.com/file2",
"https://example.com/file3"
]
timeout = 1
... | [] | [
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 os\n\nasync def fetch_file(session, url, filename, timeout, buffer_size):\n try:\n async with session.get(url, timeout=... | trial_gpt4o_2 | {
"original_instruction": "### Asynchronous File Downloader with Exception Handling\n\nYou are required to implement an asynchronous file downloader that reads files from multiple URLs and saves them locally. The implementation should handle various error conditions using the specified `asyncio` exceptions.\n\n#### R... | 0.61026 | Docs: Python310_3385 | C | [
"download_file",
"download_files"
] | 2 | [
[
"download_files",
"download_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | c54faa86d9d06353142c1b064465b53115d366f7 | 6b1a848d022e77676b840b5bb72aaf3897d8a4da | |||
v1.0 | complete | Docs | Docs: Python310_3746_C | import asyncio
async def start_server(host, port):
"""Start an asynchronous server that echoes messages back to clients and
sends periodic 'status update' messages to all connected clients.
Parameters:
host (str): The server's hostname or IP address.
port (int): The port number on which the server... | import asyncio
clients = []
async def handle_client(reader, writer):
addr = writer.get_extra_info('peername')
print(f"Connected to {addr}")
clients.append(writer)
try:
while True:
data = await reader.read(100)
if not data:
break
message = da... | import asyncio
import pytest
from unittest.mock import patch, MagicMock
from solution import start_server, start_client
@pytest.fixture
def event_loop():
loop = asyncio.new_event_loop()
yield loop
loop.close()
@pytest.mark.asyncio
async def test_server_start(event_loop):
with patch('solution.handle_c... | [] | [
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\nclients = []\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"Connected to {addr}\")\n\n cli... | trial_gpt4o_0 | {
"original_instruction": "#### Objective:\nDemonstrate your understanding of the asyncio event loop by implementing a server-client system where the server echoes messages sent by the clients. Additionally, use scheduled callbacks to periodically send a status update to connected clients.\n\n#### Question:\nYou need... | 0.651258 | Docs: Python310_3746 | C | [
"handle_client",
"status_update",
"start_server",
"start_client"
] | 4 | [
[
"start_server",
"handle_client"
],
[
"start_server",
"status_update"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 37f2d63a7b27e5e0f0363048971fa043ce9780ec | 94acd8efb503e8506f2ff6129b25d201cec2c034 | |||
v1.0 | complete | Docs | Docs: Python310_3406_C | import os
import sys
def validate_directories(directories):
"""
Validates the existence of directories.
Args:
directories (list): List of directory paths as strings.
Returns:
dict: Dictionary with directory paths as keys and boolean values indicating existence.
>>> validate_d... | import os
import sys
def validate_directories(directories):
"""
Validates the existence of directories.
Args:
directories (list): List of directory paths as strings.
Returns:
dict: Dictionary with directory paths as keys and boolean values indicating existence.
"""
return {dir... | import os
import tempfile
import pytest
from solution import validate_directories, configure_paths, add_site_directory, site_configuration
def test_validate_directories():
with tempfile.TemporaryDirectory() as tempdir:
valid_paths = [tempdir]
invalid_paths = [os.path.join(tempdir, "nonexistent")]
... | [
{
"docstring": "Validates the existence of directories.\n\nArgs:\n directories (list): List of directory paths as strings.\n\nReturns:\n dict: Dictionary with directory paths as keys and boolean values indicating existence.",
"function_declaration": "def validate_directories(directories):",
"funct... | [
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 os\nimport sys\n\ndef validate_directories(directories):\n \"\"\"\n Validates the existence of directories.\n \n Args:\n directories (list): L... | trial_gpt4o_2 | {
"original_instruction": "**Challenge: Environment Configuration with the `site` Module**\n\nIn this exercise, you will demonstrate your understanding of the `site` module by creating a Python script that configures the environment paths according to specific rules and validates the configuration.\n\n### Task\n\n1. ... | 0.586198 | Docs: Python310_3406 | C | [
"validate_directories",
"configure_paths",
"add_site_directory",
"site_configuration"
] | 4 | [
[
"configure_paths",
"validate_directories"
],
[
"site_configuration",
"add_site_directory"
],
[
"site_configuration",
"configure_paths"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | d7e5fa59d64efaf3661e4eaefd4d4d6e2234c5d1 | 097496b5c27cb7f3c5a694cb0e56f8af366497b0 | |||
v1.0 | complete | Docs | Docs: Python310_3179_C | import cProfile
import pstats
def function_a(n):
total = 0
for i in range(n):
total += i
return total
def function_b(n):
total = 0
for i in range(n):
total += function_a(i)
return total
def main():
result1 = function_a(1000)
result2 = function_b(1000)
return result... | import cProfile
import pstats
import io
import time
def function_a(n):
total = 0
for i in range(n):
total += i
return total
def function_b(n):
total = 0
for i in range(n):
total += function_a(i)
return total
def main():
result1 = function_a(1000)
result2 = function_b(... | import os
import pstats
from io import StringIO
from solution import profile_main, analyze_profiling_data
def test_profile_result_file_exists():
profile_main()
assert os.path.exists('profiling_results.prof')
def test_analyze_profiling_data_output():
profile_main()
output = StringIO()
stats = pstat... | [
{
"docstring": null,
"function_declaration": "def function_a(n):",
"function_name": "function_a",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def function_b(n):",
"function_name": "function_b",
"parameter_list": "(n)"
},
{
"docstring": null,
... | [
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 cProfile\nimport pstats\n\ndef function_a(n):\n total = 0\n for i in range(n):\n total += i\n return total\n\ndef function_b(n):\n total = 0\n... | trial_gpt4o_5 | {
"original_instruction": "### Advanced Python Profiling and Analysis\n\n**Objective**: To assess your understanding of Python's profiling tools \"cProfile\" and \"pstats\". \n\n**Problem Statement**:\nYou are provided with a piece of code that simulates some complex computations. Your task is to:\n1. Profile the cod... | 0.516734 | Docs: Python310_3179 | C | [
"function_a",
"function_b",
"main",
"profile_main",
"analyze_profiling_data"
] | 5 | [
[
"function_b",
"function_a"
],
[
"profile_main",
"main"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f23b9009b048e1b7f9ba6c9c7d321749158a67f8 | d77450f13054ac1ab3106f1fcf85c95fe9306ebe | |||
v1.0 | complete | Docs | Docs: Python310_3849_C | import asyncio
import random
async def process_tasks(task_count: int, worker_count: int) -> float:
"""Manage a series of tasks using asynchronous programming and asyncio Queue.
Parameters:
task_count (int): The number of tasks to generate and process.
worker_count (int): The number of worker coroutine... | import asyncio
import random
import time
async def worker(name, queue):
while True:
try:
sleep_for = await queue.get()
await asyncio.sleep(sleep_for)
queue.task_done()
except asyncio.CancelledError:
break
async def process_tasks(task_count: int, work... | import asyncio
import pytest
from solution import process_tasks
@pytest.mark.asyncio
async def test_process_tasks_with_few_tasks():
time_taken = await process_tasks(5, 2)
assert isinstance(time_taken, float)
assert time_taken > 0
@pytest.mark.asyncio
async def test_process_tasks_with_many_tasks():
ti... | [] | [
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\nimport time\n\nasync def worker(name, queue):\n while True:\n try:\n sleep_for = await queue.get()\n awai... | trial_gpt4o_0 | {
"original_instruction": "You are required to manage a series of tasks using asynchronous programming concepts and the `asyncio` queue described in the provided documentation. Each task involves a varying amount of work to be done (simulated by sleeping for a random amount of time). Your goal is to ensure that work ... | 0.583833 | Docs: Python310_3849 | C | [
"worker",
"process_tasks"
] | 2 | [
[
"process_tasks",
"worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 618438b98c56020040adceb46d12e8b575ac90e5 | c7731ac859c3577889a6365656ddf835c38f1b6b | |||
v1.0 | complete | Docs | Docs: Python310_2540_C | from typing import List, Optional
def generate_and_serve_docs(modules: List[str], output_dir: Optional[str] = None, serve: bool = False, keyword: Optional[str] = None) -> None:
""" Generate and serve documentation for a list of modules.
Parameters:
- modules: A list of module names to generate documen... | import pydoc
import os
from http.server import HTTPServer, SimpleHTTPRequestHandler
import threading
def generate_html_docs(module_name, output_dir=None):
"""
Generate HTML documentation for a given module and optionally save it to output_dir.
"""
try:
html_doc = pydoc.HTMLDoc().docroutine(__im... | def test_generate_and_serve_docs(tmp_path):
from solution import generate_and_serve_docs
import os
# Test data
modules = ["sys", "os", "math"]
output_dir = tmp_path
serve = False
keyword = "system"
# Run function
generate_and_serve_docs(modules, output_dir, serve, keyword)
... | [
{
"docstring": "Generate HTML documentation for a given module and optionally save it to output_dir.",
"function_declaration": "def generate_html_docs(module_name, output_dir=None):",
"function_name": "generate_html_docs",
"parameter_list": "(module_name, output_dir=None)"
},
{
"docstring": ... | [
0,
0,
0,
0,
1,
0,
1,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pydoc\nimport os\nimport http.server\nimport socketserver\n\ndef generate_and_serve_docs(modules, output_dir=None, serve=False, keyword=None):\n # Load and ge... | trial_gpt4o_6 | {
"original_instruction": "**Question:**\n\nYou are given the task of creating a Python script that uses the \"pydoc\" module to dynamically generate and serve documentation for a given list of modules. This script should:\n\n1. Load the specified modules.\n2. Serve the generated documentation via an HTTP server.\n3.... | 0.498398 | Docs: Python310_2540 | C | [
"generate_html_docs",
"start_http_server",
"search_keyword_in_docs",
"generate_and_serve_docs"
] | 4 | [
[
"generate_and_serve_docs",
"generate_html_docs"
],
[
"generate_and_serve_docs",
"search_keyword_in_docs"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 576e7274fbc6d8da12a8ede6965778cf10deb1b4 | 4719d8ac7832156e9f70fc65abd7b2555647e87e | |||
v1.0 | complete | Docs | Docs: Python310_2990_C | from xmlrpc.server import SimpleXMLRPCServer
def add(a, b):
""" Returns the sum of a and b.
>>> add(5, 3)
8
"""
pass
def subtract(a, b):
""" Returns the subtraction of b from a.
>>> subtract(5, 3)
2
"""
pass
def multiply(a, b):
""" Returns the multiplication of a and b.
... | from xmlrpc.server import SimpleXMLRPCServer
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def run_server():
server = SimpleXMLRPCServer(("localhost", 8000))
print("Server is listening on port 8000...")
server.register_function(add, "add")
... | import xmlrpc.client
import pytest
import subprocess
import time
def start_server_process():
return subprocess.Popen(['python', 'solution.py'])
def test_add():
server = start_server_process()
time.sleep(1) # Give the server time to start
proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
... | [
{
"docstring": null,
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def subtract(a, b):",
"function_name": "subtract",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"fu... | [
1,
0,
0,
0,
0,
1,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from xmlrpc.server import SimpleXMLRPCServer\n\ndef add(a, b):\n return a + b\n\ndef subtract(a, b):\n return a - b\n\ndef multiply(a, b):\n return a * b\n\nde... | trial_gpt4o_0 | {
"original_instruction": "**Coding Assessment Question:**\n\nYou are tasked with implementing a Python XML-RPC server and client using Python's `xmlrpc` package. The server should offer three functions: addition, subtraction, and multiplication of two numbers. The client should be able to call these functions remote... | 0.445191 | Docs: Python310_2990 | C | [
"add",
"subtract",
"multiply",
"run_server"
] | 4 | [
[
"run_server",
"add"
],
[
"run_server",
"multiply"
],
[
"run_server",
"subtract"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 36065a70a8cd137d468196ae588b63d446eff657 | 8381b89c4c093be45483452a069b241077750d9e | |||
v1.0 | complete | Docs | Docs: Python310_3464_C | import requests
def fetch_data_and_process(url, db):
response = requests.get(url)
if response.status_code == 200:
data = response.json()
processed_data = process_data(data)
db.save(processed_data)
else:
raise ValueError(f"Failed to fetch data: {response.status_code}")
def p... | import requests
def fetch_data_and_process(url, db):
response = requests.get(url)
if response.status_code == 200:
data = response.json()
processed_data = process_data(data)
db.save(processed_data)
else:
raise ValueError(f"Failed to fetch data: {response.status_code}")
def p... | import unittest
from unittest.mock import patch, Mock
from solution import fetch_data_and_process
class TestFetchDataAndProcess(unittest.TestCase):
@patch('solution.requests.get')
def test_successful_fetch_and_process(self, mock_get):
url = "http://example.com/data"
db = Mock()
mock_ge... | [
{
"docstring": null,
"function_declaration": "def fetch_data_and_process(url, db):",
"function_name": "fetch_data_and_process",
"parameter_list": "(url, db)"
},
{
"docstring": null,
"function_declaration": "def process_data(data):",
"function_name": "process_data",
"parameter_lis... | [
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 requests\n\ndef fetch_data_and_process(url, db):\n response = requests.get(url)\n if response.status_code == 200:\n data = response.json()\n ... | trial_gpt4o_2 | {
"original_instruction": "**Objective:**\n\nDemonstrate your understanding and effective use of the `unittest.mock` module in Python to create, configure, and assert interactions with mock objects. This question assesses your ability to use `Mock`, `patch`, and their various features.\n\n**Question:**\n\nYour task i... | 0.718837 | Docs: Python310_3464 | C | [
"fetch_data_and_process",
"process_data"
] | 2 | [
[
"fetch_data_and_process",
"process_data"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [
"requests"
] | false | 6f92347ba46eb8f797b4299494536276312f301e | 8f3e2f57ba8d081438f2d8e5c9139bc63da1a372 | |||
v1.0 | complete | Docs | Docs: Python310_3471_C | class BaseBookingError(Exception):
"""Base class for booking-related exceptions."""
pass
class InvalidBookingError(BaseBookingError):
"""Exception raised for invalid booking parameters."""
pass
class BookingDatabaseError(BaseBookingError):
"""Exception raised for database-related errors."""
pa... | class BaseBookingError(Exception):
pass
class InvalidBookingError(BaseBookingError):
pass
class BookingDatabaseError(BaseBookingError):
pass
class BookingNetworkError(BaseBookingError):
pass
def create_booking(booking_details):
"""
Create a booking with the given details.
Args:
... | import pytest
from solution import BaseBookingError, InvalidBookingError, BookingDatabaseError, BookingNetworkError, create_booking, save_booking_to_database, send_booking_confirmation, handle_booking
def test_create_booking_with_invalid_details():
with pytest.raises(InvalidBookingError):
create_booking({"... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class BaseBookingError(Exception):\n pass\n\nclass InvalidBookingError(BaseBookingError):\n pass\n\nclass BookingDatabaseError(BaseBookingError):\n pass\n\ncla... | trial_gpt4o_2 | {
"original_instruction": "Custom Exception Handling and Propagation\n\n#### Objective:\nDemonstrate your understanding of Python exception handling by implementing custom exceptions and effectively propagating exceptions through various layers of a program.\n\n#### Problem Description:\nYou are tasked with designing... | 0.501574 | Docs: Python310_3471 | C | [
"create_booking",
"save_booking_to_database",
"send_booking_confirmation",
"handle_booking"
] | 4 | [
[
"handle_booking",
"create_booking"
],
[
"handle_booking",
"save_booking_to_database"
],
[
"handle_booking",
"send_booking_confirmation"
]
] | 3 | [] | false | [
"BaseBookingError",
"InvalidBookingError",
"BookingDatabaseError",
"BookingNetworkError"
] | true | pytest | true | [] | true | 90096a782dc82c22ee2871eeaf0397b42e490aba | 72d08a46b2c3bba9f7cd15307652316be6ca6db5 | |||
v1.0 | complete | Docs | Docs: Python310_4083_C | import warnings
def issue_warnings() -> None:
"""Issues three types of warnings:
- UserWarning with the message "This is a user warning."
- DeprecationWarning with the message "This feature is deprecated."
- RuntimeWarning with the message "This is a runtime warning."
"""
pass
def configure_wa... | import warnings
def issue_warnings():
"""
Issues three types of warnings:
* UserWarning
* DeprecationWarning
* RuntimeWarning
"""
warnings.warn("This is a user warning.", UserWarning)
warnings.warn("This feature is deprecated.", DeprecationWarning)
warnings.warn("This is a runtime w... | from solution import issue_warnings, configure_warning_filters, test_warnings
def test_issue_warnings():
with warnings.catch_warnings(record=True) as caught_warnings:
issue_warnings()
assert len(caught_warnings) == 3
assert any(isinstance(w.message, UserWarning) for w in caught_warnings)
... | [
{
"docstring": "Issues three types of warnings:\n* UserWarning\n* DeprecationWarning\n* RuntimeWarning",
"function_declaration": "def issue_warnings():",
"function_name": "issue_warnings",
"parameter_list": "()"
},
{
"docstring": "Configures the warning filters:\n* Ignores DeprecationWarning... | [
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 warnings\n\ndef issue_warnings():\n \"\"\"\n Issues three types of warnings:\n * UserWarning\n * DeprecationWarning\n * RuntimeWarning\n \"\"\"... | trial_gpt4o_0 | {
"original_instruction": "#### Title: Custom Warning Handler and Filter Implementation\n\n#### Objective:\n\nTo assess the understanding of issuing custom warnings, configuring warning filters, and using context managers to handle warnings in Python.\n\n#### Problem Statement:\n\nA new module `custom_module.py` requ... | 0.465838 | Docs: Python310_4083 | C | [
"issue_warnings",
"configure_warning_filters",
"test_warnings"
] | 3 | [
[
"test_warnings",
"configure_warning_filters"
],
[
"test_warnings",
"issue_warnings"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 71233f8bdebd42b4e9b728143a27a4f2e157173e | f436545422e011eff6bd13901345a9715f5ecfbc | |||
v1.0 | complete | Docs | Docs: Scikit_2621_C | from sklearn.semi_supervised import SelfTrainingClassifier, LabelPropagation
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
import numpy as np
# Provided dataset
X_train = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8]... | from sklearn.semi_supervised import SelfTrainingClassifier, LabelPropagation
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
import numpy as np
# Provided dataset
X_train = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8]... | import pytest
from solution import self_training_classifier, label_propagation_classifier, evaluate_models
X_train = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10], [10, 11]]
y_train = [0, 1, -1, 1, -1, 0, 1, -1, 0, 1]
def test_self_training_classifier():
model = self_training_classifier... | [
{
"docstring": null,
"function_declaration": "def self_training_classifier(X_train, y_train):",
"function_name": "self_training_classifier",
"parameter_list": "(X_train, y_train)"
},
{
"docstring": null,
"function_declaration": "def label_propagation_classifier(X_train, y_train):",
"... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sklearn.semi_supervised import SelfTrainingClassifier, LabelPropagation\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import accuracy_score\nfr... | trial_gpt4o_1 | {
"original_instruction": "### Semi-Supervised Learning with Scikit-Learn\n\n#### Objective:\nImplement and evaluate a semi-supervised learning algorithm using Scikit-Learn's `SelfTrainingClassifier` and `LabelPropagation` classes.\n\n#### Background:\nYou are provided with a partially labeled dataset. Your task is t... | 0.579807 | Docs: Scikit_2621 | C | [
"self_training_classifier",
"label_propagation_classifier",
"evaluate_models"
] | 3 | [
[
"evaluate_models",
"label_propagation_classifier"
],
[
"evaluate_models",
"self_training_classifier"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 548ed555ec80c99aa10b61111090ffef68ca200b | a3b5ba2ce3e33e6f124c3c40b22500c0998be815 | |||
v1.0 | complete | Docs | Docs: Python310_4079_C | import asyncio
from typing import List, Tuple
async def set_after(fut: asyncio.Future, delay: int, value: str) -> None:
"""
Sleeps for the specified delay and sets the future's result.
:param fut: The asyncio.Future to set the result on.
:param delay: The delay in seconds before setting the result.
... | import asyncio
from typing import List, Tuple
async def set_after(fut: asyncio.Future, delay: int, value: str) -> None:
"""
Sleeps for the specified delay and sets the future's result.
:param fut: The asyncio.Future to set the result on.
:param delay: The delay in seconds before setting the result.
... | import asyncio
import pytest
from solution import schedule_tasks
@pytest.mark.asyncio
async def test_schedule_tasks_single():
task_delays = [(1, 'task1')]
results = await schedule_tasks(task_delays)
assert results == ['task1']
@pytest.mark.asyncio
async def test_schedule_tasks_multiple():
task_delays... | [] | [
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, Tuple\n\nasync def set_after(fut: asyncio.Future, delay: int, value: str) -> None:\n \"\"\"\n Sleeps for the specified de... | trial_gpt4o_0 | {
"original_instruction": "### Asyncio Futures in Python 3.10\n\n**Objective:**\nImplement a function that schedules multiple asynchronous tasks using `asyncio.Future`. Demonstrate the use of Futures by simulating an example where you wait for different asynchronous tasks to complete and aggregate their results.\n\n*... | 0.695119 | Docs: Python310_4079 | C | [
"set_after",
"schedule_tasks",
"main"
] | 3 | [
[
"schedule_tasks",
"set_after"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a145dbf68ab5e29113a122b65c401dbea40471d4 | 632221785df9ada27c9771fd95ba4c620bedb6ae | |||
v1.0 | complete | Docs | Docs: Python310_3753_C | import asyncio
async def read_file(file_path: str) -> str:
"""
Reads the entire content of the given file asynchronously.
Arguments:
file_path : str : Path to the input file
Returns:
str : Content of the file
Example:
>>> await read_file('example.txt')
'Example content'
"... | import asyncio
import os
async def read_file(file_path: str) -> str:
"""
Reads the entire content of the given file asynchronously.
Arguments:
file_path : str : Path to the input file
Returns:
str : Content of the file
"""
try:
async with aiofiles.open(file_path, 'r') as file:... | import asyncio
import os
import pytest
from solution import read_file, process_data, write_file, process_files_concurrently
# Assuming these are the example files and files exist temporarily for the test cases
input_files = ['test_file1.txt', 'test_file2.txt']
output_files = ['test_file1_processed.txt', 'test_file2_pr... | [
{
"docstring": "The main function to execute the file processing 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\nimport os\n\nasync def read_file(file_path: str) -> str:\n \"\"\"\n Reads the entire content of the given file asynchronously.\n\n Arguments:\n... | trial_gpt4o_0 | {
"original_instruction": "### Asynchronous File Processing with asyncio\n\nYou are tasked with creating a Python script that reads data from multiple files concurrently, processes the content asynchronously, and writes the processed content to new output files using the asyncio package. The required operations inclu... | 0.564592 | Docs: Python310_3753 | C | [
"read_file",
"process_data",
"write_file",
"process_files_concurrently",
"main"
] | 5 | [
[
"process_files_concurrently",
"process_data"
],
[
"process_files_concurrently",
"read_file"
],
[
"process_files_concurrently",
"write_file"
]
] | 3 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 877ea8b70f4ac5796779e247c8924bca3297b7f1 | 3cbd6e57a6a05f6b45b75b2e13271d583aa2054e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.