version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | instruct | Docs | Docs: Python310_287_I | Secure HMAC Message Verification
A 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 mechanism provided by Python's `hmac` ... | 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": "",
"prompt_id": "00000287",
"row_id": 287,
"seed_ids": "[298]"
} | 0.849704 | Docs: Python310_287 | I | [
"sign_message",
"verify_message"
] | 2 | [
[
"verify_message",
"sign_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0ed991f02e28e0931a8138e08374070d63a7b52d | 0d2550e821808fd1b903491cf7a48e46a594470f | |||
v1.0 | instruct | Docs | Docs: Python310_333_I | ### Custom Codec Implementation and Error Handling in Python
#### Objective:
Demonstrate your understanding of custom codec implementation, error handling, and the use of the `codecs` module in Python.
#### Problem Statement:
You are to implement a custom codec to encode and decode data using a simple substitution ci... | import codecs
class CaesarCodec(codecs.Codec):
def encode(self, input, errors='strict'):
output = []
for char in input:
if 'a' <= char <= 'z':
output.append(chr((ord(char) - ord('a') + 3) % 26 + ord('a')))
elif 'A' <= char <= 'Z':
output.appen... | def test_custom_encode_simple():
assert custom_encode("abc") == "def"
assert custom_encode("xyz") == "abc"
assert custom_encode("ABC") == "DEF"
assert custom_encode("XYZ") == "ABC"
def test_custom_encode_with_non_alpha_chars():
assert custom_encode("Hello, World!") == "Khoor, Zruog!"
assert cus... | [] | [
0,
1,
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 codecs\n\nclass CaesarCodec(codecs.Codec):\n def encode(self, input, errors='strict'):\n output = []\n for char in inpu... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00000333",
"row_id": 333,
"seed_ids": "[211]"
} | 0.647375 | Docs: Python310_333 | I | [
"rot13_error_handler",
"caesar_shift",
"custom_encode",
"custom_decode"
] | 4 | [
[
"rot13_error_handler",
"caesar_shift"
]
] | 1 | [] | false | [
"CaesarCodec"
] | true | pytest | false | [] | true | 3f9c4a35e0c14ed933f4a02480648c74173e2d1b | 511dedf85f5b58633f6495f07845a89cb75fef5f | |||
v1.0 | instruct | Docs | Docs: Python310_336_I | #### Problem Description
You are required to implement a function that creates a new user on a Unix system, assigns this user to a new group, and logs this activity using the Unix syslog facility. Additionally, the function should set resource limits for the newly created user to restrict their CPU time and memory usa... | import os
import pwd
import grp
import resource
import syslog
def create_user_with_limits(username, groupname, cpu_limit, memory_limit):
try:
# Create a new group
if not group_exists(groupname):
os.system(f"groupadd {groupname}")
else:
raise Exception(f"Group {groupn... | import pytest
from unittest.mock import patch, call
from solution import create_user_with_limits, group_exists, user_exists
def test_group_exists():
with patch('grp.getgrnam') as mock_getgrnam:
mock_getgrnam.side_effect = lambda x: x
assert group_exists('existinggroup')
mock_getgrnam.assert... | [
{
"docstring": null,
"function_declaration": "def create_user_with_limits(username, groupname, cpu_limit, memory_limit):",
"function_name": "create_user_with_limits",
"parameter_list": "(username, groupname, cpu_limit, memory_limit)"
},
{
"docstring": null,
"function_declaration": "def g... | [
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 os\nimport syslog\nimport pwd\nimport grp\nimport subprocess\n\ndef create_user_with_limits(username, groupname, cpu_limit, memory_limit):\n try:\n # C... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000336",
"row_id": 336,
"seed_ids": "[149]"
} | 0.433379 | Docs: Python310_336 | I | [
"create_user_with_limits",
"group_exists",
"user_exists"
] | 3 | [
[
"create_user_with_limits",
"group_exists"
],
[
"create_user_with_limits",
"user_exists"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 30811dd2c9baa3fcfd6cf345cfa360824f47e149 | ae875cf46d85612285a71b67e1c2614e250a81ef | |||
v1.0 | instruct | Docs | Docs: Pytorch_347_I | You are tasked with implementing a function that simulates a set of asynchronous tasks using the `torch.futures.Future` class, and processes their results once all tasks are completed.
Firstly, you need to write a function `async_task_simulation` that creates `n` asynchronous tasks. Each task simply waits for a given ... | import torch
import time
import threading
def async_task_simulation(task_id, delay):
future = torch.futures.Future()
def task():
time.sleep(delay)
future.set_result((task_id, f'Result from task {task_id}'))
threading.Thread(target=task).start()
return future
def process_all_t... | from solution import async_task_simulation, process_all_tasks
import torch
import time
def test_async_task_simulation():
future = async_task_simulation(1, 0.1)
result = future.wait()
assert result == (1, 'Result from task 1')
def test_process_all_tasks():
n = 3
delays = [0.1, 0.2, 0.3]
results... | [
{
"docstring": null,
"function_declaration": "def async_task_simulation(task_id, delay):",
"function_name": "async_task_simulation",
"parameter_list": "(task_id, delay)"
},
{
"docstring": null,
"function_declaration": "def process_all_tasks(n, delays):",
"function_name": "process_all... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport time\nimport concurrent.futures\nfrom typing import List, Tuple\n\ndef async_task_simulation(task_id, delay):\n future = torch.futures.Future()\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000347",
"row_id": 347,
"seed_ids": "[53]"
} | 0.533314 | Docs: Pytorch_347 | I | [
"async_task_simulation",
"process_all_tasks"
] | 2 | [
[
"process_all_tasks",
"async_task_simulation"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 3ad7e7aeb9c58415c480db01109baa64badc8aad | 570c014c2a913c630ff3e74d50567f93fc235bed | |||
v1.0 | instruct | Docs | Docs: Python310_358_I | **Asynchronous Task Coordination using `asyncio`**
**Objective:**
Implement a function that coordinates multiple asynchronous tasks using the `asyncio` module to simulate a scenario where multiple clients request data from a server simultaneously.
**Problem Statement:**
You are required to write a Python function `si... | import asyncio
import random
async def get_server_response() -> int:
await asyncio.sleep(random.randint(1, 3))
return random.randint(1, 100)
async def process_response(response: int) -> int:
await asyncio.sleep(0) # Simulate processing time
return response * 2
async def simulate_multiple_requests(nu... | import asyncio
from solution import simulate_multiple_requests
async def test_simulate_multiple_requests_single():
results = await simulate_multiple_requests(1)
assert len(results) == 1
assert all(isinstance(result, int) for result in results)
assert all(2 <= result <= 200 for result in results)
async... | [] | [
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 get_server_response() -> int:\n await asyncio.sleep(random.randint(1, 3))\n return random.randint(1, 100)\n\nasync def ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00000358",
"row_id": 358,
"seed_ids": "[151]"
} | 0.532382 | Docs: Python310_358 | I | [
"get_server_response",
"process_response",
"simulate_multiple_requests"
] | 3 | [
[
"simulate_multiple_requests",
"get_server_response"
],
[
"simulate_multiple_requests",
"process_response"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 999a9d876274d70f7bd6ce8b4875a6b5777c609c | d42cabdb3278cbfceb2fd2e615556a8c9096f4e7 | |||
v1.0 | instruct | Docs | Docs: Python310_369_I | **Objective:**
This 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 profiling features.
**Problem Statem... | 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": "",
"prompt_id": "00000369",
"row_id": 369,
"seed_ids": "[142]"
} | 0.483061 | Docs: Python310_369 | I | [
"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 | 1c577d074724c43d85c58cc4bb2f22c0dd7d9a0a | b3ccc1b12d91b84657b328fc5598c568366354d7 | |||
v1.0 | instruct | Docs | Docs: Python310_455_I | **Challenging Python Coding Assessment Question: Signal Handling and Timed Execution**
### Problem Statement
You 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 should:
1. Execute the target functi... | 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": "",
"prompt_id": "00000455",
"row_id": 455,
"seed_ids": "[253]"
} | 0.620188 | Docs: Python310_455 | I | [
"handler",
"execute_with_timeout"
] | 2 | [
[
"execute_with_timeout",
"handler"
]
] | 1 | [] | false | [
"TimeoutError"
] | true | pytest | true | [] | true | a07f3843b93bfe78d6e941aa767eccbeb813e608 | ee8e5d0d5607f26659a32f84155e68bcc0f1e31b | |||
v1.0 | instruct | Docs | Docs: Python310_462_I | **Queue Management System**
You 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:
1. Use `asyncio.PriorityQueue` to manage high-priority t... | 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": "",
"prompt_id": "00000462",
"row_id": 462,
"seed_ids": "[111]"
} | 0.611618 | Docs: Python310_462 | I | [
"process_task",
"manage_queues"
] | 2 | [
[
"manage_queues",
"process_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4cbd85222dda0cc8b5729c0a0dc099773103a0d9 | e072fe265161d687a3222027c86c276435d1e234 | |||
v1.0 | instruct | Docs | Docs: Python310_498_I | ### Python Memory Management: Custom Allocator Implementation
**Objective:**
Demonstrate 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.
### Problem Statement:
You are t... | # 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": "",
"prompt_id": "00000498",
"row_id": 498,
"seed_ids": "[46]"
} | 0.419621 | Docs: Python310_498 | I | [
"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 | e3646ae517637e09747358a167563156852d47ba | 6ea13b61e911b14e40270d590aa09b8846bb1f42 | |||
v1.0 | instruct | Docs | Docs: Scikit_502_I | **Objective:**
You 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.
**Problem Statement:**
Given a dataset and a li... | 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": "",
"prompt_id": "00000502",
"row_id": 502,
"seed_ids": "[64]"
} | 0.487504 | Docs: Scikit_502 | I | [
"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 | 4c6cf056de93e74f16bae7a2fa975a7581002b18 | db151c5b2d51701b1a78f08c827edae8df0ba024 | |||
v1.0 | instruct | Docs | Docs: Python310_512_I | ### Cell Object Operations in Python
**Objective**:
Implement a few function simulations for manipulating cell objects, reflecting the documented C-API behavior in Python.
**Problem Statement**:
You are required to emulate the behavior of "cell" objects and provide functions to manage them.
Implement the following:... | class Cell:
"""
Class representing a cell object, which holds a single value.
"""
def __init__(self, value):
self.value = value
def is_cell(obj):
"""
Checks if the provided object is an instance of the Cell class.
"""
return isinstance(obj, Cell)
def new_cell(value):
"""
... | from solution import Cell, is_cell, new_cell, get_cell_value, set_cell_value
def test_is_cell():
cell = new_cell(10)
assert is_cell(cell) == True
assert is_cell(10) == False
assert is_cell("not a cell") == False
def test_new_cell():
cell = new_cell(42)
assert is_cell(cell) == True
assert c... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Cell:\n \"\"\"\n A class representing a cell object, which can store a single value.\n \"\"\"\n def __init__(self, value):\n self._value = valu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000512",
"row_id": 512,
"seed_ids": "[38]"
} | 0.426391 | Docs: Python310_512 | I | [
"is_cell",
"new_cell",
"get_cell_value",
"set_cell_value"
] | 4 | [
[
"get_cell_value",
"is_cell"
],
[
"set_cell_value",
"is_cell"
]
] | 2 | [] | false | [
"Cell"
] | true | pytest | true | [] | true | 2d0af1a5ad34873632c4728be526aafcfe79fd01 | 4772c962bf1e8ae3f014698a27284f832fac4d7b | |||
v1.0 | instruct | Docs | Docs: Python310_518_I | ### **Python Coding Assessment: Advanced SQLite Operations**
#### **Objective:**
Demonstrate your understanding of the `sqlite3` module by performing complex database operations, including custom type adaptation, transaction control, and secure query execution.
#### **Problem Statement:**
You are given a task to im... | 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": "",
"prompt_id": "00000518",
"row_id": 518,
"seed_ids": "[103]"
} | 0.569511 | Docs: Python310_518 | I | [
"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 | 4f52cf4ce364369bb556b380e44a951c8bc09da8 | 1ee356f45293f67715d7a11dc1203f5481ae17c9 | |||
v1.0 | instruct | Docs | Docs: Python310_537_I | #### Background
You 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 storing these serialized objects in ... | 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": "",
"prompt_id": "00000537",
"row_id": 537,
"seed_ids": "[140]"
} | 0.536825 | Docs: Python310_537 | I | [
"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 | 20bc657bbe9677948532562299f58f0adb38ee79 | b49f3bf2304c0e4fdcf1b76ae288c220434c6fea | |||
v1.0 | instruct | Docs | Docs: Python310_566_I | ### Code Assessment Question: Implementing Asynchronous Task Management
#### Objective
You are tasked with demonstrating your understanding of the `asyncio` library by writing an asynchronous function that simulates a concurrent task processing system.
#### Problem Statement
Write an asynchronous function called `pro... | 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": "",
"prompt_id": "00000566",
"row_id": 566,
"seed_ids": "[270]"
} | 0.617321 | Docs: Python310_566 | I | [
"handle_task",
"process_tasks"
] | 2 | [
[
"process_tasks",
"handle_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 05ca5b12a8fdd4c98a85c7c06a23cba2650ac361 | 3e5b80699d920a27b0591da2a9a344aff67b0bbc | |||
v1.0 | instruct | Docs | Docs: Pytorch_581_I | ### Question: GPU-Based Operations with PyTorch MPS Backend
You 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:
1. **check_mps_device()**:
- *... | 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": "",
"prompt_id": "00000581",
"row_id": 581,
"seed_ids": "[167]"
} | 0.491448 | Docs: Pytorch_581 | I | [
"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 | d5faf795f662b214242c8a40f10b9fb8568fe90e | 8b37c2c652a65567cf89e29aa6cbf86e137efa0c | |||
v1.0 | instruct | Docs | Docs: Python310_586_I | **Question: Build a Simple Web Crawler Using Python Modules**
**Objective:**
Create a simple web crawler that navigates through web pages, retrieves information, handles HTTP responses, and manages cookies. The crawler should be able to parse the page content and follow certain links based on specified criteria.
**Ta... | import urllib.request
import urllib.error
import http.cookiejar
import urllib.parse
import re
from bs4 import BeautifulSoup
def make_request(url, cookie_jar):
try:
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie_jar))
response = opener.open(url)
return respons... | from solution import web_crawler
def test_web_crawler_example():
result = web_crawler("http://example.com", 2, "example.com/")
assert "http://example.com" in result
assert result["http://example.com"] == "Example Domain"
def test_web_crawler_single_page():
result = web_crawler("http://example.com", 0,... | [
{
"docstring": null,
"function_declaration": "def make_request(url, cookie_jar):",
"function_name": "make_request",
"parameter_list": "(url, cookie_jar)"
},
{
"docstring": null,
"function_declaration": "def parse_links(html_content, base_url, pattern):",
"function_name": "parse_links... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import urllib.request\nimport urllib.parse\nimport urllib.error\nfrom http.cookiejar import CookieJar\nimport re\nimport ipaddress\nfrom bs4 import BeautifulSoup\n\ndef... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00000586",
"row_id": 586,
"seed_ids": "[160]"
} | 0.642438 | Docs: Python310_586 | I | [
"make_request",
"parse_links",
"get_page_title",
"web_crawler"
] | 4 | [
[
"web_crawler",
"get_page_title"
],
[
"web_crawler",
"make_request"
],
[
"web_crawler",
"parse_links"
]
] | 3 | [] | false | [] | false | pytest | true | [
"bs4"
] | false | d9657367b0151b58e2cbb2a04bbcfe268ea02ee6 | b1b9bcd0055eba5244c5ccfd21c1ee8c8a6d3208 | |||
v1.0 | instruct | Docs | Docs: Python310_617_I | - Advanced `doctest` Implementation
**Objective:** Implement a custom `doctest` runner that enhances some of the capabilities found in the Python Standard Library's `doctest` module.
### Task Description:
You are to write a Python function `custom_doctest(module)`, which takes a Python module as input and performs th... | 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": "",
"prompt_id": "00000617",
"row_id": 617,
"seed_ids": "[402]"
} | 0.52779 | Docs: Python310_617 | I | [
"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 | 9f82635132fc7b3aed099c634d440fc55ffdf9a5 | d438e1fc390de0f9d708bacd8629f17a0f6e7c84 | |||
v1.0 | instruct | Docs | Docs: Python310_673_I | ### Question: Implement a Secure File Integrity Verifier
**Objective:**
You 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 with.
**Details:**
1. **Functi... | 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": "",
"prompt_id": "00000673",
"row_id": 673,
"seed_ids": "[225]"
} | 0.683307 | Docs: Python310_673 | I | [
"generate_file_hashes",
"verify_file_hashes"
] | 2 | [
[
"verify_file_hashes",
"generate_file_hashes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dfe611edfb72c025626c9735109984e0e19e4959 | 9d477f304c2854f759fa2bed269e84075cf45967 | |||
v1.0 | instruct | Docs | Docs: Python310_678_I | ### Task
You are required to 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 register a custom function named `concatenate_strings` t... | 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": "",
"prompt_id": "00000678",
"row_id": 678,
"seed_ids": "[297]"
} | 0.415704 | Docs: Python310_678 | I | [
"concatenate_strings",
"run_server"
] | 2 | [
[
"run_server",
"concatenate_strings"
]
] | 1 | [] | false | [
"MathOperations"
] | true | pytest | false | [] | true | e892d1ee0cf1f9b6c162410af0299c5edf0a654a | c56a6201aca0b462f3ed77011d34c76850e3274e | |||
v1.0 | instruct | Docs | Docs: Python310_703_I | **Question: Comprehensive Data Processing and File Manipulation**
**Background:**
You 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, publication year, and genre.
**Obj... | 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": "",
"prompt_id": "00000703",
"row_id": 703,
"seed_ids": "[255]"
} | 0.623169 | Docs: Python310_703 | I | [
"process_books_file",
"is_valid_isbn"
] | 2 | [
[
"process_books_file",
"is_valid_isbn"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 490b0680d16a03aed64e91b78b389e7bba4c8dec | 3ff47a01c352efa90def2e28453c8ba230694b97 | |||
v1.0 | instruct | Docs | Docs: Pytorch_724_I | ### Question: Efficient Stream and Device Management in PyTorch
You are required to implement a set of functions that demonstrate efficient management of streams, devices, and memory in PyTorch using the `torch.mtia` module.
#### Functions to Implement
1. **initialize_device**:
```python
def initialize_devic... | 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": "",
"prompt_id": "00000724",
"row_id": 724,
"seed_ids": "[86]"
} | 0.313365 | Docs: Pytorch_724 | I | [
"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 | 8bb6058210733a7cfba0809b8d5ec3cfcc0ff113 | f85234ec6517b28f1207dd5a91f96d92b6dc63cf | |||
v1.0 | instruct | Docs | Docs: Pytorch_782_I | ### PyTorch Coding Challenge: GPU Profiling with TorchInductor
#### Objective:
Demonstrate 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, and then optimizing specific kern... | 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": "",
"prompt_id": "00000782",
"row_id": 782,
"seed_ids": "[15]"
} | 0.491948 | Docs: Pytorch_782 | I | [
"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 | 5e06fcff938dcf0ce3e72cd5b3d2e178ba3ef641 | 613a33d5a4816e761116cde73f5c808e7bf021c3 | |||
v1.0 | instruct | Docs | Docs: Python310_796_I | ### Advanced Python Coding Challenge: Multi-Client Chat Server
#### Problem Statement
You 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 other in real-time.
#### Functi... | 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": "",
"prompt_id": "00000796",
"row_id": 796,
"seed_ids": "[63]"
} | 0.690378 | Docs: Python310_796 | I | [
"create_server_socket",
"accept_new_connection",
"broadcast_message",
"handle_client_message",
"main"
] | 5 | [
[
"handle_client_message",
"broadcast_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6a750a670ae1c6cd528e0495935c2662651fa148 | 174ed117eeb7886e1b53cbfc6f7a5b5e1fe6df41 | |||
v1.0 | instruct | Docs | Docs: Python310_808_I | 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.
**Requirements:**
1. Implement a `Task` class that includes:
- `priorit... | 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": "",
"prompt_id": "00000808",
"row_id": 808,
"seed_ids": "[111]"
} | 0.585469 | Docs: Python310_808 | I | [
"worker",
"task_scheduler",
"main"
] | 3 | [
[
"task_scheduler",
"worker"
]
] | 1 | [] | false | [
"Task"
] | true | pytest | true | [] | true | 599ebfc5203437de3356e7cddf99ebcf45c715bb | 1d6e16292fb1ebf6043d1ac105d6469e144cffaa | |||
v1.0 | instruct | Docs | Docs: Python310_834_I | **Objective:**
Implement 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.
**Function:**
```python
def process_paths_and_interactivity(paths):
"""
This function takes a list... | 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": "",
"prompt_id": "00000834",
"row_id": 834,
"seed_ids": "[49]"
} | 0.591337 | Docs: Python310_834 | I | [
"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 | 185236b56e3a07ae951eef910a6b760a39470b35 | f10729b055005ba47d5bd4216f03cff45f7fc5b1 | |||
v1.0 | instruct | Docs | Docs: Python310_898_I | #### Objective
To 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.
#### Problem Statement
In this task, you will implement a utility function that performs the ... | 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": "",
"prompt_id": "00000898",
"row_id": 898,
"seed_ids": "[216]"
} | 0.445186 | Docs: Python310_898 | I | [
"create_cyclic_reference",
"gc_utility"
] | 2 | [
[
"gc_utility",
"create_cyclic_reference"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3033df33525611c511f80f131ea204652620de2a | 019b704ef5c5bb1b8a4465a9dd33d755ad859850 | |||
v1.0 | instruct | Docs | Docs: Python310_959_I | ### Advanced Python Profiling and Analysis
**Objective**: Implement and analyze the performance of a Python script using `cProfile` and `pstats`.
**Problem Statement**:
You are given a Python script that performs a series of complex operations. Your task is to:
1. Profile the execution of the script using the `cProf... | import cProfile
import pstats
from pstats import SortKey
import time
def complex_operation_1():
time.sleep(0.5)
return sum([i**2 for i in range(10000)])
def complex_operation_2():
time.sleep(0.7)
return sum([i**3 for i in range(10000)])
def execute_operations():
result1 = complex_operation_1()
... | import os
import pytest
from solution import profile_script, analyze_profile
def test_profile_script_creates_file():
# Ensure profile file does not exist prior to profiling
if os.path.exists('profile_results.prof'):
os.remove('profile_results.prof')
# Run the profiler script
profile_script... | [
{
"docstring": null,
"function_declaration": "def complex_operation_1():",
"function_name": "complex_operation_1",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def complex_operation_2():",
"function_name": "complex_operation_2",
"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 cProfile\nimport pstats\nfrom pstats import SortKey\nimport time\n\ndef complex_operation_1():\n time.sleep(0.5)\n return sum([i**2 for i in range(10000)])... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00000959",
"row_id": 959,
"seed_ids": "[142]"
} | 0.540528 | Docs: Python310_959 | I | [
"complex_operation_1",
"complex_operation_2",
"execute_operations",
"profile_script",
"analyze_profile"
] | 5 | [
[
"execute_operations",
"complex_operation_1"
],
[
"execute_operations",
"complex_operation_2"
],
[
"profile_script",
"execute_operations"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 9aa2205830aec13047ec16643236a405b6bd4eac | 41de5815d96eeaa689bff612b6c5664557915a4c | |||
v1.0 | instruct | Docs | Docs: Python310_974_I | ### Parallel File Processing with `concurrent.futures`
#### Objective
Implement 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 count the number of words and l... | 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": "",
"prompt_id": "00000974",
"row_id": 974,
"seed_ids": "[224]"
} | 0.579001 | Docs: Python310_974 | I | [
"count_words_and_lines",
"process_files_concurrently"
] | 2 | [
[
"process_files_concurrently",
"count_words_and_lines"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1a2e4ad22104ac56029c9d669c9ded6cdb2d0975 | 0db4ae55009484b7668578c3f85db2d10a43a8b1 | |||
v1.0 | instruct | Docs | Docs: Python310_1011_I | ### Advanced Python Asyncio Subprocess Management
In 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.
#### Task:
Write a function `run_commands(comm... | 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": "",
"prompt_id": "00001011",
"row_id": 1011,
"seed_ids": "[264]"
} | 0.696938 | Docs: Python310_1011 | I | [
"run_command",
"run_commands"
] | 2 | [
[
"run_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | af9b2a85826a451194e080cc56a2f0fafc68f1ee | f8110cb3b7035c3818245bceb424b84a653bab83 | |||
v1.0 | instruct | Docs | Docs: Python310_1021_I | ### Asyncio Subprocesses: A Practical Exercise
You 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.
#### Task
Implement the function `run_commands(... | 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": "",
"prompt_id": "00001021",
"row_id": 1021,
"seed_ids": "[264]"
} | 0.714007 | Docs: Python310_1021 | I | [
"run_command",
"run_commands"
] | 2 | [
[
"run_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1dea643bf358da7485a632edce368d979a3f62fe | 1352e2aa96e1f32dc5dda7e04801db743e340148 | |||
v1.0 | instruct | Docs | Docs: Pandas_1024_I | **COVID-19 Data Analysis with pandas**
You are given a CSV file `covid19_data.csv` containing COVID-19 data with the following columns:
- `date`: The date of the record in `YYYY-MM-DD` format.
- `country`: The country for which the record applies.
- `new_cases`: The number of new COVID-19 cases reported on that date.
... | 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": "",
"prompt_id": "00001024",
"row_id": 1024,
"seed_ids": "[35]"
} | 0.632993 | Docs: Pandas_1024 | I | [
"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 | 7c878d3ac72c55dc7c99e78068a77d19edfef36b | 2d417b870065a19042d46936edbd5aa8f6776cab | |||
v1.0 | instruct | Docs | Docs: Python310_1040_I | ### Asyncio Exception Handling Task
#### Objective:
Write a Python function to handle multiple asyncio tasks, ensuring robust exception handling for common asyncio exceptions.
#### Task:
Implement an asynchronous function `fetch_multiple_urls(urls: List[str]) -> List[Tuple[str, Optional[str], Optional[Exception]]]` t... | 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": "",
"prompt_id": "00001040",
"row_id": 1040,
"seed_ids": "[396]"
} | 0.578591 | Docs: Python310_1040 | I | [
"fetch_url",
"fetch_multiple_urls"
] | 2 | [
[
"fetch_multiple_urls",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 577cd1c11fe649a05cf52eb653bc47faf0201167 | 297e0c6130751fa978669f6b8ae2b80a9a8796ca | |||
v1.0 | instruct | Docs | Docs: Python310_1050_I | ### Question: Advanced Filtering and Transformation with Functional Programming Modules
You 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 aggregate the data.
Implement the fu... | 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": "",
"prompt_id": "00001050",
"row_id": 1050,
"seed_ids": "[387]"
} | 0.570298 | Docs: Python310_1050 | I | [
"is_prime",
"process_numbers"
] | 2 | [
[
"process_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 43f82dda8d2fe5b7f0b747b8b91538a8202c05a7 | 3fbccbb3f3c984601141d42496372d658a4234a1 | |||
v1.0 | instruct | Docs | Docs: Python310_1052_I | ### Asyncio Task Queue Implementation
**Objective**: Demonstrate your understanding of the `asyncio` package by implementing a function that manages a queue of tasks to be executed asynchronously.
**Task Description**:
Write an asynchronous function `process_task_queue(task_list: List[Tuple[int, int]]) -> List[Tuple[... | 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": "",
"prompt_id": "00001052",
"row_id": 1052,
"seed_ids": "[270]"
} | 0.616922 | Docs: Python310_1052 | I | [
"worker",
"process_task_queue"
] | 2 | [
[
"process_task_queue",
"worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 74e85590eb3645376d78699cacda379ba3353077 | 6f339eadc19ca75cbdcc78e7997af5ba062ea196 | |||
v1.0 | instruct | Docs | Docs: Pytorch_1095_I | **Question:**
In 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`.
### Task Description
1. **Model Definition and Parameter Extraction**:
- Define a simple neural n... | 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": "",
"prompt_id": "00001095",
"row_id": 1095,
"seed_ids": "[61]"
} | 0.528001 | Docs: Pytorch_1095 | I | [
"model_function",
"compute_jacobian"
] | 2 | [
[
"compute_jacobian",
"model_function"
]
] | 1 | [] | false | [
"MyModel"
] | true | pytest | true | [
"torch"
] | false | 1c568c9c35b0a527c626f4efc289f0b5fe729a3d | ddd6d1caa9346fe38087a314998476e1f26fffd5 | |||
v1.0 | instruct | Docs | Docs: Pandas_1101_I | ### Pandas Coding Challenge
**Objective:** Validate students' understanding of pandas by having them perform a series of data operations on a given dataset.
#### Problem Statement
You are provided with a dataset in CSV format containing the sales records of a retail store. The CSV file (`sales_data.csv`) has the fol... | 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": "",
"prompt_id": "00001101",
"row_id": 1101,
"seed_ids": "[2]"
} | 0.740799 | Docs: Pandas_1101 | I | [
"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 | efb50ddd03fd6a59789fc3a4d926be3482270cfb | 403a105bb98e67c6be2f708bf112d12430c6610e | |||
v1.0 | instruct | Docs | Docs: Python310_1115_I | 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:
1. Validate the subnets.
2. Identify if a given address falls within any of the given subnets.
3. Summarize the given subnets to find the smallest set of superne... | 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": "",
"prompt_id": "00001115",
"row_id": 1115,
"seed_ids": "[408]"
} | 0.556172 | Docs: Python310_1115 | I | [
"validate_subnets",
"is_ip_in_subnets",
"summarize_subnets",
"total_unique_ips"
] | 4 | [
[
"total_unique_ips",
"validate_subnets"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 189c3091dc7e3220622ad56c8a4d7d52ca52847c | bf6810d4bd96dd3a6ba0878e50692c32bf1f2c77 | |||
v1.0 | instruct | Docs | Docs: Python310_1142_I | **ZIP File Operations**
**Objective**: To assess your understanding and ability to use the `zipfile` module in Python for handling ZIP file operations.
**Problem Statement**:
You are asked to write a Python function `zip_directory_structure` that takes the following inputs:
1. `input_directory` (str): The path to t... | 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": "",
"prompt_id": "00001142",
"row_id": 1142,
"seed_ids": "[242]"
} | 0.761901 | Docs: Python310_1142 | I | [
"zip_directory_structure",
"extract_and_verify_zip",
"compare_directories"
] | 3 | [
[
"extract_and_verify_zip",
"compare_directories"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 722c6d5baeec6998def84ac506c30b2d26be0ef7 | 7fc344655f2bab97e9e5f5dbdad3a8f7a00d5f1d | |||
v1.0 | instruct | Docs | Docs: Python310_1216_I | ### Concurrent Web Scraper using `asyncio`
#### Objective:
Implement 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.
#### Requirements:
1. Your solution must use `asyncio` for handling concurrency.
2. Create... | 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": "",
"prompt_id": "00001216",
"row_id": 1216,
"seed_ids": "[317]"
} | 0.653338 | Docs: Python310_1216 | I | [
"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 | eab46542cdddf4b0a6990f9b8635bb27f4667639 | cec2e4e2a3421ca930e60a4288886589f2f7fd20 | |||
v1.0 | instruct | Docs | Docs: Python310_1252_I | **Problem Statement**
You 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 manner.
### Function Signature
```... | 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": "",
"prompt_id": "00001252",
"row_id": 1252,
"seed_ids": "[338]"
} | 0.732657 | Docs: Python310_1252 | I | [
"compute_task",
"process_tasks"
] | 2 | [
[
"process_tasks",
"compute_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2fe6da8426f92e9e747c872c2b02d5665404fec4 | 9f4b454ab400680ae482f39ab39b174ed84b5aed | |||
v1.0 | instruct | Docs | Docs: Python310_1261_I | ### Group Management Script
You 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:
1. **Retrieve Group by ID**:
- Create a function `get_group_by_id(group_id)` that takes an integer `group_id` and returns ... | 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": "",
"prompt_id": "00001261",
"row_id": 1261,
"seed_ids": "[268]"
} | 0.392304 | Docs: Python310_1261 | I | [
"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 | de728277c342d16ef2585d14e184f4c53312eabd | 72a7b75bcae1a3b1819442282d71e83e3bddd80c | |||
v1.0 | instruct | Docs | Docs: Python310_1299_I | ### Question: Parallel File Processing Using `concurrent.futures`
You 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 integers in each file. Your task... | 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": "",
"prompt_id": "00001299",
"row_id": 1299,
"seed_ids": "[224]"
} | 0.52674 | Docs: Python310_1299 | I | [
"sum_integers_in_file",
"parallel_sum"
] | 2 | [
[
"parallel_sum",
"sum_integers_in_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 177f4c2e056597bfe4935f8c8884a52179a24be8 | fd2c0b201f3985b5574849d0c80ab2716ec20fc5 | |||
v1.0 | instruct | Docs | Docs: Python310_1334_I | #### Background
You 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.
#### Problem Statement
Implement an async ... | 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": "",
"prompt_id": "00001334",
"row_id": 1334,
"seed_ids": "[370]"
} | 0.550574 | Docs: Python310_1334 | I | [
"single_task",
"platform_aware_async_task"
] | 2 | [
[
"platform_aware_async_task",
"single_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ae413b0b629e7b6c8c09e882406b81947a71de2f | 36a718a4796583ac70f4ffc4b85503d3dc0e1361 | |||
v1.0 | instruct | Docs | Docs: Python310_1345_I | ### Python310 Cell Objects - Coding Assessment Question
#### Objective:
Demonstrate the use of Python310 Cell objects to manage and manipulate shared variables across multiple scopes.
#### Problem Statement:
Write a Python function `closure_cell_example()` that simulates the behavior of closure using Python310 Cell o... | # 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": "",
"prompt_id": "00001345",
"row_id": 1345,
"seed_ids": "[38]"
} | 0.481851 | Docs: Python310_1345 | I | [
"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 | 24155e53b235bf9d80f4dffd733940357874fd94 | 617ea8a8f2d0c237a45792b43e6131e026854ef3 | |||
v1.0 | instruct | Docs | Docs: Pytorch_1418_I | #### Objective
The 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 managing process synchronizati... | 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": "",
"prompt_id": "00001418",
"row_id": 1418,
"seed_ids": "[131]"
} | 0.49066 | Docs: Pytorch_1418 | I | [
"setup",
"cleanup",
"run_distributed_training"
] | 3 | [
[
"run_distributed_training",
"cleanup"
],
[
"run_distributed_training",
"setup"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 89653ed4f22cf675ee855e8ee756dc222b7106bf | 66064133ccaef8163dfc8e2c0a99eb5a2d76e026 | |||
v1.0 | instruct | Docs | Docs: Python310_1424_I | **Problem Statement:**
Create a Python program using the `ossaudiodev` module to perform one of the following operations based on user input:
1. **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.
2. **Live Audio Pass-Through**: C... | 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": "",
"prompt_id": "00001424",
"row_id": 1424,
"seed_ids": "[127]"
} | 0.49359 | Docs: Python310_1424 | I | [
"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 | f92107074620df64b1051f095c92640320be6b9b | b51605cd89304fbd5aa62e7ac22ba87da0f9a2cb | |||
v1.0 | instruct | Docs | Docs: Scikit_1461_I | **Question:**
You 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.
**Dataset Description:**
- The dataset `sales_data.cs... | 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": "",
"prompt_id": "00001461",
"row_id": 1461,
"seed_ids": "[1]"
} | 0.745018 | Docs: Scikit_1461 | I | [
"preprocess_data",
"forecast_sales"
] | 2 | [
[
"forecast_sales",
"preprocess_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 4cf3571dfd669eab52d45c565cb5b33ca9e660a0 | 8d0e032999d3eba0fa203a40cab00ad1dbb860e7 | |||
v1.0 | instruct | Docs | Docs: Python310_1495_I | ### Asynchronous TCP Server-Client Model
#### Objective
Design and implement an asynchronous TCP server-client model using the asyncio package.
#### Description
You are required to implement two components: an asynchronous TCP server and an asynchronous TCP client. The server will receive messages from the client and... | 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": "",
"prompt_id": "00001495",
"row_id": 1495,
"seed_ids": "[101]"
} | 0.664864 | Docs: Python310_1495 | I | [
"handle_client",
"start_server",
"start_client"
] | 3 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d8d0be65418ac0654b3b4666adb28f6ea152e441 | 63f83291d6a2e85a4c806cc9f55e8fe38224b0a2 | |||
v1.0 | instruct | Docs | Docs: Python310_1513_I | ### Debugging and Profiling with Python
#### Background:
You 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.
#### Task:
Given the following code ... | 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": "",
"prompt_id": "00001513",
"row_id": 1513,
"seed_ids": "[364]"
} | 0.526899 | Docs: Python310_1513 | I | [
"factorial",
"profile_function",
"main",
"factorial_optimized",
"main_optimized"
] | 5 | [
[
"main_optimized",
"factorial_optimized"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4018d9821458cc0f08ac530116b844460999ce32 | b8241f44b1979273f2efb448d9dc04a5ef4bd5d9 | |||
v1.0 | instruct | Docs | Docs: Pytorch_1539_I | **Challenging PyTorch Coding Question: Deterministic Tensor Initialization**
### Objective
Your 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 the `fill_uninitialized_memory` ... | 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": "",
"prompt_id": "00001539",
"row_id": 1539,
"seed_ids": "[108]"
} | 0.454474 | Docs: Pytorch_1539 | I | [
"manipulate_tensors",
"check_uninitialized_memory"
] | 2 | [
[
"check_uninitialized_memory",
"manipulate_tensors"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | d1091eca0829b98b5d0e033713da3a31a919e6c4 | d9262a1e8f178d47036aeb87e8fd8e4c479f51ff | |||
v1.0 | instruct | Docs | Docs: Python310_1541_I | ### Custom Codec Handling and Incremental Encoding/Decoding Assessment
You 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.
#### Task Description
1. **Custo... | 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": "",
"prompt_id": "00001541",
"row_id": 1541,
"seed_ids": "[211]"
} | 0.507141 | Docs: Python310_1541 | I | [
"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 | 2eda3b2047acc57442cd22d9711e702825931e82 | b2316b537a4a09df21e7e339e20d565b4941fbc5 | |||
v1.0 | instruct | Docs | Docs: Python310_1577_I | Profiling and Optimizing Python Code
**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.
**Instructions**:
1. **Function Implementation**:
- You are provided with a Pyt... | 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": "",
"prompt_id": "00001577",
"row_id": 1577,
"seed_ids": "[364]"
} | 0.512032 | Docs: Python310_1577 | I | [
"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 | 48b24f31dd2ebd0bb388cc3984805a81e215515e | 5a7de70cf17e3f6a485f0b89585bd4000bd39e4f | |||
v1.0 | instruct | Docs | Docs: Python310_1601_I | **Python Coding Assessment**
### Question: AIFF File Manipulation and Analysis
You 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:
1. **Open an AIFF file**: Write a function t... | 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": "",
"prompt_id": "00001601",
"row_id": 1601,
"seed_ids": "[365]"
} | 0.561592 | Docs: Python310_1601 | I | [
"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 | 1704d526f0b17f5dd919588191ff0ad545b8f78b | 193f387edba2cde21bf8f78684422329cb5adce1 | |||
v1.0 | instruct | Docs | Docs: Python310_1652_I | #### Objective
The 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.
#### Problem Statement
Create a Python function that uses context variables to maintain and m... | 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": "",
"prompt_id": "00001652",
"row_id": 1652,
"seed_ids": "[392]"
} | 0.496611 | Docs: Python310_1652 | I | [
"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 | d1a9cf26a111cf4a6bfb11ce8851505b70b44000 | c97f9b63f34a4f31afea9ac6afdb12c7592106e2 | |||
v1.0 | instruct | Docs | Docs: Python310_1706_I | ## Signal Handling and Inter-process Communication in Python
### Objective
Your 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 handling of signals in a Python pr... | 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": "",
"prompt_id": "00001706",
"row_id": 1706,
"seed_ids": "[253]"
} | 0.595681 | Docs: Python310_1706 | I | [
"computation",
"handler",
"simulation"
] | 3 | [
[
"simulation",
"computation"
],
[
"simulation",
"handler"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 464708f00f974fd229e210429669310a49c456b1 | efe863b036850c533d9f6c5bf0e86f62831ae565 | |||
v1.0 | instruct | Docs | Docs: Scikit_1722_I | Optimize Prediction Performance with Scikit-learn
#### Objective:
The 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 configuring appropriate settings.
#### 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": "",
"prompt_id": "00001722",
"row_id": 1722,
"seed_ids": "[64]"
} | 0.613938 | Docs: Scikit_1722 | I | [
"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 | 9f071e3ee6758b99edcb205acbac6d190168f41b | eda995df329ee33d186c7814d6d93f03122d4ea1 | |||
v1.0 | instruct | Docs | Docs: Python310_1728_I | **Objective**: Assess the understanding and application of context managers using the `contextlib` module, specifically `ExitStack`.
#### Problem Statement
Please write a function `manage_resources` that handles multiple resource management scenarios using a combination of context managers and other cleanup functions... | 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": "",
"prompt_id": "00001728",
"row_id": 1728,
"seed_ids": "[177]"
} | 0.395956 | Docs: Python310_1728 | I | [
"custom_acquire",
"custom_release",
"manage_resources"
] | 3 | [
[
"manage_resources",
"custom_acquire"
],
[
"manage_resources",
"custom_release"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b9e65566a7d56b1d8b94a4370d5a862550c3294f | 944233a3ea88e0bc1cd3d8ef19383f2b9bfd5797 | |||
v1.0 | instruct | Docs | Docs: Python310_1749_I | Mailbox Management and Message Handling
You are tasked with creating a mailbox management utility that organizes emails into different mailboxes based on specific criteria. The utility will primarily work with the `Maildir` and `mbox` formats. Your program should demonstrate an understanding of mailbox manipulation, a... | import mailbox
import email
def create_maildir(path):
"""
Create a Maildir mailbox at the specified path.
"""
return mailbox.Maildir(path, create=True)
def create_mbox(path):
"""
Create an mbox mailbox at the specified path.
"""
return mailbox.mbox(path, create=True)
def add_message_t... | import os
import shutil
import pytest
from solution import (
create_maildir, create_mbox, add_message_to_mailbox,
move_message, list_all_messages, remove_message
)
def test_maildir_mailbox_creation(tmpdir):
maildir_path = tmpdir.join("maildir")
maildir_box = create_maildir(maildir_path)
assert os.... | [
{
"docstring": "Create a Maildir mailbox at the specified path.",
"function_declaration": "def create_maildir(path):",
"function_name": "create_maildir",
"parameter_list": "(path)"
},
{
"docstring": "Create an mbox mailbox at the specified path.",
"function_declaration": "def create_mbox... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import mailbox\nimport os\n\ndef create_maildir(path):\n \"\"\"Create a Maildir mailbox at the specified path.\"\"\"\n return mailbox.Maildir(path, create=True)\n... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00001749",
"row_id": 1749,
"seed_ids": "[361]"
} | 0.404947 | Docs: Python310_1749 | I | [
"create_maildir",
"create_mbox",
"add_message_to_mailbox",
"move_message",
"list_all_messages",
"remove_message"
] | 6 | [
[
"move_message",
"remove_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ece209d9351db7e61483bda1932350e2d96bde22 | 6091e886f7bdaf55cdc2923d3e1b8d0f41269542 | |||
v1.0 | instruct | Docs | Docs: Pytorch_1766_I | <|Analysis Begin|>
Upon 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, and discusses both numeric and anal... | 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": "",
"prompt_id": "00001766",
"row_id": 1766,
"seed_ids": "[179]"
} | 0.363369 | Docs: Pytorch_1766 | I | [
"f_real",
"f_complex",
"verify_gradients"
] | 3 | [
[
"verify_gradients",
"f_complex"
],
[
"verify_gradients",
"f_real"
]
] | 2 | [] | false | [] | false | pytest | false | [
"torch"
] | false | b7027b7372c9640a36591cd57a9dbad2fb3a8f6b | e7f1d62a0d2ed111c95226e03da744a844e9594e | |||
v1.0 | instruct | Docs | Docs: Python310_1806_I | **Objective:** Demonstrate your understanding of the `xmlrpc.server` module by implementing a simple XML-RPC server that provides calculator functionalities.
**Task:**
1. **Create a SimpleXMLRPCServer** running on `localhost` and port `9000`.
2. **Register the following functions**:
- `add(x, y)`: Returns the sum ... | 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": "",
"prompt_id": "00001806",
"row_id": 1806,
"seed_ids": "[297]"
} | 0.378923 | Docs: Python310_1806 | I | [
"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 | df5325e92744acfab27b41ac76fa4a8c12489f44 | 6802752c12c5db27fac6e5bcf1b398a768896b86 | |||
v1.0 | instruct | Docs | Docs: Pytorch_1809_I | ### Distributed RPC Framework Coding Assessment
**Objective:**
You 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 perform computations on behalf of the ... | 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": "",
"prompt_id": "00001809",
"row_id": 1809,
"seed_ids": "[36]"
} | 0.442634 | Docs: Pytorch_1809 | I | [
"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 | 3099318ee799aa6a2f5f2fee06e1ea750d8c6732 | 6baa8f62ff09c9f9904401de4fa2f6b062f9543d | |||
v1.0 | instruct | Docs | Docs: Python310_1877_I | ### WSGI Environment Manipulation and Server Implementation
**Objective:**
Design a WSGI application that demonstrates the following abilities:
1. **Environment Inspection and Manipulation:**
- Inspect and modify the WSGI environment.
- Implement a feature that modifies `PATH_INFO` using the `shift_path_info` ... | 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": "",
"prompt_id": "00001877",
"row_id": 1877,
"seed_ids": "[210]"
} | 0.502692 | Docs: Python310_1877 | I | [
"app1",
"app2",
"simple_app_router"
] | 3 | [
[
"simple_app_router",
"app1"
],
[
"simple_app_router",
"app2"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a40ec1544e35f70b901afbc80e587cc8be6e2fca | 1dc05776d0c6e083ffcef99407a6d75c77fcc3a1 | |||
v1.0 | instruct | Docs | Docs: Python310_1954_I | **Advanced asyncio Debugging and Concurrency Challenge**
### Objective
Your 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 program handles concurrency, task ... | 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": "",
"prompt_id": "00001954",
"row_id": 1954,
"seed_ids": "[200]"
} | 0.568874 | Docs: Python310_1954 | I | [
"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 | 56ecec7e4f094dd4b38b033d8e6a5d5774491dc6 | db2152392eff4e5d92dadceac548b9598aa57675 | |||
v1.0 | instruct | Docs | Docs: Python310_2064_I | #### Background
The `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.
#### Task
Implement a function `fetch_webpage_urls()`... | 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": "",
"prompt_id": "00002064",
"row_id": 2064,
"seed_ids": "[370]"
} | 0.628671 | Docs: Python310_2064 | I | [
"fetch_url",
"fetch_webpage_urls",
"main"
] | 3 | [
[
"fetch_webpage_urls",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 11c76840dda018f7110b4a6bd3fd7198a04a0f17 | 1cea8347a92884cee67452badfc838c2642a8dea | |||
v1.0 | instruct | Docs | Docs: Python310_2166_I | #### Objective:
Implement a function that merges two dictionaries with specific constraints and retrieves key-value pairs based on given conditions.
#### Problem Statement:
You are required to implement a Python function `merge_and_query(dict1, dict2, keys)` that takes in three parameters:
1. `dict1` (dict): The first... | 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": "",
"prompt_id": "00002166",
"row_id": 2166,
"seed_ids": "[17]"
} | 0.737391 | Docs: Python310_2166 | I | [
"merge_dicts",
"merge_and_query"
] | 2 | [
[
"merge_and_query",
"merge_dicts"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5ce71176e8f30b9689e9314b64e9a9c5c318fc93 | b56e25dda7bd5632c4d005e66253df70ba173b62 | |||
v1.0 | instruct | Docs | Docs: Python310_2277_I | ### Python Threading and Lock Management
You 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:
1. Create two threads that both attempt to increment a shared global co... | 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": "",
"prompt_id": "00002277",
"row_id": 2277,
"seed_ids": "[223]"
} | 0.517885 | Docs: Python310_2277 | I | [
"increment_counter",
"multi_threaded_sum"
] | 2 | [
[
"multi_threaded_sum",
"increment_counter"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 948867dcdafaa3b71f251083832e9a1a5209cc40 | f118e0d7204adcff988874ffbbc8c3a141f2ca37 | |||
v1.0 | instruct | Docs | Docs: Pytorch_2289_I | ### Custom Operator with Gradient Check in PyTorch
#### Objective:
You 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:
1. Define and register the custom operation.
2. Implement the gr... | 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": "",
"prompt_id": "00002289",
"row_id": 2289,
"seed_ids": "[51]"
} | 0.502298 | Docs: Pytorch_2289 | I | [
"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 | 5574d27158df9547f6e5bf784d9ab2cd2bbea9f0 | 03b6f3bad773852ba3a31705af738dc357da0e80 | |||
v1.0 | instruct | Docs | Docs: Python310_2310_I | ### Asynchronous Web Scraper
**Objective**: Implement an asynchronous web scraper that fetches data from multiple URLs concurrently and processes the fetched data without blocking the event loop.
**Requirements**:
1. Create an asynchronous function `fetch_url` that takes a URL and fetches its content using an HTTP 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": "",
"prompt_id": "00002310",
"row_id": 2310,
"seed_ids": "[200]"
} | 0.622072 | Docs: Python310_2310 | I | [
"fetch_url",
"process_data",
"async_scraper"
] | 3 | [
[
"async_scraper",
"fetch_url"
],
[
"async_scraper",
"process_data"
]
] | 2 | [
"process_data"
] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 9998247be278127f58a69cbe20769e14ed550183 | c9869228fe36e52ff7ad651d7f52c5f548109f18 | |||
v1.0 | instruct | Docs | Docs: Pandas_2329_I | #### Context
You 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 optimizing memory usage and imp... | 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": "",
"prompt_id": "00002329",
"row_id": 2329,
"seed_ids": "[13]"
} | 0.509514 | Docs: Pandas_2329 | I | [
"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 | e0b640e18d21194e28539f2698d123c789eb86cf | 93f412b6cbd86c047b1f44244b2feb7dc2fdd914 | |||
v1.0 | instruct | Docs | Docs: Python310_2381_I | **Question: Porting Code for Compatibility with Python 2 and 3**
**Objective:**
You 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 division changes, and ensure the code r... | 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": "",
"prompt_id": "00002381",
"row_id": 2381,
"seed_ids": "[70]"
} | 0.467212 | Docs: Python310_2381 | I | [
"read_and_process_file",
"process_content",
"main"
] | 3 | [
[
"read_and_process_file",
"process_content"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7ba97750cf7bf26a61f3afe3df244bb2d78e20fb | 925a6fb3d62a02e257884d2c7f6795f90b2b3e32 | |||
v1.0 | instruct | Docs | Docs: Python310_2513_I | You are tasked with designing an asynchronous event-driven application using Python's `asyncio` library. The application should perform the following operations:
1. Schedule and run multiple asynchronous tasks.
2. Wait for and handle network connections.
3. Use low-level event loop operations to manage the scheduling ... | 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": "",
"prompt_id": "00002513",
"row_id": 2513,
"seed_ids": "[267]"
} | 0.612739 | Docs: Python310_2513 | I | [
"network_server",
"handle_client",
"schedule_tasks",
"main"
] | 4 | [
[
"network_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a74573face74c2e1fe0dc6e7580d17706bdada49 | 32c7228e9092d2709972ebe3898a451876dd82d8 | |||
v1.0 | instruct | Docs | Docs: Python310_2540_I | **Question:**
You 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:
1. Load the specified modules.
2. Serve the generated documentation via an HTTP server.
3. Provide an option to save the docume... | 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": "",
"prompt_id": "00002540",
"row_id": 2540,
"seed_ids": "[240]"
} | 0.52195 | Docs: Python310_2540 | I | [
"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 | f501624efdc6f806f06cd1db91345f9f91b39a5e | 4719d8ac7832156e9f70fc65abd7b2555647e87e | |||
v1.0 | instruct | Docs | Docs: Python310_2565_I | ### Coding Assessment: Exit Handlers
#### Objective:
Write 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.
#### Specifications:
1. **Function Imple... | 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": "",
"prompt_id": "00002565",
"row_id": 2565,
"seed_ids": "[278]"
} | 0.486734 | Docs: Python310_2565 | I | [
"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 | 73c5d2b850a4aabc247bc218b009255fc6e35a96 | c468ca8faa2ffea6154579778582bf108caf73c0 | |||
v1.0 | instruct | Docs | Docs: Pytorch_2582_I | ### PyTorch Distributed Training with Custom Communication Hook
#### Background
Distributed 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 communication hooks that can be... | 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": "",
"prompt_id": "00002582",
"row_id": 2582,
"seed_ids": "[92]"
} | 0.483295 | Docs: Pytorch_2582 | I | [
"compress_gradients",
"custom_comm_hook",
"train",
"main"
] | 4 | [
[
"custom_comm_hook",
"compress_gradients"
]
] | 1 | [] | false | [
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | 13151992536e2626ea1d1b8e9da82866ac04db09 | d9234e4bd6643827d609508493698d1bed6cb293 | |||
v1.0 | instruct | Docs | Docs: Python310_2587_I | #### Objective:
Demonstrate your understanding of the Python `struct` module by implementing functions that handle packing and unpacking of structured binary data.
#### Task:
1. Implement a function `pack_data(format_str, data)` that takes a format string and a tuple of values, and returns a packed bytes object.
2. Im... | 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": "",
"prompt_id": "00002587",
"row_id": 2587,
"seed_ids": "[143]"
} | 0.551632 | Docs: Python310_2587 | I | [
"pack_data",
"unpack_data",
"read_struct",
"write_struct"
] | 4 | [
[
"read_struct",
"unpack_data"
],
[
"write_struct",
"pack_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f01baafbab66e8deb67a3ac66924a715d675b55f | 63b8c439db0e9ff5f83817c6ee9074201d99adc5 | |||
v1.0 | instruct | Docs | Docs: Python310_2588_I | ### Unicode Normalization in Python
**Objective:**
Write 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.
**Details:**
The task demonstrates your understanding of ... | 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": "",
"prompt_id": "00002588",
"row_id": 2588,
"seed_ids": "[71]"
} | 0.569238 | Docs: Python310_2588 | I | [
"normalized_unicode",
"compare_normalized_strings"
] | 2 | [
[
"compare_normalized_strings",
"normalized_unicode"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8be7086683148f2865dbeb63dc726f92430366f2 | 782af112291a38659fced1bd486105435684e21e | |||
v1.0 | instruct | Docs | Docs: Python310_2595_I | **Objective**:
Implement 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 list.
**Function Signature**:
``... | 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": "",
"prompt_id": "00002595",
"row_id": 2595,
"seed_ids": "[347]"
} | 0.755477 | Docs: Python310_2595 | I | [
"factorial",
"parallel_factorial"
] | 2 | [
[
"parallel_factorial",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b1c17b5c175d49bcb6431a78d307547c9c2a2099 | 51e484fb698f1ab4d52c317429482dc3730519d6 | |||
v1.0 | instruct | Docs | Docs: Scikit_2621_I | ### Semi-Supervised Learning with Scikit-Learn
#### Objective:
Implement and evaluate a semi-supervised learning algorithm using Scikit-Learn's `SelfTrainingClassifier` and `LabelPropagation` classes.
#### Background:
You are provided with a partially labeled dataset. Your task is to leverage both the labeled and unl... | 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": "",
"prompt_id": "00002621",
"row_id": 2621,
"seed_ids": "[21]"
} | 0.484781 | Docs: Scikit_2621 | I | [
"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 | b7764f84adaa43e40f17662a1d2da24e76041957 | a3b5ba2ce3e33e6f124c3c40b22500c0998be815 | |||
v1.0 | instruct | Docs | Docs: Python310_2642_I | ### Question: Context-Aware Asynchronous Logging System
You 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 preserved based on the request contex... | 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": "",
"prompt_id": "00002642",
"row_id": 2642,
"seed_ids": "[392]"
} | 0.534975 | Docs: Python310_2642 | I | [
"log_request_id",
"log_message",
"get_logs",
"process_request"
] | 4 | [
[
"process_request",
"get_logs"
],
[
"process_request",
"log_message"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c28b2113b0d62acaa47b099a03763174bbde83bb | f238dd682c97ac0cea52b18ae34990ba5dec37b4 | |||
v1.0 | instruct | Docs | Docs: Pandas_2660_I | You are given a dataset `employee_data.csv` that contains the following columns:
- `EmployeeID`: A unique identifier for each employee.
- `Department`: The department in which the employee works.
- `Position`: The position held by the employee.
- `StartDate`: The date the employee started working.
- `Salary`: The curre... | import pandas as pd
def pivot_salary_data(df: pd.DataFrame) -> pd.DataFrame:
"""
Pivot the dataset to show the average salary for each position within each department.
Parameters:
- df: pd.DataFrame
Returns:
- pd.DataFrame: Pivoted DataFrame with average salaries.
"""
# Explode positi... | import pytest
import pandas as pd
from solution import pivot_salary_data, add_categorical_columns, explode_positions, employee_crosstab, cut_salary_bins
@pytest.fixture
def sample_data():
data = {
'EmployeeID': [101, 102, 103, 104, 105],
'Department': ['Sales', 'IT', 'HR', 'Sales', 'IT'],
'... | [
{
"docstring": "Pivot the dataset to show the average salary for each position within each department.\n\nParameters:\n- df: pd.DataFrame\n\nReturns:\n- pd.DataFrame: Pivoted DataFrame with average salaries.",
"function_declaration": "def pivot_salary_data(df):",
"function_name": "pivot_salary_data",
... | [
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.125 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\n\ndef pivot_salary_data(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Pivot the dataset to show the average salary for each position within e... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00002660",
"row_id": 2660,
"seed_ids": "[6]"
} | 0.723279 | Docs: Pandas_2660 | I | [
"pivot_salary_data",
"add_categorical_columns",
"explode_positions",
"employee_crosstab",
"cut_salary_bins"
] | 5 | [
[
"employee_crosstab",
"explode_positions"
],
[
"pivot_salary_data",
"explode_positions"
]
] | 2 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | bae4bf60d9970e0b512a00865702cae50fc1bde0 | 104b9e63f5668c8f19b82a01c25bad2a1d318e9a | |||
v1.0 | instruct | Docs | Docs: Python310_2690_I | #### Objective
Demonstrate your understanding of the `cProfile` and `pstats` modules by implementing a profiling function and analyzing the profiling results.
#### Problem Statement
You are given a Python script that calculates the nth Fibonacci number using both an iterative and recursive approach. Your task is to:
... | 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": "",
"prompt_id": "00002690",
"row_id": 2690,
"seed_ids": "[142]"
} | 0.614165 | Docs: Python310_2690 | I | [
"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 | f8a3f52d3bb6ccd27306e72111c8215dd5f1f25a | 8dd39fefc2798fd6f071faa6233ce0d6e7ce9b3e | |||
v1.0 | instruct | Docs | Docs: Python310_2743_I | <|Analysis Begin|>
The 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 function calls, such as call count, ... | 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": "",
"prompt_id": "00002743",
"row_id": 2743,
"seed_ids": "[142]"
} | 0.503935 | Docs: Python310_2743 | I | [
"compute_statistics",
"profile_and_analyze",
"optimized_compute_statistics"
] | 3 | [
[
"profile_and_analyze",
"compute_statistics"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2f9d689132f5fa23ae046b8853859478e05a13f5 | 798a22b7d866fa62611bbb2f4d02fa0d0cb0cf54 | |||
v1.0 | instruct | Docs | Docs: Python310_2748_I | **Problem Statement: Data Integrity Verification Utility**
**Objective:**
Create 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 algorithms.
**Function to Imple... | 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": "",
"prompt_id": "00002748",
"row_id": 2748,
"seed_ids": "[225]"
} | 0.681319 | Docs: Python310_2748 | I | [
"verify_file_integrity",
"generate_file_hash"
] | 2 | [
[
"verify_file_integrity",
"generate_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 15a489c2b9d4a7057f54dc49ab6e39ed46cb21b1 | 1183eb3be1bb5db26ab19aac5a89a9a4a8489488 | |||
v1.0 | instruct | Docs | Docs: Python310_2780_I | ### Advanced Python Networking with `asyncio` Streams
**Problem Statement:**
You 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 goal is to implement a function `... | 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": "",
"prompt_id": "00002780",
"row_id": 2780,
"seed_ids": "[182]"
} | 0.614692 | Docs: Python310_2780 | I | [
"handle_client",
"start_http_server"
] | 2 | [
[
"start_http_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b52a4060020c7b2d9bce70428fcb2f728d9c14ed | b559b41135dacc5b9ff0af3748e55902cbd5ccc8 | |||
v1.0 | instruct | Docs | Docs: Pytorch_2829_I | ### PyTorch Coding Assessment Question
**Objective:**
Demonstrate your understanding of PyTorch's torch.func operations and limitations by implementing a function that applies vectorized computations and gradients using pure function transformations.
**Problem Statement:**
Implement a function `batch_mse_gradient` t... | 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": "",
"prompt_id": "00002829",
"row_id": 2829,
"seed_ids": "[136]"
} | 0.527084 | Docs: Pytorch_2829 | I | [
"mse_loss",
"batch_mse_gradient"
] | 2 | [
[
"batch_mse_gradient",
"mse_loss"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 02ea2037d8b0c9268834e3f1080501026045cf53 | 95d9c3d3f345e3b24f155396869428157a74c7c0 | |||
v1.0 | instruct | Docs | Docs: Python310_2882_I | **Question: Implementing Parallel Task Execution with `concurrent.futures`**
**Objective:** To assess your understanding of the `concurrent.futures` module by implementing a solution that uses parallel task execution for a given problem.
**Problem Statement:**
You are given a list of URLs, and your task is to downlo... | 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": "",
"prompt_id": "00002882",
"row_id": 2882,
"seed_ids": "[224]"
} | 0.518098 | Docs: Python310_2882 | I | [
"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 | 924509fd2e52807d06377c1ffc4d87809ffbaa6b | a812dc421af70db98b6f499df841483ee80b690f | |||
v1.0 | instruct | Docs | Docs: Python310_2990_I | **Coding Assessment Question:**
You 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 remotely and print the results.
### ... | 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": "",
"prompt_id": "00002990",
"row_id": 2990,
"seed_ids": "[280]"
} | 0.448603 | Docs: Python310_2990 | I | [
"add",
"subtract",
"multiply",
"run_server"
] | 4 | [
[
"run_server",
"add"
],
[
"run_server",
"multiply"
],
[
"run_server",
"subtract"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 6aa70b7eb49893a069c800eb3240dfb3f5a12ca0 | 8381b89c4c093be45483452a069b241077750d9e | |||
v1.0 | instruct | Docs | Docs: Python310_2996_I | #### Objective
Your 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 memory safety.
#### Task
1. Impl... | 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": "",
"prompt_id": "00002996",
"row_id": 2996,
"seed_ids": "[19]"
} | 0.517124 | Docs: Python310_2996 | I | [
"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 | c6389c80b90f5b3885978675d0c49b8faa12631c | e1211fc750d1738eae1e3d7a1bcd4264c092a771 | |||
v1.0 | instruct | Docs | Docs: Python310_3021_I | ### Asynchronous File Processing with Coroutines
#### Objective
Create 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 a new file. This will test your u... | 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": "",
"prompt_id": "00003021",
"row_id": 3021,
"seed_ids": "[8]"
} | 0.555723 | Docs: Python310_3021 | I | [
"read_and_process_file",
"process_files"
] | 2 | [
[
"process_files",
"read_and_process_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiofiles"
] | false | 761e2b2006e0e39ea0853a0afec9e8561affd8f2 | 2cea23e744e3477589c9e15b4d3c953c3dd94740 | |||
v1.0 | instruct | Docs | Docs: Seaborn_3026_I | ### Question: Advanced Data Visualization with Seaborn
You 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 relationships and distributions acro... | 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": "",
"prompt_id": "00003026",
"row_id": 3026,
"seed_ids": "[3]"
} | 0.718165 | Docs: Seaborn_3026 | I | [
"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 | 223ee837b5e7d1eb7dbfb4e3c8fe8bf93e578b43 | 36e0182d032d83a8c95e3dba1bb434ddf2e5be0a | |||
v1.0 | instruct | Docs | Docs: Python310_3039_I | <|Analysis Begin|>
The `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:
1. **Timeit Function**:
- `timeit.timeit(stmt, setup, timer, number, globals)`: Times th... | 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": "",
"prompt_id": "00003039",
"row_id": 3039,
"seed_ids": "[328]"
} | 0.489139 | Docs: Python310_3039 | I | [
"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 | 71f2082e7113fad0ab1d5fd23b2ea1e1625d3913 | 36ccd34303cb7d29529759d7f5a40e582e304a2a | |||
v1.0 | instruct | Docs | Docs: Python310_3101_I | ### Asyncio Task Scheduling and Synchronization in Python
You 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 while maintaining the order of se... | 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": "",
"prompt_id": "00003101",
"row_id": 3101,
"seed_ids": "[360]"
} | 0.575511 | Docs: Python310_3101 | I | [
"handle_request",
"client_requests"
] | 2 | [
[
"client_requests",
"handle_request"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fd9cca764614614d3db4e44ea4f31ed66ef25a83 | 6a7bfdf8225dd54469665ce6faae8c9e43c0a0d7 | |||
v1.0 | instruct | Docs | Docs: Python310_3104_I | ### Question: Implement a Multi-Threaded Counter using `_thread` Module
#### Objective:
Implement a multi-threaded counter using the `_thread` module. Your task is to create a counter that is incremented by multiple threads. Ensure that the counter is thread-safe, meaning that no two threads should increment the count... | import _thread
import time
# Shared counter variable
counter = 0
# Lock object for synchronizing threads
lock = _thread.allocate_lock()
def increment_counter(n, lock):
"""
Function to increment the global counter n times in a thread-safe manner.
"""
global counter
for _ in range(n):
with ... | import pytest
from solution import start_threads_and_increment
def test_single_thread_small_increment():
assert start_threads_and_increment(1, 10) == 10
def test_single_thread_large_increment():
assert start_threads_and_increment(1, 1000) == 1000
def test_multiple_threads_small_increment():
assert start_... | [
{
"docstring": "Function to increment the global counter n times in a thread-safe manner.",
"function_declaration": "def increment_counter(n, lock):",
"function_name": "increment_counter",
"parameter_list": "(n, lock)"
},
{
"docstring": "Function to start threads and wait for their completio... | [
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 _thread\nimport time\n\n# Shared counter variable\ncounter = 0\n\n# Lock object for synchronizing threads\nlock = _thread.allocate_lock()\n\ndef increment_counte... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00003104",
"row_id": 3104,
"seed_ids": "[223]"
} | 0.554964 | Docs: Python310_3104 | I | [
"increment_counter",
"start_threads_and_increment"
] | 2 | [
[
"start_threads_and_increment",
"increment_counter"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f34f11efeb6f99f0557f6dfb4c36abd3d7a012c3 | f6507803e1843b7d6caf63e5b92094f441d2964d | |||
v1.0 | instruct | Docs | Docs: Python310_3148_I | ### Question: Asynchronous Network Client
You 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.
#### Requirements:
1. Implement an asynchronous function `async_network_client(server_address: str, port... | 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": "",
"prompt_id": "00003148",
"row_id": 3148,
"seed_ids": "[270]"
} | 0.603025 | Docs: Python310_3148 | I | [
"send_message",
"async_network_client"
] | 2 | [
[
"async_network_client",
"send_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3b73c281d371d10e2544b2ce529dc10e790a4c9e | 9119c23bf47f5b9a519d667fd2c507f36772d107 | |||
v1.0 | instruct | Docs | Docs: Python310_3179_I | ### Advanced Python Profiling and Analysis
**Objective**: To assess your understanding of Python's profiling tools "cProfile" and "pstats".
**Problem Statement**:
You are provided with a piece of code that simulates some complex computations. Your task is to:
1. Profile the code using the "cProfile" module.
2. Save ... | 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": "",
"prompt_id": "00003179",
"row_id": 3179,
"seed_ids": "[142]"
} | 0.567009 | Docs: Python310_3179 | I | [
"function_a",
"function_b",
"main",
"profile_main",
"analyze_profiling_data"
] | 5 | [
[
"function_b",
"function_a"
],
[
"profile_main",
"main"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0811c6abb9e1df025d78b21668cc92c50fce6051 | d77450f13054ac1ab3106f1fcf85c95fe9306ebe | |||
v1.0 | instruct | Docs | Docs: Python310_3227_I | ### Python Coding Assessment: Memory Allocation Debugging
#### Objective:
You are required to use the `tracemalloc` module to identify memory leak patterns in a given Python application.
#### Background:
You are provided with a Python application that simulates a memory leak. Your task is to:
1. Identify the lines of... | 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": "",
"prompt_id": "00003227",
"row_id": 3227,
"seed_ids": "[404]"
} | 0.516683 | Docs: Python310_3227 | I | [
"simulate_memory_leak",
"generate_memory_report"
] | 2 | [
[
"generate_memory_report",
"simulate_memory_leak"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c3a44d87dc4a2a132a149d661d3a78c4cf6515f1 | 4cc81fb54c572f2da78adc6484496bf9440ea53f | |||
v1.0 | instruct | Docs | Docs: Python310_3385_I | ### Asynchronous File Downloader with Exception Handling
You 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.
#### Requirements
1. Implement a funct... | 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": "",
"prompt_id": "00003385",
"row_id": 3385,
"seed_ids": "[396]"
} | 0.579621 | Docs: Python310_3385 | I | [
"download_file",
"download_files"
] | 2 | [
[
"download_files",
"download_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 7de92aec3a37647913406ffa1e134dca0deea56a | 6b1a848d022e77676b840b5bb72aaf3897d8a4da | |||
v1.0 | instruct | Docs | Docs: Python310_3406_I | **Challenge: Environment Configuration with the `site` Module**
In 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.
### Task
1. **Directory Validation Function:**
... | 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": "",
"prompt_id": "00003406",
"row_id": 3406,
"seed_ids": "[147]"
} | 0.516614 | Docs: Python310_3406 | I | [
"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 | d43ea39c914c74bf106f829bda1f5ffc79885f85 | 097496b5c27cb7f3c5a694cb0e56f8af366497b0 | |||
v1.0 | instruct | Docs | Docs: Python310_3449_I | ### HMAC Coding Challenge
#### Objective
Implement a secure messaging system that uses HMAC for message authentication and integrity checking. You are required to write functions to generate an HMAC for a message, update the HMAC with an additional message, retrieve the hexadecimal digest, and verify a received messag... | import hmac
import hashlib
def generate_hmac(key: bytes, msg: bytes, digest_name: str) -> hmac.HMAC:
"""
Creates an HMAC object using the provided key, message, and digest algorithm.
"""
return hmac.new(key, msg, getattr(hashlib, digest_name))
def update_hmac(hmac_obj: hmac.HMAC, msg: bytes) -> None:
... | import pytest
from solution import generate_hmac, update_hmac, get_hex_digest, verify_message
def test_generate_hmac():
key = b'secret'
msg = b'Test message'
digest_name = 'sha256'
hmac_obj = generate_hmac(key, msg, digest_name)
assert isinstance(hmac_obj, hmac.HMAC)
def test_update_hmac():
ke... | [
{
"docstring": "Creates an HMAC object using the provided key, message, and digest algorithm.",
"function_declaration": "def generate_hmac(key, msg, digest_name):",
"function_name": "generate_hmac",
"parameter_list": "(key, msg, digest_name)"
},
{
"docstring": "Updates the HMAC object with t... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hmac\nimport hashlib\n\ndef generate_hmac(key: bytes, msg: bytes, digest_name: str) -> hmac.HMAC:\n \"\"\"\n Generates an HMAC object for the given message... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00003449",
"row_id": 3449,
"seed_ids": "[298]"
} | 0.771234 | Docs: Python310_3449 | I | [
"generate_hmac",
"update_hmac",
"get_hex_digest",
"verify_message"
] | 4 | [
[
"verify_message",
"generate_hmac"
],
[
"verify_message",
"get_hex_digest"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e89e67b19b9066bd4defb37c1bb47b67602ccd71 | 5b92cf89ee388799ddf1729048d289dfd5e3732a | |||
v1.0 | instruct | Docs | Docs: Python310_3452_I | #### Objective
You 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.
#### Problem Statement
Write a function `run_multiple_c... | 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": "",
"prompt_id": "00003452",
"row_id": 3452,
"seed_ids": "[264]"
} | 0.73038 | Docs: Python310_3452 | I | [
"run_command",
"run_multiple_commands"
] | 2 | [
[
"run_multiple_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2ea62a078fc5b929b01692eb802b5dea117794ee | 9fd38f8f90d6aa3634b79c71a206648115dee471 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.