version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | complete | Docs | Docs: Python310_32052_C | import asyncio
clients = {}
async def broadcast_message(message: str, writer: asyncio.StreamWriter) -> None:
"""Send a message to all connected clients except the sender."""
# Implementation here
async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
"""Manage the in... | import asyncio
clients = {}
async def broadcast_message(message: str, writer: asyncio.StreamWriter) -> None:
for client_writer in clients.values():
if client_writer != writer:
client_writer.write(message.encode())
await client_writer.drain()
async def handle_client(reader: asyncio... | import pytest
import asyncio
from solution import start_server, handle_client, broadcast_message
@pytest.mark.asyncio
async def test_server_start():
host = '127.0.0.1'
port = 12345
server = await start_server(host, port)
assert server.sockets, "Server failed to start"
@pytest.mark.asyncio
async de... | [] | [
1,
1,
1,
1,
0,
0,
1,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nclients = {}\n\nasync def broadcast_message(message: str, writer: asyncio.StreamWriter) -> None:\n for client_writer in clients.values():\n ... | trial_gpt4o_0 | {
"original_instruction": "**Objective**: Write an asynchronous program that demonstrates your understanding of the `asyncio` event loop and its various methods for handling callbacks, tasks, and network connections.\n\n**Problem**:\n\nCreate a Python script using the `asyncio` library to implement a simple chat serv... | 0.565872 | Docs: Python310_32052 | C | [
"broadcast_message",
"handle_client",
"start_server",
"main"
] | 4 | [
[
"handle_client",
"broadcast_message"
],
[
"start_server",
"handle_client"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4867252328cbd2b8ad84e10da7509a72fd9b5d00 | 4eec993c62f84667dfdfa323205be6ebbb601b7a | |||
v1.0 | complete | Docs | Docs: Python310_31972_C | import asyncio
async def fetch_content(url: str) -> str:
"""Simulate a network request to fetch content from a URL."""
await asyncio.sleep(random.randint(1, 3)) # Simulate network delay
return f"<html>Content from {url}</html>"
async def fetch_html(urls: list[str]) -> dict[str, str]:
""" Fetch HTML c... | import asyncio
import random
async def fetch_content(url: str) -> str:
await asyncio.sleep(random.randint(1, 3)) # Simulate network delay
return f"<html>Content from {url}</html>"
async def fetch_html(urls: list[str]) -> dict[str, str]:
async def _fetch_and_store(url):
content = await fetch_conte... | import pytest
import asyncio
from solution import fetch_html
@pytest.mark.asyncio
async def test_fetch_html_single_url():
urls = ["http://example.com"]
content = await fetch_html(urls)
assert len(content) == 1
assert "http://example.com" in content
assert content["http://example.com"].startswith("<... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\n\nasync def fetch_content(url: str) -> str:\n await asyncio.sleep(random.randint(1, 3)) # Simulate network delay\n return f\"<html... | trial_gpt4o_7 | {
"original_instruction": "### Asynchronous Web Scraping Simulation\n\n**Objective**: Utilize the asyncio library to simulate an asynchronous web scraping task. This task will test your ability to handle concurrent execution, manage asyncio tasks, and synchronize the output.\n\n**Problem Statement**:\nYou are tasked ... | 0.620004 | Docs: Python310_31972 | C | [
"fetch_content",
"fetch_html"
] | 2 | [
[
"fetch_html",
"fetch_content"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a4ddfd154b66eee241314f4e51b548a5aa7ec370 | 54a53a047c946f964f023b8bec6948e3e993ce63 | |||
v1.0 | complete | Docs | Docs: Python310_32489_C | import asyncio
import signal
async def handle_client(reader, writer):
""" Handle the client connection and echo received messages back to the client.
Arg:
reader: StreamReader object to read data from client.
writer: StreamWriter object to write data to client.
"""
pass
async def start... | import asyncio
import signal
async def handle_client(reader, writer):
addr = writer.get_extra_info('peername')
print(f"Connected to {addr}")
try:
while True:
data = await reader.read(100)
if not data:
break
message = data.decode()
pri... | import asyncio
import pytest
from solution import handle_client, start_server, client
@pytest.mark.asyncio
async def test_echo_server():
server = await asyncio.start_server(handle_client, '127.0.0.1', 8888)
addr = server.sockets[0].getsockname()
async with server:
message = "Hello, Asyncio!"
... | [
{
"docstring": null,
"function_declaration": "def ask_exit(signame, loop):",
"function_name": "ask_exit",
"parameter_list": "(signame, loop)"
}
] | [
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\nimport signal\nimport sys\n\nasync def handle_client(reader, writer):\n try:\n addr = writer.get_extra_info('peername')\n print(f\"Conn... | trial_gpt4o_1 | {
"original_instruction": "### Advanced Python Networking with asyncio\n\n**Objective:** \n\nDemonstrate your ability to use the asyncio library to handle multiple asynchronous tasks, manage network connections, and schedule callbacks efficiently.\n\n**Question:**\n\nYou are tasked with implementing a simple echo ser... | 0.581398 | Docs: Python310_32489 | C | [
"handle_client",
"start_server",
"ask_exit",
"client",
"main"
] | 5 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9137d82dd4a09bfad5490f3ad00034dda13a0fb8 | e18dcc654a550133871ed3f131c4aa8d194d7662 | |||
v1.0 | complete | Docs | Docs: Python310_32529_C | import sqlite3
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"{self.x},{self.y}"
@classmethod
def from_string(cls, string):
x, y = map(float, string.split(','))
return cls(x, y)
def adapt_point(point):
return str(p... | import sqlite3
import re
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"{self.x},{self.y}"
@classmethod
def from_string(cls, string):
x, y = map(float, string.split(','))
return cls(x, y)
def adapt_point(point):
re... | import os
import pytest
import sqlite3
from solution import manage_employee_database, Point
def setup_module(module):
"""Module setup/teardown for testing the database."""
# Remove the database file if it exists to ensure a clean state for tests.
try:
os.remove('company.db')
except OSError:
... | [] | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sqlite3\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __repr__(self):\n return f\"Point({self.x}, {sel... | trial_gpt4o_6 | {
"original_instruction": "### SQLite Database Management with Custom Types and Transactions\n\nIn this task, you will create and manage an SQLite database using Python's `sqlite3` module. You need to demonstrate advanced understanding including transaction control, error handling, and custom type adapters.\n\n#### T... | 0.548459 | Docs: Python310_32529 | C | [
"adapt_point",
"convert_point",
"manage_employee_database"
] | 3 | [
[
"manage_employee_database",
"adapt_point"
],
[
"manage_employee_database",
"convert_point"
]
] | 2 | [] | false | [
"Point"
] | true | pytest | true | [] | true | 3208df3e3be76e1129869aa3e1ae886e0e4ef7be | 5dab87d5413510af3d7094f6ba0589adf0bf8e5b | |||
v1.0 | complete | Docs | Docs: Python310_32404_C | from typing import List, Dict, Optional
import imghdr
def detect_custom_format(h: bytes) -> Optional[str]:
"""
Detects the custom image format by checking for a specific header signature.
Parameters:
h (bytes): Byte stream to check.
Returns:
Optional[str]: 'custom' if the ... | from typing import List, Dict, Optional
import imghdr
def detect_custom_format(h: bytes) -> Optional[str]:
"""
Detects the custom image format by checking for a specific header signature.
Parameters:
h (bytes): Byte stream to check.
Returns:
Optional[str]: 'custom' if the ... | import os
import pytest
import imghdr
from solution import detect_custom_format, categorize_images
# Create test image files for testing
def create_test_image_files():
files = {
'image1.png': b'\x00\x00\x00\x00',
'image2.jpeg': b'\x00\x00\x00\x00',
'custom_image': b'\x89PNGsomething'
}
... | [
{
"docstring": "Detects the custom image format by checking for a specific header signature.\n\nParameters:\n h (bytes): Byte stream to check.\n \nReturns:\n Optional[str]: 'custom' if the signature matches, otherwise None.",
"function_declaration": "def detect_custom_format(h):",
"function_nam... | [
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, Dict, Optional\nimport imghdr\n\ndef detect_custom_format(h: bytes) -> Optional[str]:\n \"\"\"\n Detects if the byte stream corresponds t... | trial_gpt4o_2 | {
"original_instruction": "#### Objective:\nDemonstrate understanding of the `imghdr` module and the ability to extend its functionality by implementing custom image type detection logic.\n\n#### Problem Statement:\n\nYou are tasked with developing a utility to process a list of image files, determine their types, an... | 0.601295 | Docs: Python310_32404 | C | [
"detect_custom_format",
"categorize_images"
] | 2 | [
[
"categorize_images",
"detect_custom_format"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 61920c0a798600e7de17f809b43e19a045281e48 | 42061c2f39bf88aeef0987493343f6fbdcd3cd91 | |||
v1.0 | complete | Docs | Docs: Pytorch_32651_C | def set_reproducibility(seed=0):
"""Sets the seeds for torch, random, and numpy to ensure reproducibility."""
torch.manual_seed(seed)
random.seed(seed)
np.random.seed(seed)
torch.backends.cudnn.benchmark = False
torch.use_deterministic_algorithms(True)
class SimpleNN(torch.nn.Module):
"""Si... | import torch
import random
import numpy as np
# Step 1: Setting up reproducibility
def set_reproducibility(seed=0):
torch.manual_seed(seed)
random.seed(seed)
np.random.seed(seed)
torch.backends.cudnn.benchmark = False
torch.use_deterministic_algorithms(True)
set_reproducibility(42)
# Step 2: Defi... | def test_reproducible_pipeline():
output1 = run_pipeline()
output2 = run_pipeline()
assert torch.equal(output1, output2), "Outputs are not reproducible!" | [] | [
0,
0,
1,
1,
1,
1,
1,
1,
1
] | 7 | easy | 0.778 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport random\nimport numpy as np\n\n# Step 1: Setting up reproducibility\ndef set_reproducibility(seed=0):\n torch.manual_seed(seed)\n random.seed(... | trial_gpt4o_8 | {
"original_instruction": "### PyTorch Reproducibility Challenge\n\n**Objective:**\nThe goal of this task is to create a small PyTorch pipeline that includes both deterministic and nondeterministic operations. You will then configure the pipeline to ensure reproducible results following the provided guidelines.\n\n**... | 0.561765 | Docs: Pytorch_32651 | C | [
"set_reproducibility",
"run_pipeline"
] | 2 | [
[
"run_pipeline",
"set_reproducibility"
]
] | 1 | [] | false | [
"SimpleNN"
] | true | pytest | false | [
"numpy",
"torch"
] | false | 3a1b0337832e34cdc49f0078f9fe7bb0c890c247 | a78b9965f2c80fa2918a9e68be47862a328e8e2c | |||
v1.0 | complete | Docs | Docs: Python310_32077_C | from multiprocessing import Pool
from typing import List, Tuple, Any, Dict
def task_scheduler(tasks: List[Tuple[Any, Tuple]], num_workers: int) -> Dict[int, Any]:
""" Implement a Task Scheduling System using Python's Multiprocessing.
>>> from typing import Callable
>>> def add(a: int, b: int) -> int:
>... | from multiprocessing import Pool
def execute_task(task):
func, args = task
return func(*args)
def task_scheduler(tasks, num_workers):
with Pool(processes=num_workers) as pool:
task_indices = list(range(len(tasks)))
results = pool.starmap(execute_task, [(tasks[i],) for i in task_indices])
... | from solution import task_scheduler
def add(a, b):
return a + b
def multiply(a, b):
return a * b
def test_task_scheduler():
tasks = [
(add, (1, 2)),
(multiply, (2, 3)),
(add, (5, 3)),
(multiply, (8, 7))
]
num_workers = 2
results = task_scheduler(tasks, num... | [
{
"docstring": null,
"function_declaration": "def execute_task(task):",
"function_name": "execute_task",
"parameter_list": "(task)"
},
{
"docstring": null,
"function_declaration": "def task_scheduler(tasks, num_workers):",
"function_name": "task_scheduler",
"parameter_list": "(ta... | [
1,
1,
0,
1,
1,
0,
1,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from multiprocessing import Pool\n\ndef task_worker(task):\n func, args = task\n return func(*args)\n\ndef task_scheduler(tasks, num_workers):\n with Pool(num_... | trial_gpt4o_3 | {
"original_instruction": "## Question: Implement a Task Scheduling System using Python's Multiprocessing\n\n### Objective:\nYou will develop a task scheduling system that will distribute tasks to worker processes using Python's `multiprocessing` package. The system will read a list of tasks, execute them concurrentl... | 0.738507 | Docs: Python310_32077 | C | [
"execute_task",
"task_scheduler"
] | 2 | [
[
"task_scheduler",
"execute_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9737f01539abf9f686563b07dc487329166523dd | 6620c47a149f01d79f469cccd77d171da7779419 | |||
v1.0 | complete | Docs | Docs: Pytorch_32600_C | import torch
import torch.nn as nn
import torch.optim as optim
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, Dataset, Subset
# Define a simple neural network model
class SimpleModel(nn.Module):
def __init__(self):
supe... | import torch
import torch.nn as nn
import torch.optim as optim
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, Dataset, Subset
import numpy as np
# Define a simple neural network model
class SimpleModel(nn.Module):
def __init__(... | import torch
from solution import SimpleModel, CustomDataset, split_dataset
def test_model_structure():
model = SimpleModel()
x = torch.randn(2, 10)
y = model(x)
assert y.shape == (2, 1), "Model output shape is incorrect."
def test_custom_dataset():
dataset = CustomDataset(size=10)
assert len... | [] | [
1,
1,
0,
1,
0,
0,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom t... | trial_gpt4o_0 | {
"original_instruction": "### Distributed Training with Uneven Inputs\n\n**Objective:**\nImplement a simple distributed training setup using PyTorch, where the dataset is not evenly divisible among the processors. You are required to manage these uneven inputs using the provided classes `Join`, `Joinable`, and `Join... | 0.543679 | Docs: Pytorch_32600 | C | [
"split_dataset",
"train"
] | 2 | [
[
"train",
"split_dataset"
]
] | 1 | [] | false | [
"SimpleModel",
"CustomDataset"
] | true | pytest | true | [
"numpy",
"torch"
] | false | 43ceca176077caadd625dfbe345aa49e378f129a | a124186a20de05c3bb9aeba19e4c5c756ae56415 | |||
v1.0 | complete | Docs | Docs: Python310_32200_C | import math
def normal_cdf(x: float) -> float:
"""
Calculates the Cumulative Distribution Function (CDF) for a standard normal distribution at point x.
Examples:
>>> normal_cdf(0)
0.5
>>> normal_cdf(1.96)
0.975
>>> normal_cdf(-1.96)
0.025
>>> normal_cdf(3)
0.998650
... | import math
def normal_cdf(x):
"""
Calculates the Cumulative Distribution Function (CDF) for a standard normal distribution at point x.
"""
return (1 + math.erf(x / math.sqrt(2))) / 2
def inverse_normal_cdf(p, tolerance=1e-5):
"""
Calculates the inverse CDF (quantile function) for a standard n... | from solution import normal_cdf, inverse_normal_cdf, binomial_pmf, binomial_cdf
def test_normal_cdf():
assert math.isclose(normal_cdf(0), 0.5)
assert math.isclose(normal_cdf(1.96), 0.975, abs_tol=1e-3)
assert math.isclose(normal_cdf(-1.96), 0.025, abs_tol=1e-3)
assert math.isclose(normal_cdf(3), 0.9986... | [
{
"docstring": "Calculates the Cumulative Distribution Function (CDF) for a standard normal distribution at point x.",
"function_declaration": "def normal_cdf(x):",
"function_name": "normal_cdf",
"parameter_list": "(x)"
},
{
"docstring": "Calculates the inverse CDF (quantile function) for a ... | [
0,
0,
1,
1,
0,
0,
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 math\n\ndef normal_cdf(x):\n return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0\n\ndef inverse_normal_cdf(p, tolerance=1e-5):\n if p <= 0 or p >= 1:\n ... | trial_gpt4o_6 | {
"original_instruction": "### Problem: Statistical Distribution Calculations\n\nIn this task, you are required to implement a few helper functions that utilize the `math` module functions to perform calculations related to statistical distributions. You will need to implement the following functions:\n\n1. **normal_... | 0.520235 | Docs: Python310_32200 | C | [
"normal_cdf",
"inverse_normal_cdf",
"binomial_pmf",
"binomial_cdf"
] | 4 | [
[
"binomial_cdf",
"binomial_pmf"
],
[
"inverse_normal_cdf",
"normal_cdf"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9de22db10897681c1869bf99f630cd9a2dd5fe7b | 1fe7e4a92cdf1b359dcfe736c64b2d04f87a71d2 | |||
v1.0 | complete | Docs | Docs: Python310_32730_C | import curses
def display_menu(stdscr):
""" Display a menu and allow navigation using arrow keys.
Args:
stdscr: The main window object.
"""
pass
def option_selected(stdscr, option):
""" Display the selected option message.
Args:
stdscr: The main window object.
option: T... | import curses
def display_menu(stdscr):
curses.curs_set(0) # Hide the cursor
stdscr.clear()
k = 0
current_row = 0
menu = ['Option 1', 'Option 2', 'Option 3', 'Exit']
while True:
stdscr.clear()
h, w = stdscr.getmaxyx()
for idx, row in enumerate(menu):
x = ... | # It's challenging to write automated tests for curses applications since they interact with the terminal.
# Usually, such applications are tested manually or with end-to-end testing tools designed for terminal applications.
# However, we can test some logic components without relying on curses.
from solution import d... | [
{
"docstring": null,
"function_declaration": "def display_menu(stdscr):",
"function_name": "display_menu",
"parameter_list": "(stdscr)"
},
{
"docstring": null,
"function_declaration": "def option_selected(stdscr, option):",
"function_name": "option_selected",
"parameter_list": "(... | [
0,
1,
0,
0,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import curses\n\ndef draw_menu(stdscr, current_row_idx):\n \"\"\"Draws the menu and highlights the current selected row.\"\"\"\n stdscr.clear()\n h, w = stdscr... | trial_gpt4o_1 | {
"original_instruction": "#### Objective:\nYou are asked to create a simple text-based GUI interface using the Python `curses` module. This interface should allow a user to navigate through a menu using the arrow keys, select an option, and display corresponding information.\n\n#### Task:\nImplement a Python program... | 0.360761 | Docs: Python310_32730 | C | [
"display_menu",
"option_selected",
"main"
] | 3 | [
[
"display_menu",
"option_selected"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d53fcf0dd653e3b8dcc67e6f17b59b848b40d585 | c9654774ce4de5c51af77408c333a5ba5de2dea6 | |||
v1.0 | complete | Docs | Docs: Python310_32214_C | import asyncio
async def platform_specific_io_handler(source_file_path: str, destination_file_path: str) -> bool:
"""
Asynchronous Task Scheduler: Platform-Specific I/O Handlers
================================================
Create an asynchronous Python function that schedules a task to perform non-... | import asyncio
import platform
import selectors
async def read_file_async(file_path):
loop = asyncio.get_running_loop()
with open(file_path, 'rb') as f:
return await loop.run_in_executor(None, f.read)
async def write_file_async(file_path, data):
loop = asyncio.get_running_loop()
with open(file... | import asyncio
import tempfile
import os
from solution import platform_specific_io_handler
def create_temp_file(content):
tmp_file = tempfile.NamedTemporaryFile(delete=False)
tmp_file.write(content)
tmp_file.close()
return tmp_file.name
def test_io_handler_success():
src_content = b"Hello, World!"... | [] | [
1,
0,
0,
1,
1,
0,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport platform\nimport selectors\nimport os\nfrom asyncio import StreamReader, StreamWriter\n\nasync def platform_specific_io_handler(source_file_path:... | trial_gpt4o_4 | {
"original_instruction": "### Asynchronous Task Scheduler: Platform-Specific I/O Handlers\n\n#### Objective\nCreate an asynchronous Python function that schedules a task to perform non-blocking I/O operations based on the platform-specific capabilities and limitations. The function should read data from a file and w... | 0.534694 | Docs: Python310_32214 | C | [
"read_file_async",
"write_file_async",
"platform_specific_io_handler"
] | 3 | [
[
"platform_specific_io_handler",
"read_file_async"
],
[
"platform_specific_io_handler",
"write_file_async"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 729bba3a256fd2d4497a9dd3418b9374444e9eda | cd096bf0745af1fd9542275ff6ffb8d92ddbd23a | |||
v1.0 | complete | Docs | Docs: Python310_31208_C | import random
import math
from collections import Counter
def generate_random_sequence(length: int, distribution: str, params: dict) -> list:
"""
Generates a sequence of random numbers based on the specified distribution and parameters.
Parameters:
- length (int): The number of random numbers to gener... | import random
import math
from collections import Counter
def generate_random_sequence(length, distribution, params):
"""
Generates a sequence of random numbers based on the specified distribution and parameters.
Parameters:
- length (int): The number of random numbers to generate.
- distribution ... | from solution import generate_random_sequence, analyze_sequence, simulate_and_analyze
def test_generate_random_sequence_uniform():
length = 1000
params = {'a': 0, 'b': 1}
sequence = generate_random_sequence(length, 'uniform', params)
assert len(sequence) == length
assert all(0 <= x <= 1 for x in se... | [
{
"docstring": "Generates a sequence of random numbers based on the specified distribution and parameters.\n\nParameters:\n- length (int): The number of random numbers to generate.\n- distribution (str): The type of distribution to use. One of 'uniform', 'normal', 'exponential', or 'binary'.\n- params (dict): P... | [
0,
1,
1,
1,
1,
1,
0,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport math\nfrom collections import Counter\n\ndef generate_random_sequence(length, distribution, params):\n \"\"\"\n Generates a sequence of rand... | trial_gpt4o_9 | {
"original_instruction": "**Title:** Implement a Pseudo-Random Number Sequence Simulation and Analysis Tool\n\n**Objective:**\nTo assess the student's ability to utilize the Python `random` module to generate and analyze pseudo-random number sequences and to simulate probability distributions.\n\n**Problem Statement... | 0.690309 | Docs: Python310_31208 | C | [
"generate_random_sequence",
"analyze_sequence",
"simulate_and_analyze"
] | 3 | [
[
"simulate_and_analyze",
"analyze_sequence"
],
[
"simulate_and_analyze",
"generate_random_sequence"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 91c756bf381acf91d630c7184956bbcd0ad0cffc | 943071de7761eff85f61ab29a85131a9299b4123 | |||
v1.0 | complete | Docs | Docs: Python310_32513_C | import hashlib
import hmac
import secrets
import base64
def generate_secure_hash(message: str, algorithm: str = 'sha256') -> str:
""" Returns a secure hash of the given message using the specified hashing algorithm.
Parameters:
message (str): The message to hash.
algorithm (str): The hashing algorithm ... | import hashlib
import hmac
import secrets
import base64
def generate_secure_hash(message: str, algorithm: str = 'sha256') -> str:
"""
Returns a secure hash of the given message using the specified hashing algorithm.
:param message: The message to hash.
:param algorithm: The hashing algorithm to us... | import pytest
from solution import generate_secure_hash, create_hmac, verify_hmac, generate_secure_token
def test_generate_secure_hash():
message = "This is a test message."
hash_sha256 = generate_secure_hash(message, 'sha256')
assert hash_sha256 == hashlib.sha256(message.encode('utf-8')).hexdigest()
... | [
{
"docstring": "Returns a secure hash of the given message using the specified hashing algorithm.\n\n:param message: The message to hash.\n:param algorithm: The hashing algorithm to use (default 'sha256').\n:return: Hexadecimal digest of the hashed message.",
"function_declaration": "def generate_secure_has... | [
0,
0,
0,
0,
1,
1,
1,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\nimport hmac\nimport secrets\nimport base64\n\ndef generate_secure_hash(message: str, algorithm: str = 'sha256') -> str:\n \"\"\"\n Generates a sec... | trial_gpt4o_6 | {
"original_instruction": "### Coding Assessment: Secure Message Transmission\n\n#### Objective:\nImplement a secure message transmission module in Python using the cryptographic services provided by `hashlib`, `hmac`, and `secrets`. Your task is to write functions that:\n\n1. **Generate Secure Hash**: Create a secur... | 0.84066 | Docs: Python310_32513 | C | [
"generate_secure_hash",
"create_hmac",
"verify_hmac",
"generate_secure_token"
] | 4 | [
[
"verify_hmac",
"create_hmac"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | df7d461ef9c71e9d207165383ebe772b61864bb5 | 0821582a78416112a7f2ad7898324f28264e03c8 | |||
v1.0 | complete | Docs | Docs: Python310_31788_C | import sys
import getopt
def parse_arguments(args):
""" Parse command-line arguments using getopt.
Supported options:
-h, --help show this help message and exit
-v enable verbose mode
-o FILE, --output=FILE specify the output file
--condition=VALUE set ... | import sys
import getopt
def parse_arguments(args):
shortopts = "hvo:"
longopts = ["help", "output=", "condition="]
try:
opts, remaining_args = getopt.getopt(args, shortopts, longopts)
except getopt.GetoptError as err:
print(str(err))
display_help()
sys.exit(2)
opti... | import pytest
from solution import parse_arguments, display_help
def test_parse_help_option(capsys):
with pytest.raises(SystemExit): # Since help option will exit the script
parse_arguments(["-h"])
captured = capsys.readouterr()
assert "Usage: script.py [options]" in captured.out
with pyt... | [
{
"docstring": null,
"function_declaration": "def parse_arguments(args):",
"function_name": "parse_arguments",
"parameter_list": "(args)"
},
{
"docstring": null,
"function_declaration": "def display_help():",
"function_name": "display_help",
"parameter_list": "()"
}
] | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nimport getopt\n\ndef parse_arguments(args):\n shortopts = \"hvo:\"\n longopts = [\"help\", \"output=\", \"condition=\"]\n try:\n opts, remai... | trial_gpt4o_0 | {
"original_instruction": "**Question: Implement a Command-Line Tool Using getopt**\n\n---\n\n### Description\n\nYou are required to implement a Python command-line tool that processes a series of arguments using the `getopt` module. The tool will support both short and long options for displaying help, verbosity, sp... | 0.497722 | Docs: Python310_31788 | C | [
"parse_arguments",
"display_help"
] | 2 | [
[
"parse_arguments",
"display_help"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0b4d23515b906f50a41e4ca235d8a1a22921e108 | b6c710b9b65e0cd323ac62f7889d9d748e3ba8dc | |||
v1.0 | complete | Docs | Docs: Python310_32944_C | import asyncio
import random
async def create_task(task_id: int) -> None:
"""
Creates a task that prints a start message, waits for a random duration,
and then prints a completion message.
"""
pass
async def task_manager(num_tasks: int, timeout: int) -> None:
"""
Manages and runs a specifi... | import asyncio
import random
async def create_task(task_id: int) -> None:
"""
Creates a task that prints a start message, waits for a random duration,
and then prints a completion message.
"""
print(f"Task {task_id} started.")
await asyncio.sleep(random.randint(1, 5))
print(f"Task {task_id}... | import asyncio
from solution import create_task, task_manager, distribute_tasks
async def test_create_task():
await create_task(1)
async def test_task_manager():
await task_manager(5, 10)
async def test_worker():
queue = asyncio.Queue()
await queue.put(1)
task = asyncio.create_task(worker(queue))... | [
{
"docstring": null,
"function_declaration": "def main():",
"function_name": "main",
"parameter_list": "()"
}
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\n\nasync def create_task(task_id: int) -> None:\n \"\"\"\n Simulates a task by printing a start message, sleeping for a random durat... | trial_gpt4o_5 | {
"original_instruction": "## Coding Assessment Question\n\n### Objective\nWrite a Python program that simulates a simple task management system using asyncio. Your program should create multiple tasks, manage their execution with timeouts, and use a FIFO queue to distribute tasks among workers.\n\n### Requirements\n... | 0.588307 | Docs: Python310_32944 | C | [
"create_task",
"task_manager",
"worker",
"distribute_tasks",
"main"
] | 5 | [
[
"distribute_tasks",
"worker"
],
[
"task_manager",
"create_task"
],
[
"worker",
"create_task"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ce2780df54815d4a37f85a3e5f44761b293beb00 | e1fc6c0aed1480a9b367ca0c247520ec040e9e3f | |||
v1.0 | complete | Docs | Docs: Python310_32673_C | import argparse
import math
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:
raise ValueError("Cannot divide by zero")
return x / y
def exp(x, y):
return x ** y
def sqrt(x):
if x < 0:
raise ValueE... | import argparse
import math
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:
raise ValueError("Cannot divide by zero")
return x / y
def exp(x, y):
return x ** y
def sqrt(x):
if x < 0:
raise ValueE... | import pytest
from solution import add, subtract, multiply, divide, exp, sqrt, process_operation
def test_add():
assert add(5, 3) == 8
assert add(-1, 1) == 0
def test_subtract():
assert subtract(5, 3) == 2
assert subtract(-1, 1) == -2
def test_multiply():
assert multiply(5, 3) == 15
assert mu... | [
{
"docstring": null,
"function_declaration": "def add(x, y):",
"function_name": "add",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def subtract(x, y):",
"function_name": "subtract",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"fu... | [
0,
1,
1,
1,
0,
0,
1,
0,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import argparse\nimport math\nimport sys\n\ndef add(x, y):\n return x + y\n\ndef subtract(x, y):\n return x - y\n\ndef multiply(x, y):\n return x * y\n\ndef di... | trial_gpt4o_3 | {
"original_instruction": "### Command-Line Calculator\n\n#### Objective\nDesign and implement a command-line calculator using the `argparse` module. The calculator should support basic arithmetic operations, advanced mathematical functions, and batch processing through input files.\n\n#### Task\n1. Design an argumen... | 0.614861 | Docs: Python310_32673 | C | [
"add",
"subtract",
"multiply",
"divide",
"exp",
"sqrt",
"process_operation",
"main"
] | 8 | [
[
"process_operation",
"add"
],
[
"process_operation",
"divide"
],
[
"process_operation",
"exp"
],
[
"process_operation",
"multiply"
],
[
"process_operation",
"sqrt"
],
[
"process_operation",
"subtract"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | bfbcfe10cdd43fb95ee0c96a3cfaaec2d87909b2 | 436b7e6eb2968cfa756aa529ba545dcd39f2084d | |||
v1.0 | complete | Docs | Docs: Python310_33017_C | import urllib.parse
import ipaddress
def hostname_to_ip(hostname):
# This is a stub function, the real implementation will be provided during evaluation.
return None
def categorize_urls(urls: list[str]) -> dict[str, list[str]]:
"""
Validates a list of URLs and categorizes them based on their IP addre... | import urllib.parse
import ipaddress
def hostname_to_ip(hostname):
# This is a stub function, the real implementation will be provided during evaluation.
# Here we return some hardcoded values for the sake of example.
if hostname == "example.com":
return "93.184.216.34" # Public IP
elif hostna... | from solution import categorize_urls
def test_categorize_urls():
urls = [
"http://example.com",
"http://192.168.1.1",
"ftp://10.0.0.5/resource",
"http://invalidhostname"
]
result = categorize_urls(urls)
assert result == {
"Private": ["http://192.168.1.1", "ftp://... | [
{
"docstring": null,
"function_declaration": "def hostname_to_ip(hostname):",
"function_name": "hostname_to_ip",
"parameter_list": "(hostname)"
},
{
"docstring": null,
"function_declaration": "def categorize_urls(urls):",
"function_name": "categorize_urls",
"parameter_list": "(ur... | [
1,
0,
1,
0,
1,
1,
1,
1,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import urllib.parse\nimport ipaddress\n\ndef hostname_to_ip(hostname):\n # Placeholder function\n # This function should resolve the hostname to an IP address.\n ... | trial_gpt4o_7 | {
"original_instruction": "**Coding Assessment Question:**\n\n### URL Validation and IP Address Categorization\n\nYour task is to implement a Python function that validates a list of URLs and categorizes them based on their IP addresses. You must use Python's `urllib.parse` for URL components parsing and `ipaddress` ... | 0.783459 | Docs: Python310_33017 | C | [
"hostname_to_ip",
"categorize_urls"
] | 2 | [
[
"categorize_urls",
"hostname_to_ip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6eca0ab88e0f16daff5854022647e228c102324a | 75c8247b24fd59375febbefadc5ebf0723236247 | |||
v1.0 | complete | Docs | Docs: Python310_32306_C | import turtle
def draw_line():
turtle.forward(100)
def draw_square():
for _ in range(4):
turtle.forward(50)
turtle.right(90)
def draw_circle():
turtle.circle(30)
def clear_screen():
turtle.clear()
def quit_program():
turtle.bye()
def setup_drawing_program():
"""
Sets up... | import turtle
def draw_line():
turtle.forward(100)
def draw_square():
for _ in range(4):
turtle.forward(50)
turtle.right(90)
def draw_circle():
turtle.circle(30)
def clear_screen():
turtle.clear()
def quit_program():
turtle.bye()
def setup_drawing_program():
# Set up turtle... | # Note: Testing GUI and interactive programs like turtle is challenging with standard unit tests.
# Here, we define mock functions to ensure drawing functions are called correctly.
# These tests need to be run in an interactive Python environment where turtle graphics can be displayed.
from solution import draw_line, ... | [
{
"docstring": null,
"function_declaration": "def draw_line():",
"function_name": "draw_line",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def draw_square():",
"function_name": "draw_square",
"parameter_list": "()"
},
{
"docstring": null,
"... | [
0,
0,
0,
1,
0,
0,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import turtle\n\ndef draw_line():\n turtle.forward(100)\n\ndef draw_square():\n for _ in range(4):\n turtle.forward(50)\n turtle.right(90)\n\ndef dr... | trial_gpt4o_3 | {
"original_instruction": "**Problem Statement:**\n\nYou are tasked with creating an interactive drawing program using the `turtle` graphics module. In this task, you will implement a program that allows a user to draw various geometric shapes on the canvas by responding to keyboard events. Your program should suppor... | 0.742498 | Docs: Python310_32306 | C | [
"draw_line",
"draw_square",
"draw_circle",
"clear_screen",
"quit_program",
"setup_drawing_program"
] | 6 | [
[
"setup_drawing_program",
"clear_screen"
],
[
"setup_drawing_program",
"draw_circle"
],
[
"setup_drawing_program",
"draw_line"
],
[
"setup_drawing_program",
"draw_square"
],
[
"setup_drawing_program",
"quit_program"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 9888a7c733a5d6d5764b883fd8fc72011a6a2f71 | bfdffa8515a297d46d649cc132b6cbc59897bda7 | |||
v1.0 | complete | Docs | Docs: Python310_32957_C | import threading
import queue
import time
import logging
# Configure logging
logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s')
def fetch_data():
"""Simulate data fetching logic.
"""
# Increment a counter to simulate data production
fetch_data.counter += 1
return fetch_... | import threading
import queue
import time
import logging
# Configure logging
logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s')
def fetch_data():
# Simulate data fetching logic
fetch_data.counter += 1
return fetch_data.counter
fetch_data.counter = 0
def producer(buffer, stop_e... | import threading
import queue
import time
import logging
from solution import fetch_data, producer, consumer, main
# Set logging to only show errors to keep test output clean.
logging.basicConfig(level=logging.ERROR, format='%(threadName)s: %(message)s')
def test_fetch_data():
count1 = fetch_data()
count2 = f... | [
{
"docstring": null,
"function_declaration": "def fetch_data():",
"function_name": "fetch_data",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def producer(buffer, stop_event):",
"function_name": "producer",
"parameter_list": "(buffer, stop_event)"
},
... | [
1,
0,
0,
1,
0,
0,
1,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import threading\nimport queue\nimport time\nimport logging\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s')\n\nde... | trial_gpt4o_0 | {
"original_instruction": "### Python Coding Assessment: `threading` Module\n\n**Objective**: Assess the ability to leverage the `threading` module in Python to implement a multi-threaded producer-consumer scenario while ensuring proper synchronization.\n\n#### Problem Statement\n\nYou are required to implement a mul... | 0.548498 | Docs: Python310_32957 | C | [
"fetch_data",
"producer",
"consumer",
"main"
] | 4 | [
[
"producer",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d60375b24471195fcf3c7147c61217e0b2a36d6a | 61e0b1b9bdb91c18b1efaaa1f7689bd1596b1cfd | |||
v1.0 | complete | Docs | Docs: Python310_32450_C | import json
import os
import sys
from distutils.core import setup
def read_config(file_path):
""" Reads the package configuration from a JSON file.
Args:
file_path (str): Path to the configuration file.
Returns:
dict: The configuration data.
Raises:
FileNotFoundEr... | import json
import os
import sys
from distutils.core import setup
def read_config(file_path):
with open(file_path, 'r') as file:
return json.load(file)
def package_directory(config_path='package_config.json'):
try:
config = read_config(config_path)
# Validating config fields
r... | import os
import pytest
import json
from unittest.mock import patch
from solution import package_directory, read_config
def test_read_config(tmpdir):
config_content = {
"name": "sample_package",
"version": "0.1",
"description": "A sample Python package",
"author": "Jane Doe",
... | [
{
"docstring": null,
"function_declaration": "def read_config(file_path):",
"function_name": "read_config",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def package_directory(config_path='package_config.json'):",
"function_name": "package_directory... | [
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 json\nimport os\nfrom distutils.core import setup\n\ndef read_config(file_path):\n \"\"\"\n Read and parse the configuration file.\n \"\"\"\n with op... | trial_gpt4o_9 | {
"original_instruction": "You need to design a Python script that packages a directory containing Python modules into a distributable format. You will use the `distutils` library to achieve this.\n\n#### Task\nWrite a Python script that:\n1. Reads the metadata of a Python package from a configuration file.\n2. Packa... | 0.643193 | Docs: Python310_32450 | C | [
"read_config",
"package_directory"
] | 2 | [
[
"package_directory",
"read_config"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a510f3f5bd0886059882494e407b2c7afd5b6dc3 | 59589f699a18a94ec7be91ed328e49ba44fe7bb1 | |||
v1.0 | complete | Docs | Docs: Scikit_32821_C | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.metrics import accuracy_score, confusion_matrix
def load_data(file_path):
"""
Load dataset from a CSV file... | import pandas as pd
import string
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.metrics import accuracy_score, confusion_matrix
def load_data(file_path):
"""
Load dataset f... | from solution import load_data, preprocess_text, prepare_data, vectorize_data, train_and_evaluate_model
import pandas as pd
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.feature_extraction.text import TfidfVectorizer
# Sample data to simulate spam.csv
data = {
'text': ["Free entry in 2 a ... | [
{
"docstring": "Load dataset from a CSV file.",
"function_declaration": "def load_data(file_path):",
"function_name": "load_data",
"parameter_list": "(file_path)"
},
{
"docstring": "Preprocess the text by removing punctuation and converting to lowercase.",
"function_declaration": "def pr... | [
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\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import ... | trial_gpt4o_9 | {
"original_instruction": "**Question**: \n\nYou are given a dataset `spam.csv` that contains two columns: `text` (the message content) and `label` (either \"spam\" or \"ham\"). Your task is to implement a text classification pipeline using the Naive Bayes classifiers from the scikit-learn library to classify whether... | 0.633472 | Docs: Scikit_32821 | C | [
"load_data",
"preprocess_text",
"prepare_data",
"vectorize_data",
"train_and_evaluate_model",
"main"
] | 6 | [
[
"prepare_data",
"preprocess_text"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas",
"sklearn"
] | false | 0bb18aaca676d4fefe35835303f29f4eba0427f7 | cfdedd1f91d738c888bb9222e2ad0838ddb50ba6 | |||
v1.0 | complete | Docs | Docs: Python310_32853_C | class CustomError(Exception):
""" Custom exception for specific error cases.
"""
pass
def raise_custom_error(message: str) -> None:
""" Raise a CustomError with the provided message.
Args:
message (str): The error message.
"""
raise CustomError(message)
def process_operations(... | class CustomError(Exception):
pass
def raise_custom_error(message: str) -> None:
raise CustomError(message)
def process_operations(operations: list) -> list:
sample_list = [1, 2, 3]
results = []
for operation in operations:
op_type = operation[0]
try:
if op_type =... | from solution import CustomError, raise_custom_error, process_operations
def test_divide():
assert process_operations([("divide", 6, 3)]) == [2]
assert process_operations([("divide", 6, 0)]) == ["Error: Division by zero."]
def test_concat():
assert process_operations([("concat", "hello", 3)]) == ["Error: ... | [] | [
0,
0,
0,
1,
1,
0,
1,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class CustomError(Exception):\n pass\n\ndef raise_custom_error(message: str) -> None:\n raise CustomError(message)\n\ndef process_operations(operations: list) -> ... | trial_gpt4o_7 | {
"original_instruction": "As part of improving error handling in your Python application, you need to manage different types of errors gracefully. Your task is to implement a function that processes a list of operations and appropriately handles any errors that might occur using built-in Python exceptions. Additiona... | 0.540625 | Docs: Python310_32853 | C | [
"raise_custom_error",
"process_operations"
] | 2 | [
[
"process_operations",
"raise_custom_error"
]
] | 1 | [] | false | [
"CustomError"
] | true | pytest | true | [] | true | b4208a3e0cdcc2a7fe34f1cf27c0b1d834d0e26a | 58603c0b1410d8d2af0a371afec09f04f62e5cdd | |||
v1.0 | complete | Docs | Docs: Python310_33296_C | import faulthandler
import signal
import time
def setup_fault_handler():
"""
Sets up the fault handler to dump tracebacks to a file.
"""
pass
def disable_fault_handler():
"""
Disables the fault handler.
"""
pass
def run_process():
"""
Simulate a process that prints "Running...... | import faulthandler
import signal
import time
def setup_fault_handler():
"""
Sets up the fault handler to dump tracebacks to a file.
"""
with open("traceback.log", "w") as f:
faulthandler.enable(file=f)
with open("traceback.log", "a") as f:
# Register SIGUSR1 to dump traceback
... | # To test this script manually, execute it and:
# 1. Verify that `traceback.log` contains tracebacks as expected.
# 2. Send SIGUSR1 to the process and observe the behavior.
# 3. Optional: Interrupt the script with KeyboardInterrupt and see if it handles it gracefully.
# Automated testing code is limited for this scena... | [
{
"docstring": "Sets up the fault handler to dump tracebacks to a file.",
"function_declaration": "def setup_fault_handler():",
"function_name": "setup_fault_handler",
"parameter_list": "()"
},
{
"docstring": "Disables the fault handler.",
"function_declaration": "def disable_fault_handl... | [
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 faulthandler\nimport signal\nimport time\nimport sys\n\ndef enable_faulthandler():\n # Open the file in append mode to log tracebacks\n log_file = open(\"t... | trial_gpt4o_9 | {
"original_instruction": "**Title:** Implementing Robust Debugging with `faulthandler`\n\n**Objective:** \nYou are tasked with creating a Python script that robustly handles unexpected terminations by utilizing the `faulthandler` module. Your implementation should demonstrate comprehensive use of the functionalities... | 0.5527 | Docs: Python310_33296 | C | [
"setup_fault_handler",
"disable_fault_handler",
"run_process"
] | 3 | [
[
"run_process",
"disable_fault_handler"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d62b58ca6762c890bea7218ea756073927cfeffa | faa9fe9d3fe8eabea2eef5cada289684691df450 | |||
v1.0 | complete | Docs | Docs: Python310_33444_C | import pwd
import grp
import syslog
def get_user_info(username):
"""Returns user information from the Unix password database.
>>> get_user_info("john")
{"userID": 1001, "userName": "john", "homeDirectory": "/home/john", "shell": "/bin/bash"}
"""
pass
def get_group_info(groupname):
"""Returns g... | import pwd
import grp
import syslog
def get_user_info(username):
"""
Returns user information from the Unix password database.
"""
try:
user_info = pwd.getpwnam(username)
return {
"userID": user_info.pw_uid,
"userName": user_info.pw_name,
"homeDirecto... | import pytest
from solution import get_user_info, get_group_info, add_user_to_group, log_event
def test_get_user_info(monkeypatch):
# Mocking pwd.getpwnam
class MockUser:
pw_uid = 1001
pw_name = "john"
pw_dir = "/home/john"
pw_shell = "/bin/bash"
def mock_getpwnam(usern... | [
{
"docstring": "Returns user information from the Unix password database.",
"function_declaration": "def get_user_info(username):",
"function_name": "get_user_info",
"parameter_list": "(username)"
},
{
"docstring": "Returns group information from the Unix group database.",
"function_decl... | [
0,
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pwd\nimport grp\nimport syslog\n\ndef get_user_info(username):\n try:\n user_info = pwd.getpwnam(username)\n return {\n \"userID\": u... | trial_gpt4o_9 | {
"original_instruction": "## Coding Assessment Question\n\n### Objective\nDesign a Python program to demonstrate your understanding of Unix-specific system interactions using Python 3.10. You are required to implement functions that utilize Unix system calls and database modules to perform various tasks.\n\n### Prob... | 0.454063 | Docs: Python310_33444 | C | [
"get_user_info",
"get_group_info",
"add_user_to_group",
"log_event"
] | 4 | [
[
"add_user_to_group",
"log_event"
],
[
"get_group_info",
"log_event"
],
[
"get_user_info",
"log_event"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 36bc2de62b9a1ff05760b89debc87cc32c23577e | 6af01e8e4ed0fab72f975dcb8a1379201ab3b9b7 | |||
v1.0 | complete | Docs | Docs: Python310_33209_C | import asyncio
async def run_data_logger(host: str, port: int, log_file: str):
""" Asynchronous data logger using Python's asyncio module.
Listens for incoming data on a specified network socket and logs the data to a file.
:param host: The host address on which the server will listen (e.g., "127.0.0.... | import asyncio
import signal
import datetime
async def handle_client(reader, writer, log_file):
with open(log_file, 'a') as f:
while True:
data = await reader.read(100)
if not data:
break
timestamp = datetime.datetime.now().isoformat()
f.write... | import asyncio
import os
import pytest
import signal
from solution import run_data_logger
@pytest.fixture
def log_file():
log_file_path = 'test_data.log'
yield log_file_path
if os.path.exists(log_file_path):
os.remove(log_file_path)
async def send_data(host, port, data):
reader, writer = awai... | [
{
"docstring": null,
"function_declaration": "def shutdown():",
"function_name": "shutdown",
"parameter_list": "()"
}
] | [
0,
1,
1,
0,
1,
1,
0,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport signal\nfrom datetime import datetime\n\nasync def handle_client(reader, writer, log_file):\n addr = writer.get_extra_info('peername')\n\n ... | trial_gpt4o_2 | {
"original_instruction": "**Question: Implementing an Asynchronous Data Logger**\n\nYou are required to create an asynchronous data logger using Python's `asyncio` module. This logger should listen for incoming data on a specified network socket and log the data to a file. The logger needs to support the following f... | 0.537912 | Docs: Python310_33209 | C | [
"handle_client",
"run_data_logger"
] | 2 | [
[
"run_data_logger",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9e3f8ebf2ca82beeae1880924d2910fc27362bc3 | e449570d6c0ebc065b83878a9beb501053e886d2 | |||
v1.0 | complete | Docs | Docs: Seaborn_33270_C | import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
def load_and_display_tips():
"""Load the 'tips' dataset and display the first 5 rows.
>>> tips = load_and_display_tips()
>>> isinstance(tips, pd.DataFrame) True
>>> not tips.empty True
"""
# Load the dataset
tips = sn... | import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
def load_and_display_tips():
# Load the dataset
tips = sns.load_dataset("tips")
# Display first 5 rows of the dataset
print(tips.head())
return tips
def basic_scatter_plot(tips):
# Basic scatter plot with hue and style
... | from solution import load_and_display_tips, basic_scatter_plot, enhanced_scatter_plot, faceted_scatter_plot
import seaborn as sns
def test_load_and_display_tips():
tips = load_and_display_tips()
assert isinstance(tips, pd.DataFrame), "Output should be a pandas DataFrame"
assert not tips.empty, "DataFrame s... | [
{
"docstring": null,
"function_declaration": "def load_and_display_tips():",
"function_name": "load_and_display_tips",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def basic_scatter_plot(tips):",
"function_name": "basic_scatter_plot",
"parameter_list": ... | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Load the dataset\ntips = sns.load_dataset(\"tips\")\n\n# Task 1: Display first 5 rows o... | trial_gpt4o_8 | {
"original_instruction": "### Question\n\n**Plotting with Seaborn: Scatter Plot Customization and Faceting**\n\n#### Objective\nCreate a series of scatter plots using the Seaborn library to visualize relationships between variables in a dataset. The plots should utilize various Seaborn functionalities such as color ... | 0.758068 | Docs: Seaborn_33270 | C | [
"load_and_display_tips",
"basic_scatter_plot",
"enhanced_scatter_plot",
"faceted_scatter_plot",
"generate_plots"
] | 5 | [
[
"generate_plots",
"basic_scatter_plot"
],
[
"generate_plots",
"enhanced_scatter_plot"
],
[
"generate_plots",
"faceted_scatter_plot"
],
[
"generate_plots",
"load_and_display_tips"
]
] | 4 | [] | false | [] | false | pytest | true | [
"matplotlib",
"pandas",
"seaborn"
] | false | 7a2909d6f2e5a50207c07252edaa65f33c6ffddc | 2a78ebbec4d93f9118c0feff49dfda031becfa04 | |||
v1.0 | complete | Docs | Docs: Python310_33167_C | from typing import List
from threading import Thread, Lock
from multiprocessing import Process, Manager
def find_primes_concurrently(start: int, end: int) -> List[int]:
""" Finds all prime numbers in a given range [start, end] using both threading and multiprocessing.
This function will split work across ... | from threading import Thread, Lock
from multiprocessing import Process, Manager
from typing import List
import math
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i... | import pytest
from solution import find_primes_concurrently
def test_find_primes_small_range():
assert find_primes_concurrently(10, 20) == [11, 13, 17, 19]
def test_find_primes_large_range():
assert find_primes_concurrently(1, 100) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def find_primes_in_range(start, end, primes):",
"function_name": "find_primes_in_range",
"parameter_list": "(star... | [
0,
0,
1,
0,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport threading\nimport multiprocessing\n\n# Helper function to check if a number is prime\ndef is_prime(n: int) -> bool:\n if n < 2... | trial_gpt4o_8 | {
"original_instruction": "**Title: Implement a Concurrent Prime Number Finder**\n\n**Objective:** To assess your understanding of threading and multiprocessing in Python, you will implement a concurrent program to find prime numbers within a specified range. Your task is to use both thread-based and process-based pa... | 0.574049 | Docs: Python310_33167 | C | [
"is_prime",
"find_primes_in_range",
"find_primes_concurrently"
] | 3 | [
[
"find_primes_concurrently",
"find_primes_in_range"
],
[
"find_primes_in_range",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4f5548fbfdd32a69217dd3ca8e4f14fd08230806 | e0c0865b98219e0499280c48c7e5f2cc627a4d77 | |||
v1.0 | complete | Docs | Docs: Python310_33688_C | def simple_file_server_application(environ, start_response):
"""
WSGI application to serve static files from a specified directory.
The application should:
- Serve files from the specified directory.
- Serve `index.html` if the request corresponds to a directory.
- Return `404 Not Found` if the ... | import os
from wsgiref.simple_server import make_server
from wsgiref.util import setup_testing_defaults, FileWrapper
from wsgiref.headers import Headers
import mimetypes
def simple_file_server_application(environ, start_response):
setup_testing_defaults(environ)
path = environ.get('PATH_INFO', '').lstrip(... | import os
import tempfile
import shutil
import pytest
from wsgiref.util import setup_testing_defaults
from io import BytesIO
from solution import simple_file_server_application
@pytest.fixture(scope='module')
def test_dir():
base_dir = tempfile.mkdtemp()
subdir = os.path.join(base_dir, 'subdir')
os.makedir... | [
{
"docstring": null,
"function_declaration": "def simple_file_server_application(environ, start_response):",
"function_name": "simple_file_server_application",
"parameter_list": "(environ, start_response)"
},
{
"docstring": null,
"function_declaration": "def run_server(directory, port=80... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nfrom wsgiref.util import setup_testing_defaults, FileWrapper\nfrom wsgiref.headers import Headers\nfrom wsgiref.simple_server import make_server\nimport mime... | trial_gpt4o_4 | {
"original_instruction": "You are required to implement a simple WSGI application using the `wsgiref` module that serves static files from a specified directory. The application should meet the following requirements:\n\n1. **Directory Listing and File Serving:**\n - The application should serve files from a spec... | 0.539128 | Docs: Python310_33688 | C | [
"simple_file_server_application",
"run_server"
] | 2 | [
[
"run_server",
"simple_file_server_application"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9b28db4b13e4f95fbd28b54bd0e8ef6be4f99342 | 45e259e6586f35b36d16b1e2295fa4863284530a | |||
v1.0 | complete | Docs | Docs: Python310_32581_C | import codecs
class CustomCodec:
def __init__(self):
pass
def custom_encoder(self, input_string):
""" Encode the input string by replacing each character with its corresponding ASCII value followed by a space.
>>> encoder = CustomCodec()
>>> encoder.custom_encoder("Hello")
... | import codecs
class CustomCodec:
def __init__(self):
pass
def custom_encoder(self, input_string):
encoded = ' '.join(str(ord(char)) for char in input_string)
return encoded, len(encoded)
def custom_decoder(self, encoded_string):
decoded = ''.join(chr(int(code)) for code in... | from solution import encode_decode_test
def test_encode_decode_basic():
encoded, decoded = encode_decode_test("Hello")
assert encoded == "72 101 108 108 111"
assert decoded == "Hello"
def test_encode_decode_empty():
encoded, decoded = encode_decode_test("")
assert encoded == ""
assert decoded ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import codecs\n\nclass CustomCodec:\n def __init__(self):\n pass\n\n def custom_encoder(self, input_string):\n encoded = ' '.join(str(ord(char)) for... | trial_gpt4o_0 | {
"original_instruction": "### Coding Challenge: Custom Codec Registration and Usage\n\n#### Objective:\nCreate a custom encoding/decoding mechanism in Python 3.10 and demonstrate its registration and usage with error handling.\n\n#### Task:\n1. Implement a custom encoder and decoder using Python classes.\n2. Registe... | 0.583744 | Docs: Python310_32581 | C | [
"lookup_custom",
"register_custom_codecs",
"encode_decode_test"
] | 3 | [
[
"encode_decode_test",
"register_custom_codecs"
],
[
"register_custom_codecs",
"lookup_custom"
]
] | 2 | [] | false | [
"CustomCodec"
] | true | pytest | true | [] | true | 7e2aa446e636a02930bbee7a4f44703667f3aa09 | 3026ada84157a35e5a8bcfd866219344d35f1336 | |||
v1.0 | complete | Docs | Docs: Python310_33812_C | import asyncio
from typing import List
async def ping_url(url: str) -> str:
"""
Run a subprocess to ping the URL and return the result.
"""
pass
async def process_queue(url_queue: asyncio.Queue):
"""
Process URLs from the queue, ping them, and store the result.
"""
pass
async def tcp_... | import asyncio
import subprocess
from asyncio import Queue
from typing import List
async def ping_url(url: str) -> str:
"""
Run a subprocess to ping the URL and return the result.
"""
try:
proc = await asyncio.create_subprocess_shell(
f"ping -c 1 {url}",
stdout=asyncio.s... | import pytest
import asyncio
from solution import ping_url, process_queue, tcp_server, main
@pytest.mark.asyncio
async def test_ping_url_success():
result = await ping_url("google.com")
assert "1 packets transmitted" in result
@pytest.mark.asyncio
async def test_ping_url_failure():
result = await ping_url... | [] | [
0,
1,
1,
0,
0,
1,
1,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport subprocess\nfrom typing import List\n\nasync def ping_url(url: str) -> str:\n \"\"\"\n Runs a subprocess to ping the URL and return the res... | trial_gpt4o_2 | {
"original_instruction": "**Async Task and Network Programming with asyncio**\n\n### Problem Statement\n\nYou are to implement an asynchronous solution that fulfills the following requirements:\n\n1. **Subprocess Management**:\n - Create an asynchronous function that runs a subprocess to execute a shell command (\... | 0.570573 | Docs: Python310_33812 | C | [
"ping_url",
"process_queue",
"tcp_server",
"main"
] | 4 | [
[
"process_queue",
"ping_url"
],
[
"tcp_server",
"ping_url"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2c06ac763ec4d7f7bf45023156ea0a2f44b2400b | 660d674123e4cfde6741ef152bfe3409a11fbbd3 | |||
v1.0 | complete | Docs | Docs: Pytorch_33310_C | import torch
import torch.distributed.rpc as rpc
from torch.distributed.rpc import RRef
def create_rref_worker():
""" Function to create and return a RRef
>>> create_rref_worker()
RRef(tensor([1, 2, 3]))
"""
return RRef(torch.tensor([1, 2, 3]))
def use_rref_worker(rref):
""" Function to use an... | import os
import torch
import torch.distributed.rpc as rpc
from torch.distributed.rpc import RRef
# Function to create and return a RRef
def create_rref_worker():
return RRef(torch.tensor([1, 2, 3]))
# Function to use an RRef
def use_rref_worker(rref):
tensor = rref.to_here()
print(f"Worker {rpc.get_worke... | import pytest
import torch
import torch.multiprocessing as mp
import torch.distributed.rpc as rpc
from solution import create_rref_worker, pass_rref_worker, use_rref_worker
def rpc_worker(rank, world_size):
rpc.init_rpc(f"worker{rank}", rank=rank, world_size=world_size)
if rank == 0:
rref = create_rre... | [
{
"docstring": null,
"function_declaration": "def create_rref_worker():",
"function_name": "create_rref_worker",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def use_rref_worker(rref):",
"function_name": "use_rref_worker",
"parameter_list": "(rref)"
}... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.distributed.rpc as rpc\n\n# Functions to demonstrate RRef life cycle\n\ndef create_tensor():\n \"\"\"\n Creates a tensor to be shared a... | trial_gpt4o_2 | {
"original_instruction": "**Advanced PyTorch Distributed RPC Task**\n\n### Objective:\nYou are tasked with implementing functionality related to the Remote Reference (RRef) protocol in PyTorch's distributed RPC framework. The goal is to create a function that demonstrates the life cycle of an RRef, including its cre... | 0.389768 | Docs: Pytorch_33310 | C | [
"create_rref_worker",
"use_rref_worker",
"pass_rref_worker"
] | 3 | [
[
"pass_rref_worker",
"use_rref_worker"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 238ee9617d07ef7d95669a094e1a3fbd8cea413c | 6b00dc51d2e1aa79a100d8e500f0e7702c682582 | |||
v1.0 | complete | Docs | Docs: Python310_33686_C | import io
def read_text_file(file_path: str) -> str:
""" Reads the content from the specified text file path.
Ensures that the text file content is read with UTF-8 encoding.
Handles edge cases such as files not existing or improper file paths by raising appropriate exceptions.
"""
pass
def write_t... | import os
import io
def read_text_file(file_path: str) -> str:
try:
with io.open(file_path, 'r', encoding='utf-8') as file:
return file.read()
except FileNotFoundError:
raise FileNotFoundError(f"File at {file_path} does not exist.")
except Exception as e:
raise IOError(f... | import pytest
import io
import os
from solution import read_text_file, write_text_file, read_binary_file, write_binary_file, combine_and_save_files
# Helper functions to set up and tear down test files
def setup_text_file(path, content):
with open(path, 'w', encoding='utf-8') as f:
f.write(content)
def s... | [
{
"docstring": null,
"function_declaration": "def read_text_file(file_path):",
"function_name": "read_text_file",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def write_text_file(file_path, content):",
"function_name": "write_text_file",
"param... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport io\n\ndef read_text_file(file_path: str) -> str:\n try:\n with io.open(file_path, 'r', encoding='utf-8') as file:\n return file.r... | trial_gpt4o_0 | {
"original_instruction": "#### Title: Advanced Usage of Python's io Module for Text and Binary I/O Operations\n\n#### Problem Statement:\nYou are tasked with developing a utility for reading, manipulating, and writing data from and to text and binary files using Python's `io` module.\n\n#### Requirements:\n\n1. **Fu... | 0.569554 | Docs: Python310_33686 | C | [
"read_text_file",
"write_text_file",
"read_binary_file",
"write_binary_file",
"combine_and_save_files"
] | 5 | [
[
"combine_and_save_files",
"read_binary_file"
],
[
"combine_and_save_files",
"read_text_file"
],
[
"combine_and_save_files",
"write_binary_file"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | c2e85bb9e1c96aa699979e82676017437756b6d4 | 846e312418feb368b18da0cfcb93a09f71e96a11 | |||
v1.0 | complete | Docs | Docs: Scikit_33769_C | import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB, ComplementNB, BernoulliNB
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
def naive_bayes_classifiers(f... | import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB, ComplementNB, BernoulliNB
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
def load_data(file_path):
... | import pytest
from sklearn.datasets import fetch_20newsgroups
import pandas as pd
# Assuming the above code is saved in a file named solution.py
from solution import naive_bayes_classifiers
# Create a temporary dataset for testing
def create_temp_csv():
data = fetch_20newsgroups(subset='train')
df = pd.DataFr... | [
{
"docstring": null,
"function_declaration": "def load_data(file_path):",
"function_name": "load_data",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def preprocess_data(text_data):",
"function_name": "preprocess_data",
"parameter_list": "(text_... | [
0,
0,
1,
1,
1,
1,
1,
1,
0,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import ... | trial_gpt4o_7 | {
"original_instruction": "**Title: Implement and Evaluate Different Naive Bayes Classifiers**\n\n**Background:**\nYou are provided with a dataset in CSV format containing textual data and associated labels. Your task is to implement and evaluate different Naive Bayes classifiers from the scikit-learn library on this... | 0.629226 | Docs: Scikit_33769 | C | [
"load_data",
"preprocess_data",
"evaluate_model",
"naive_bayes_classifiers"
] | 4 | [
[
"naive_bayes_classifiers",
"evaluate_model"
],
[
"naive_bayes_classifiers",
"load_data"
],
[
"naive_bayes_classifiers",
"preprocess_data"
]
] | 3 | [] | false | [] | false | pytest | true | [
"pandas",
"sklearn"
] | false | 27e5b8c2bac1e7da3d86fd94475f872b3c5dfce5 | f2f767914234bc2357f81be941d9eaac124d06ec | |||
v1.0 | complete | Docs | Docs: Scikit_33747_C | def convert_to_sparse(X):
"""
Converts a dense dataset to a sparse CSR format.
Parameters:
- X (np.ndarray): Dense input dataset.
Returns:
- X_sparse (scipy.sparse.csr_matrix): Sparse CSR representation of the input dataset.
"""
pass
def benchmark_models(models, n_samples, n_features,... | import numpy as np
from scipy.sparse import csr_matrix
from sklearn.datasets import make_classification
from time import perf_counter
from sklearn.metrics import accuracy_score
def convert_to_sparse(X):
"""
Converts a dense dataset to a sparse CSR format.
Parameters:
- X (np.ndarray): Dense input data... | from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from solution import benchmark_models, convert_to_sparse
def test_convert_to_sparse():
X_dense = np.array([[1, 0, 3], [0, 0, 6], [7, 0, 9]])
X_sparse = convert_to_sparse(X_dense)
assert X_sparse.shape ==... | [
{
"docstring": "Converts a dense dataset to a sparse CSR format.\n\nParameters:\n- X (np.ndarray): Dense input dataset.\n\nReturns:\n- X_sparse (scipy.sparse.csr_matrix): Sparse CSR representation of the input dataset.",
"function_declaration": "def convert_to_sparse(X):",
"function_name": "convert_to_s... | [
1,
1,
1,
1,
1,
1,
0,
0,
0
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.sparse import csr_matrix\nfrom time import perf_counter\nfrom sklearn.datasets import make_classification\n\ndef benchmark_models(models,... | trial_gpt4o_6 | {
"original_instruction": "### Question:\n\n### Prediction Latency and Sparse Data Handling in Scikit-learn\n\nYou are tasked with analyzing and optimizing the prediction latency and throughput of different scikit-learn models using both dense and sparse input data representations. This involves conducting benchmarks... | 0.563136 | Docs: Scikit_33747 | C | [
"convert_to_sparse",
"benchmark_models"
] | 2 | [
[
"benchmark_models",
"convert_to_sparse"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy",
"sklearn"
] | false | ff7373630f4125fdef7ab9cac1b6272597e13111 | 404f0cdbc1fd2fdec62ce3de5ae9c71b1ee93b2d | |||
v1.0 | complete | Docs | Docs: Python310_33674_C | class PyStatus:
def __init__(self, ok=True, exit_code=0, err_msg=None):
self.ok = ok
self.exit_code = exit_code
self.err_msg = err_msg
class PyConfig:
def __init__(self):
self.isolated = 0
self.use_environment = 1
self.site_import = 1
self.utf8_mode = 0
... | class PyStatus:
def __init__(self, ok=True, exit_code=0, err_msg=None):
self.ok = ok
self.exit_code = exit_code
self.err_msg = err_msg
class PyConfig:
def __init__(self):
self.isolated = 0
self.use_environment = 1
self.site_import = 1
self.utf8_mode = 0
... | from solution import PyConfig, Py_InitializeFromConfig, PyConfig_InitIsolatedConfig, run_custom_python
def test_pyconfig_initialization():
config = PyConfig()
PyConfig_InitIsolatedConfig(config)
config.utf8_mode = 1
config.allocator = "PYMEM_ALLOCATOR_MALLOC"
status = Py_InitializeFromConfig(c... | [] | [
0,
0,
1,
1,
0,
1,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Simulated PyStatus class to represent the status of Python initialization\nclass PyStatus:\n def __init__(self, ok=True, exit_code=0, err_msg=None):\n self.... | trial_gpt4o_3 | {
"original_instruction": "### Question: Custom Python Initialization\n\nYou are tasked with creating a custom Python environment that initializes Python in isolated mode, sets specific configuration parameters, and runs a Python command.\n\nWrite a Python program that achieves the following:\n1. **Initializes Python... | 0.443725 | Docs: Python310_33674 | C | [
"PyConfig_InitIsolatedConfig",
"Py_InitializeFromConfig",
"run_custom_python"
] | 3 | [
[
"run_custom_python",
"PyConfig_InitIsolatedConfig"
],
[
"run_custom_python",
"Py_InitializeFromConfig"
]
] | 2 | [] | false | [
"PyStatus",
"PyConfig"
] | true | pytest | true | [] | true | f783b2c29f248a8368c2eebb2ebad06641f43ed8 | 22c5be3dc35fe3364d80c59f8794c83165ebed0b | |||
v1.0 | complete | Docs | Docs: Pytorch_33587_C | import torch
import torch.fx as fx
def custom_compile(fn):
"""A decorator to trace tensor operations, handling both constant and dynamic shapes.
"""
def wrapper(*args, **kwargs):
class CustomTracer(fx.Tracer):
def is_leaf_module(self, m, name):
return False
... | import torch
import torch.fx as fx
def custom_compile(fn):
def wrapper(*args, **kwargs):
class CustomTracer(fx.Tracer):
def is_leaf_module(self, m, name):
# Everything is a leaf module, including nn.Modules
return False
def create_proxy(self, kind, t... | from solution import custom_compile, test_custom_compile
import torch
def test_decorator_with_even_shape():
x = torch.randn(4)
y = torch.randn(4)
result = dynamic_mse(x, y)
assert isinstance(result, torch.Tensor)
assert result.shape == torch.Size([])
def test_decorator_with_odd_shape():
x = to... | [] | [
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.fx import symbolic_trace\nimport torch.fx.experimental.symbolic_shapes as symbolic_shapes\n\n# Custom decorator to dynamically compile and trac... | trial_gpt4o_4 | {
"original_instruction": "### PyTorch Coding Assessment Question: Custom Tracer with Dynamic Shape Handling\n\n#### Objective\nImplement a custom PyTorch function decorator to trace tensor operations, handling both constant and dynamic shapes while utilizing the Dynamo tracer capabilities described.\n\n#### Task Des... | 0.515354 | Docs: Pytorch_33587 | C | [
"custom_compile",
"dynamic_mse",
"test_custom_compile"
] | 3 | [
[
"test_custom_compile",
"dynamic_mse"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 17a8ceb3beff498fdb20253f16c877f52788e989 | 973c130c6c72549a49e315add8c0672dc1cde420 | |||
v1.0 | complete | Docs | Docs: Python310_33381_C | # Server code
from xmlrpc.server import SimpleXMLRPCServer
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
def add(a, b):
"""Adds two integers and returns the result."""
result = a + b
logging.info(f"add({a}, {b}) = {result}")
return result
def start_server():
"""Starts th... | # Server code
from xmlrpc.server import SimpleXMLRPCServer
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
def add(a, b):
result = a + b
logging.info(f"add({a}, {b}) = {result}")
return result
def start_server():
server = SimpleXMLRPCServer(('localhost', 8000))
logging.inf... | import threading
import time
from solution import start_server, client_add
def test_server_and_client():
# Start the server in a separate thread
server_thread = threading.Thread(target=start_server)
server_thread.daemon = True
server_thread.start()
# Give server some time to start
time.sleep(1... | [
{
"docstring": null,
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def start_server():",
"function_name": "start_server",
"parameter_list": "()"
},
{
"docstring": null,
"fu... | [
0,
1,
1,
0,
0,
1,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# server.py\nfrom xmlrpc.server import SimpleXMLRPCServer\nimport logging\n\n# Set up logging\nlogging.basicConfig(level=logging.INFO)\n\ndef add(a, b):\n result = a... | trial_gpt4o_5 | {
"original_instruction": "### XMLRPC Server and Client Implementation\n\nYou are tasked with implementing an XML-RPC server and a client that interacts with it.\n\n**Server Requirements:**\n1. Implement an XML-RPC server that listens on `localhost` and port `8000`.\n2. The server should provide a single method `add(... | 0.449185 | Docs: Python310_33381 | C | [
"add",
"start_server",
"client_add"
] | 3 | [
[
"start_server",
"add"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4c9b0d98f9a8121e270eef37286217aed0bb8bdd | 995e6fd09bc1a28d775b20ca0276322422ee6b1c | |||
v1.0 | complete | Docs | Docs: Python310_33676_C | import asyncio
def process_iterator(lst: list, async_flag: bool) -> int:
"""
Processes a list of integers using synchronous or asynchronous iteration.
Parameters:
lst (list): The list of integers to be iterated over.
async_flag (bool): A flag indicating whether to use asynchronous iter... | import asyncio
def process_iterator(lst: list, async_flag: bool) -> int:
"""
Processes a list of integers using synchronous or asynchronous iteration.
Parameters:
lst (list): The list of integers to be iterated over.
async_flag (bool): A flag indicating whether to use asynchronous iter... | from solution import process_iterator
def test_process_iterator_sync():
assert process_iterator([1, 2, 3, 4, 5], False) == 15
def test_process_iterator_async():
assert process_iterator([1, 2, 3, 4, 5], True) == 15
def test_process_iterator_empty_sync():
assert process_iterator([], False) == 0
def test_p... | [
{
"docstring": "Processes a list of integers using synchronous or asynchronous iteration.\n\nParameters:\n lst (list): The list of integers to be iterated over.\n async_flag (bool): A flag indicating whether to use asynchronous iteration.\n\nReturns:\n int: The sum of the integers in the list.",
"f... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def process_iterator(lst: list, async_flag: bool) -> int:\n \"\"\"\n Sums up all integers in the given list `lst`.\n Handles both synchronous and asynchronous ... | trial_gpt4o_9 | {
"original_instruction": "**Title**: Implement a Custom Iterator Function in Python\n\n**Objective**: Create a Python function that uses the iterator-related C-API functionalities from the provided documentation. This exercise will test your proficiency in handling Python's iterator protocols and error management.\n... | 0.555341 | Docs: Python310_33676 | C | [
"process_iterator",
"_sync_sum",
"_async_sum"
] | 3 | [
[
"process_iterator",
"_async_sum"
],
[
"process_iterator",
"_sync_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5b91d81f255faec8bc7794f345cb7fe8c0e1d4d8 | 16e5851eafe161bff12b688bae39a36251d2a92e | |||
v1.0 | complete | Docs | Docs: Python310_33037_C | import os
import shutil
import glob
import argparse
import datetime
import zipfile
import sys
def log_message(directory: str, message: str):
"""Logs a message with a timestamp to the backup.log file in the specified directory."""
pass
def backup_python_files(directory: str):
"""Backs up all Python files i... | import os
import shutil
import glob
import argparse
import datetime
import zipfile
import sys
def log_message(directory, message):
with open(os.path.join(directory, 'backup.log'), 'a') as log_file:
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log_file.write(f'[{timestamp}] {mes... | import os
import shutil
import zipfile
from solution import backup_python_files, log_message
def setup_test_environment(test_dir):
if not os.path.exists(test_dir):
os.makedirs(test_dir)
project1_path = os.path.join(test_dir, 'project1')
project2_path = os.path.join(test_dir, 'project2')
os.make... | [
{
"docstring": null,
"function_declaration": "def log_message(directory, message):",
"function_name": "log_message",
"parameter_list": "(directory, message)"
},
{
"docstring": null,
"function_declaration": "def backup_python_files(directory):",
"function_name": "backup_python_files",... | [
1,
0,
0,
1,
0,
0,
1,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport shutil\nimport glob\nimport argparse\nimport datetime\nimport zipfile\nimport sys\n\ndef log_msg(log_file, msg):\n timestamp = datetime.datetime.no... | trial_gpt4o_3 | {
"original_instruction": "#### Objective\nThe purpose of this exercise is to assess your understanding and ability to use various Python standard libraries to solve a comprehensive problem. You will demonstrate your skills by building a small utility script.\n\n#### Problem Statement\nYou are tasked with creating a ... | 0.754603 | Docs: Python310_33037 | C | [
"log_message",
"backup_python_files",
"main"
] | 3 | [
[
"backup_python_files",
"log_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 67edd2fc9a52666abfa7d2d3e250da4353e906c5 | f70f96bb5760e076dac40302cae6cd2ceeed1e21 | |||
v1.0 | complete | Docs | Docs: Python310_33860_C | import hashlib
def generate_secure_hash(file_path: str, salt: bytes, algorithm: str) -> str:
"""
Generate a secure hash of a file with the specified algorithm and salt.
Parameters:
- file_path (str): Path to the file.
- salt (bytes): Salt value to be used.
- algorithm (str): Hashing algori... | import hashlib
def generate_secure_hash(file_path: str, salt: bytes, algorithm: str) -> str:
"""
Generate a secure hash of a file with the specified algorithm and salt.
Parameters:
- file_path (str): Path to the file.
- salt (bytes): Salt value to be used.
- algorithm (str): Hashing algorithm ... | import os
import pytest
@pytest.fixture
def create_test_file(tmp_path):
"""
Fixture to create a temporary test file with some content.
"""
file_content = b"Sample content for hashing"
file_path = tmp_path / "test_file.txt"
with open(file_path, "wb") as f:
f.write(file_content)
retur... | [
{
"docstring": "Generate a secure hash of a file with the specified algorithm and salt.\n\nParameters:\n- file_path (str): Path to the file.\n- salt (bytes): Salt value to be used.\n- algorithm (str): Hashing algorithm to be used (e.g., 'sha256', 'blake2b').\n\nReturns:\n- str: The hexadecimal hash string.",
... | [
1,
0,
0,
1,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\n\ndef generate_secure_hash(file_path: str, salt: bytes, algorithm: str) -> str:\n \"\"\"\n Generate a secure hash for a given file using the speci... | trial_gpt4o_8 | {
"original_instruction": "#### Context\nYou are developing a secure file verification system using Python. This system should be able to:\n\n1. Calculate a hash of a given file to ensure its integrity.\n2. Use salting to protect against collision attacks.\n3. Allow verification of the file’s hash.\n\n#### Task\nImpl... | 0.71769 | Docs: Python310_33860 | C | [
"generate_secure_hash",
"verify_file_hash"
] | 2 | [
[
"verify_file_hash",
"generate_secure_hash"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | cb392818d859aae8807cd84dafeaa79c10d2e22d | 19cd89fd4692ed587c70247acf63ef6d8705125b | |||
v1.0 | complete | Docs | Docs: Python310_33553_C | import asyncio
import ssl
import signal
clients = []
async def broadcast(message: str):
"""Broadcast message to all connected clients."""
pass # Complete this function
async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
"""Handle communication with a connected client."""... | import asyncio
import ssl
import signal
from datetime import datetime
clients = []
async def broadcast(message: str):
for client in clients:
try:
client.write(f"{message}\n".encode())
await client.drain()
except:
clients.remove(client)
async def handle_client(r... | import asyncio
import pytest
from solution import handle_client, main, broadcast
@pytest.fixture
async def mock_server():
server = await asyncio.start_server(handle_client, '127.0.0.1', 8888)
async with server:
yield server.sockets[0].getsockname()
async def test_handle_client(mock_server):
reader... | [
{
"docstring": null,
"function_declaration": "def handle_sigint(signal, frame):",
"function_name": "handle_sigint",
"parameter_list": "(signal, frame)"
}
] | [
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 asyncio\nimport ssl\nimport signal\n\nclients = set()\n\nasync def handle_client(reader, writer):\n global clients\n client_address = writer.get_extra_info... | trial_gpt4o_1 | {
"original_instruction": "### Python Networking and Asynchronous I/O Challenge\n\nYou are to implement a simple secure chat server and client using the `asyncio` and `ssl` modules in Python. Your task is to create both the server and client program, with the server listening for incoming client connections and each ... | 0.544149 | Docs: Python310_33553 | C | [
"broadcast",
"handle_client",
"main",
"handle_sigint"
] | 4 | [
[
"handle_client",
"broadcast"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3e74e6226bd631625997f9398e22700af08c4317 | b5a6f8b7db8eb356be6b7477990b492f469a613b | |||
v1.0 | complete | Docs | Docs: Pytorch_34051_C | import torch
from torch import dtype
from typing import Dict
def get_floating_point_info(dtype: torch.dtype) -> Dict[str, float]:
"""Returns a dictionary with properties of the floating-point dtype."""
pass
def get_integer_info(dtype: torch.dtype) -> Dict[str, int]:
"""Returns a dictionary with properties... | import torch
def get_floating_point_info(dtype):
"""
Returns a dictionary with properties of the floating-point dtype.
"""
finfo = torch.finfo(dtype)
return {
"bits": finfo.bits,
"eps": finfo.eps,
"max": finfo.max,
"min": finfo.min,
"tiny": finfo.tiny,
... | from solution import get_floating_point_info, get_integer_info, compare_dtypes
import torch
def test_get_floating_point_info():
info = get_floating_point_info(torch.float64)
assert info["bits"] == 64
assert info["eps"] > 0
assert info["max"] > 0
assert info["min"] < 0
assert info["tiny"] > 0
... | [
{
"docstring": "Returns a dictionary with properties of the floating-point dtype.",
"function_declaration": "def get_floating_point_info(dtype):",
"function_name": "get_floating_point_info",
"parameter_list": "(dtype)"
},
{
"docstring": "Returns a dictionary with properties of the integer dt... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef get_floating_point_info(dtype):\n \"\"\"\n Returns the properties of a floating-point dtype in PyTorch.\n \n Parameters:\n dtype (tor... | trial_gpt4o_2 | {
"original_instruction": "### PyTorch dtype Properties Assessment\n\n#### Objective\n\nYour task is to demonstrate your understanding of PyTorch's numerical properties of dtypes using the `torch.finfo` and `torch.iinfo` classes. You will write functions to extract and compare these properties for given dtypes.\n\n##... | 0.619375 | Docs: Pytorch_34051 | C | [
"get_floating_point_info",
"get_integer_info",
"compare_dtypes"
] | 3 | [
[
"compare_dtypes",
"get_floating_point_info"
],
[
"compare_dtypes",
"get_integer_info"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 2f18d654e28f4be5f338b9e7f1d270667c246827 | f99d7f96116386c891abac293722861ba5eb00c1 | |||
v1.0 | complete | Docs | Docs: Python310_34139_C | import atexit
import os
import readline
def load_command_history(histfile: str) -> None:
""" Attempts to read the command history from histfile.
If the file does not exist, it should be created.
"""
def save_command_history(prev_h_len: int, histfile: str) -> None:
""" Saves the new history to histfil... | import atexit
import os
import readline
def load_command_history(histfile: str) -> None:
try:
readline.read_history_file(histfile)
print("History loaded successfully.")
except FileNotFoundError:
open(histfile, 'wb').close()
print("History file not found. Created a new history fi... | import pytest
import os
import readline
from solution import load_command_history, save_command_history, interactive_shell
@pytest.fixture
def mock_histfile(tmp_path):
return os.path.join(tmp_path, "history_file")
def test_load_command_history_file_not_found(mock_histfile):
load_command_history(mock_histfile)... | [
{
"docstring": null,
"function_declaration": "def load_command_history(histfile):",
"function_name": "load_command_history",
"parameter_list": "(histfile)"
},
{
"docstring": null,
"function_declaration": "def save_command_history(prev_h_len, histfile):",
"function_name": "save_comman... | [
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 atexit\nimport os\nimport readline\n\ndef load_command_history(histfile: str) -> None:\n try:\n readline.read_history_file(histfile)\n print(\"H... | trial_gpt4o_6 | {
"original_instruction": "**Problem Statement:** \n\nDesign and implement a Python program that enhances the Python interactive shell experience by implementing a command history management feature using the \"readline\" module. The program should support loading command history from a file, allowing the user to int... | 0.421782 | Docs: Python310_34139 | C | [
"load_command_history",
"save_command_history",
"interactive_shell"
] | 3 | [
[
"interactive_shell",
"load_command_history"
],
[
"interactive_shell",
"save_command_history"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6b45ce71e95cf1f9cd29d37b29553772411f3e3b | 3be713070ba0612e4e90270abca5c7c0682075a4 | |||
v1.0 | complete | Docs | Docs: Seaborn_33491_C | import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from typing import Union
def create_color_palette(base_color: str, num_colors: int, as_cmap: bool) -> Union[sns.palettes._ColorPalette, sns.mpl.colormap.ColorMap]:
"""
Create a color palette using seaborn's dark_palette function.
Ar... | import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
def create_color_palette(base_color: str, num_colors: int, as_cmap: bool) -> sns.palettes._ColorPalette:
"""
Create a color palette using seaborn's dark_palette function.
Args:
- base_color (str): The base color for the palette.... | import pytest
from tempfile import NamedTemporaryFile
import pandas as pd
import seaborn as sns
from solution import create_color_palette, plot_data
def test_create_color_palette_discrete():
palette = create_color_palette("seagreen", 5, False)
assert isinstance(palette, sns.palettes._ColorPalette)
assert l... | [
{
"docstring": "Create a color palette using seaborn's dark_palette function.\n\nArgs:\n- base_color (str): The base color for the palette.\n- num_colors (int): The number of discrete colors in the palette.\n- as_cmap (bool): Whether to return a continuous colormap (True) or a discrete palette (False).\n\nRetur... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef create_color_palette(base_color: str, num_colors: int, as_cmap: bool):\n \"\"\"\n ... | trial_gpt4o_1 | {
"original_instruction": "You are tasked with analyzing the color distribution of a dataset and presenting it using a custom color palette created with seaborn's `dark_palette` function.\n\n### Problem Statement\n\n1. **Input**: You will be provided with a CSV file named `data.csv` containing a dataset with numerica... | 0.76882 | Docs: Seaborn_33491 | C | [
"create_color_palette",
"plot_data"
] | 2 | [
[
"plot_data",
"create_color_palette"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"pandas",
"seaborn"
] | false | f7b0b984afbc19a6ee396ece0bd2745e3ef9b30c | af83ea6ef9fb77ef734320e05fba75a3d77ae373 | |||
v1.0 | complete | Docs | Docs: Python310_33809_C | from multiprocessing import Pool
from typing import List
def matrix_element(A, B, row, col):
"""
Compute a single element of the resulting matrix
"""
return sum(A[row][i] * B[i][col] for i in range(len(B)))
def parallel_matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
""... | from multiprocessing import Pool
def matrix_element(A, B, row, col):
"""
Compute a single element of the resulting matrix
"""
return sum(A[row][i] * B[i][col] for i in range(len(B)))
def parallel_matrix_multiply(A, B):
"""
Multiply two matrices A and B using multiprocessing
"""
num_row... | from solution import parallel_matrix_multiply
def test_parallel_matrix_multiply_small():
A = [
[1, 2],
[3, 4]
]
B = [
[5, 6],
[7, 8]
]
assert parallel_matrix_multiply(A, B) == [[19, 22], [43, 50]]
def test_parallel_matrix_multiply_identity():
A = [
[1, 2... | [
{
"docstring": "Compute a single element of the resulting matrix",
"function_declaration": "def matrix_element(A, B, row, col):",
"function_name": "matrix_element",
"parameter_list": "(A, B, row, col)"
},
{
"docstring": "Multiply two matrices A and B using multiprocessing",
"function_dec... | [
1,
1,
1,
1,
1,
0,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from multiprocessing import Pool\n\ndef single_element_multiply(row, column):\n return sum(x * y for x, y in zip(row, column))\n\ndef get_column(matrix, col_index):\... | trial_gpt4o_8 | {
"original_instruction": "**Coding Challenge: Parallel Matrix Multiplication Using Multiprocessing**\n\n**Objective:** \nImplement a function to perform matrix multiplication using Python's `multiprocessing` module. This task aims to assess your understanding of creating processes, using pools, and inter-process com... | 0.656548 | Docs: Python310_33809 | C | [
"matrix_element",
"parallel_matrix_multiply"
] | 2 | [
[
"parallel_matrix_multiply",
"matrix_element"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a5ed039dc8ddd7cf2d10c1f133bc4f5c5959e91a | 8fad15d34cd6765a9ea5927851a1fad0e56be0ec | |||
v1.0 | complete | Docs | Docs: Python310_33910_C | import random
def random_walk(steps):
""" Perform a single random walk with a specified number of steps.
>>> random_walk(10)
[0, 1, 0, 1, 2, 1, 2, 3, 4, 3, 4]
>>> random_walk(5)
[0, -1, 0, 1, 2, 1]
"""
def simulate_walks(num_walks, steps):
""" Perform multiple random walks and record the ... | import random
def random_walk(steps):
if steps < 0:
raise ValueError("Number of steps cannot be negative")
position = 0
walk = [position]
for _ in range(steps):
step = random.choice([-1, 1])
position += step
walk.append(position)
return walk
def simulate_walks(num_w... | import pytest
from solution import random_walk, simulate_walks, analyze_walks
def test_random_walk_negative_steps():
with pytest.raises(ValueError):
random_walk(-1)
def test_random_walk():
random.seed(0) # To make the test deterministic
walk = random_walk(10)
assert walk[0] == 0
assert le... | [
{
"docstring": null,
"function_declaration": "def random_walk(steps):",
"function_name": "random_walk",
"parameter_list": "(steps)"
},
{
"docstring": null,
"function_declaration": "def simulate_walks(num_walks, steps):",
"function_name": "simulate_walks",
"parameter_list": "(num_... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef random_walk(steps):\n if steps < 0:\n raise ValueError(\"Number of steps cannot be negative\")\n position = 0\n walk = [position]\n... | trial_gpt4o_7 | {
"original_instruction": "### **Random Walk Simulation**\n\n**Objective:**\nDevelop a simulation of a random walk using the Python `random` module.\n\n**Problem Statement:**\nA random walk is a mathematical formalization to describe a path that consists of a series of random steps. Consider a simple 1-dimensional ra... | 0.730753 | Docs: Python310_33910 | C | [
"random_walk",
"simulate_walks",
"analyze_walks"
] | 3 | [
[
"simulate_walks",
"random_walk"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f696b13c8ab90fae18b7aaa0ffb1679896520228 | 4066b7eb2756908d0c82e4dafe7441aa8ad89c97 | |||
v1.0 | complete | Docs | Docs: Pytorch_33784_C | import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
from torch.nn.parallel import DistributedDataParallel as DDP
import os
def setup(rank, world_size):
"""Initialize the distributed process group using NCCL backend.
Args:
rank (int): The rank of the current ... | import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
from torch.nn.parallel import DistributedDataParallel as DDP
import os
def setup(rank, world_size):
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '12355'
dist.init_process_group("nccl", ran... | from solution import Net
import torch
def test_net_structure():
model = Net()
assert isinstance(model.fc1, torch.nn.Linear)
assert isinstance(model.fc2, torch.nn.Linear)
assert isinstance(model.relu, torch.nn.ReLU)
x = torch.randn(10, 10)
output = model(x)
assert output.shape == (10, ... | [] | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.nn.parallel import DistributedDataParallel as ... | trial_gpt4o_2 | {
"original_instruction": "#### Objective:\nImplement a distributed training setup using PyTorch's `torch.distributed` package. Your implementation should initialize the distributed process group, parallelize a simple neural network model training across multiple GPUs, and ensure synchronization of gradients between ... | 0.566989 | Docs: Pytorch_33784 | C | [
"setup",
"cleanup",
"train"
] | 3 | [
[
"train",
"cleanup"
],
[
"train",
"setup"
]
] | 2 | [] | false | [
"Net"
] | true | pytest | true | [
"torch"
] | false | d3f8a2ff07eaf735ebe70ac8066de2be4d28ab2b | 9c828a6a18815d7bc9a967e6aaedb4903ef1e252 | |||
v1.0 | complete | Docs | Docs: Python310_33484_C | class Config:
def __init__(self, name: str, version: int, settings: dict):
self.name = name
self.version = version
self.settings = settings
def update_setting(self, key: str, value: any):
self.settings[key] = value
def __str__(self) -> str:
return f"Config(name: {se... | import pickle
import copyreg
import shelve
class Config:
def __init__(self, name, version, settings):
self.name = name
self.version = version
self.settings = settings
def update_setting(self, key, value):
self.settings[key] = value
def __str__(self):
return f"Confi... | from solution import Config, serialize_config, deserialize_config, save_configs, load_configs, process_operations
def test_config_creation():
config = Config("config1", 1, {"theme": "dark"})
assert config.name == "config1"
assert config.version == 1
assert config.settings == {"theme": "dark"}
def test... | [] | [
1,
1,
0,
0,
1,
1,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pickle\nimport copyreg\nimport shelve\n\nclass Config:\n def __init__(self, name, version, settings):\n self.name = name\n self.version = versio... | trial_gpt4o_6 | {
"original_instruction": "### Question: Implementing Custom Serialization using Pickle and copyreg\n\n#### Objective\nYou are required to implement a custom serialization mechanism for a Python class using the `pickle` module, with support functions registered via `copyreg`. This will include handling a complex obje... | 0.549948 | Docs: Python310_33484 | C | [
"serialize_config",
"deserialize_config",
"save_configs",
"load_configs",
"process_operations"
] | 5 | [
[
"process_operations",
"load_configs"
],
[
"process_operations",
"save_configs"
]
] | 2 | [] | false | [
"Config"
] | true | pytest | true | [] | true | 499fd65c34508d71f08950247d61563662995f46 | 073b7aaf6dafba6cb621b77f1f0ac441dc76f751 | |||
v1.0 | complete | Docs | Docs: Pytorch_34171_C | import torch
from typing import List, Tuple
def create_named_tensor(shape: List[int], names: List[str]) -> torch.Tensor:
"""
Create a PyTorch tensor with specified shape and named dimensions.
Args:
shape (List[int]): A list of integers representing the shape of the tensor.
names (List[str]): A li... | import torch
from typing import List, Tuple
def create_named_tensor(shape: List[int], names: List[str]) -> torch.Tensor:
"""
Create a PyTorch tensor with specified shape and named dimensions.
Args:
shape (List[int]): A list of integers representing the shape of the tensor.
names (List[str]): A... | import pytest
import torch
from solution import create_named_tensor, named_tensor_operations
def test_create_named_tensor():
tensor = create_named_tensor([2, 3, 4], ['N', 'C', 'H'])
assert tensor.shape == torch.Size([2, 3, 4])
assert tensor.names == ('N', 'C', 'H')
def test_named_tensor_operations_broadca... | [
{
"docstring": "Create a PyTorch tensor with specified shape and named dimensions.\n\nArgs:\nshape (List[int]): A list of integers representing the shape of the tensor.\nnames (List[str]): A list of strings representing the names of the tensor's dimensions.\n\nReturns:\ntorch.Tensor: A PyTorch tensor with the s... | [
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\nfrom typing import List\n\ndef create_named_tensor(shape: List[int], names: List[str]) -> torch.Tensor:\n if len(shape) != len(names):\n raise V... | trial_gpt4o_6 | {
"original_instruction": "### Question: Working with Named Tensors in PyTorch\n\n#### Objective\nIn this assignment, you will work with named tensors in PyTorch to ensure the correct propagation of names through various tensor operations. Named tensors provide additional runtime correctness checks and improve code r... | 0.608907 | Docs: Pytorch_34171 | C | [
"create_named_tensor",
"named_tensor_operations"
] | 2 | [
[
"named_tensor_operations",
"create_named_tensor"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 2e3bc41bf0516a4895b00959d9dc4b53722fa70c | b801765133e9baeab005b1eaf2e32546fe20fce8 | |||
v1.0 | complete | Docs | Docs: Python310_33783_C | import contextvars
# Context variables
context_user = contextvars.ContextVar("user")
context_request_id = contextvars.ContextVar("request_id")
def initialize_context():
""" Initializes the context and sets initial values for context variables.
"""
def set_context_var(name, value):
""" Sets the value ... | import contextvars
# Context variables
context_user = contextvars.ContextVar("user")
context_request_id = contextvars.ContextVar("request_id")
def initialize_context():
"""
Initializes the context and sets initial values for context variables.
"""
context_user.set(None)
context_request_id.set(None... | from solution import initialize_context, set_context_var, get_context_var, save_current_context, switch_context, restore_context
def test_initialize_context():
initialize_context()
assert get_context_var("user") is None
assert get_context_var("request_id") is None
def test_set_context_var():
initializ... | [
{
"docstring": "Initializes the context and sets initial values for context variables.",
"function_declaration": "def initialize_context():",
"function_name": "initialize_context",
"parameter_list": "()"
},
{
"docstring": "Sets the value of a specified context variable.",
"function_decla... | [
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import contextvars\n\n# Create two context variables: \"user\" and \"request_id\"\nuser = contextvars.ContextVar(\"user\", default=None)\nrequest_id = contextvars.Conte... | trial_gpt4o_7 | {
"original_instruction": "**Question: Context Management with Context Variables**\n\nIn this problem, you will implement a simplified version of a context management system using the `contextvars` module in Python. You are required to demonstrate your understanding of creating, setting, and getting context variables... | 0.438169 | Docs: Python310_33783 | C | [
"initialize_context",
"set_context_var",
"get_context_var",
"save_current_context",
"switch_context",
"restore_context"
] | 6 | [
[
"restore_context",
"switch_context"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2f4396b39a008b25f41c6845aac75a24ee830189 | f0242a7ef8a95b3e05fed380e4a57662db875a9f | |||
v1.0 | complete | Docs | Docs: Python310_34113_C | def is_type_object(obj):
"""
Checks if the given object is a type object.
Args:
obj (Any): The object to check.
Returns:
bool: True if the object is a type object, False otherwise.
"""
pass
def create_custom_type(name, base=object):
"""
Creates a custom heap-allocated type.
... | import ctypes
def is_type_object(obj):
"""
Checks if the given object is a type object.
Args:
obj (Any): The object to check.
Returns:
bool: True if the object is a type object, False otherwise.
"""
return isinstance(obj, type)
def create_custom_type(name, base=object):
"""
C... | from solution import is_type_object, create_custom_type, interact_with_custom_type
def test_is_type_object():
assert is_type_object(int) == True
assert is_type_object(str) == True
assert is_type_object(123) == False
assert is_type_object('abc') == False
assert is_type_object(None) == False
def tes... | [] | [
1,
1,
0,
1,
0,
1,
0,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import types\n\ndef is_type_object(obj):\n \"\"\"\n Checks if the given object is a type object.\n \n Args:\n obj (Any): The object to check.\n \n ... | trial_gpt4o_9 | {
"original_instruction": "### Type Object Manipulation and Creation\n\nIn this assessment, you will demonstrate your understanding of Python's type objects and their manipulation by creating and interacting with custom heap-allocated types based on the provided documentation.\n\n#### Task\n\n1. **Type Checking Funct... | 0.497682 | Docs: Python310_34113 | C | [
"is_type_object",
"create_custom_type",
"interact_with_custom_type"
] | 3 | [
[
"interact_with_custom_type",
"create_custom_type"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b3143f92ceda965f85fba4379594c57263e1429e | c5a8d8e9b98760a56846104b5832fd114ea223b3 | |||
v1.0 | complete | Docs | Docs: Python310_34118_C | import asyncio
from typing import List
async def download_files(urls: List[str]) -> None:
""" Asynchronously downloads files from a list of URLs and saves them to the local directory.
Each download should happen concurrently, and the function should print out the progress of each download.
>>> import asyn... | import asyncio
import aiohttp
import os
from typing import List
async def download_file(session, url, path):
try:
async with session.get(url) as response:
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
downloaded_size = 0
... | import asyncio
from unittest.mock import patch, mock_open
from solution import download_files
def test_download_files(monkeypatch):
async def mock_response(url, path='tempfile'):
class MockResponse:
def __init__(self):
self.headers = {'content-length': '1024'}
se... | [] | [
1,
1,
1,
0,
0,
0,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport aiohttp\nimport os\nfrom typing import List\n\nasync def download_file(session, url, path):\n try:\n async with session.get(url) as res... | trial_gpt4o_0 | {
"original_instruction": "#### Objective\nDemonstrate your understanding of Python's asyncio library by creating a concurrent file download manager using `asyncio` that downloads files from the internet and stores them locally.\n\n#### Problem Statement\nWrite a Python function `download_files(urls: List[str]) -> No... | 0.575947 | Docs: Python310_34118 | C | [
"download_file",
"download_files"
] | 2 | [
[
"download_files",
"download_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 3a6de5a995cfee1e8fb929b895faf40d4aa06788 | ea8c57faafc5a779a0ccb1823bfe749a93f6ff1d | |||
v1.0 | complete | Docs | Docs: Python310_33723_C | import mailcap
def get_mailcap_entries() -> dict:
"""
Retrieves the mailcap entries from the system.
Returns:
dict: A dictionary mapping MIME types to their mailcap entries.
"""
pass
def execute_mime_viewer(mime_type: str, filename: str) -> str:
"""
Finds and returns the viewer co... | import mailcap
import re
def get_mailcap_entries():
"""
Retrieves the mailcap entries from the system
Returns:
dict: A dictionary mapping MIME types to their mailcap entries.
"""
return mailcap.getcaps()
def execute_mime_viewer(mime_type, filename):
"""
Finds and returns the viewer... | import mailcap
import pytest
from solution import get_mailcap_entries, execute_mime_viewer
def test_get_mailcap_entries():
# This only checks that a dictionary is returned and is non-empty if possible
result = get_mailcap_entries()
assert isinstance(result, dict)
assert bool(result) # The dictionary s... | [
{
"docstring": "Retrieves the mailcap entries from the system\nReturns:\n dict: A dictionary mapping MIME types to their mailcap entries.",
"function_declaration": "def get_mailcap_entries():",
"function_name": "get_mailcap_entries",
"parameter_list": "()"
},
{
"docstring": "Finds and ret... | [
0,
0,
1,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import mailcap\nimport re\n\ndef get_mailcap_entries():\n \"\"\"\n Retrieve mailcap entries from the system.\n \n Returns:\n dict: Dictionary mapping... | trial_gpt4o_2 | {
"original_instruction": "Handling MIME Type Command Execution\n\n#### Problem Statement\nYou are given a deprecated module called `mailcap` which provides functionality for handling MIME type configurations often used in email clients and web browsers. Your task is to use this module to retrieve the mailcap entries... | 0.53034 | Docs: Python310_33723 | C | [
"get_mailcap_entries",
"execute_mime_viewer"
] | 2 | [
[
"execute_mime_viewer",
"get_mailcap_entries"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d33d0a458fffe039c0b44e9bbad41873d882008e | 4e5bf256a868822dd89132d82be919f8a0eab2e2 | |||
v1.0 | complete | Docs | Docs: Pytorch_34471_C | import torch
import torch.distributed as dist
from torch.multiprocessing import Process
def distributed_training(world_size: int, num_epochs: int):
"""
Perform distributed training with debug and control handlers.
Args:
- world_size (int): The number of processes to run.
- num_epochs (int): The nu... | import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
from torch.multiprocessing import Process
def setup(rank, world_size):
"""
Setup the distributed environment.
"""
dist.init_process_group(
backend='gloo',
init_method='tcp://127.0.0.1:29500',... | import pytest
from solution import distributed_training
def test_distributed_training():
"""
Test case to validate the distributed training function runs without errors.
"""
try:
distributed_training(world_size=2, num_epochs=5)
except Exception as e:
pytest.fail(f"Distributed traini... | [] | [
0,
1,
0,
0,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom t... | trial_gpt4o_1 | {
"original_instruction": "### PyTorch Coding Assessment: Distributed Training with Control Plane\n\n#### Objective\nYou are given the task to implement a distributed training process in PyTorch that leverages the control plane module for debug and control handler functionalities.\n\n#### Task\nCreate a function `dis... | 0.433421 | Docs: Pytorch_34471 | C | [
"setup",
"cleanup",
"train",
"distributed_training"
] | 4 | [
[
"train",
"cleanup"
],
[
"train",
"setup"
]
] | 2 | [] | false | [
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | ca28bc3b6a9581183ca03aa8140670100cbf0629 | 865418c2863e94360f054fdba79c9819d3a2722d | |||
v1.0 | complete | Docs | Docs: Pytorch_34150_C | import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.nn as nn
import torch.optim as optim
from torch.nn.parallel import DistributedDataParallel as DDP
# Provided SimpleNN model
class SimpleNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
... | import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.nn as nn
import torch.optim as optim
from torch.nn.parallel import DistributedDataParallel as DDP
# Provided SimpleNN model
class SimpleNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
... | from solution import SimpleNN
def test_simple_nn_initialization():
model = SimpleNN(10, 50, 10)
assert isinstance(model.hidden, nn.Linear), "Hidden layer should be an instance of nn.Linear"
assert isinstance(model.relu, nn.ReLU), "ReLU layer should be an instance of nn.ReLU"
assert isinstance(model.out... | [] | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport torch\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.nn.paralle... | trial_gpt4o_6 | {
"original_instruction": "**Question: Implement Distributed Data Parallel Training with PyTorch**\n\nGiven the PyTorch DDP documentation, your task is to implement a distributed data parallel training script using PyTorch's `torch.nn.parallel.DistributedDataParallel` (DDP) module. You will use a simple neural networ... | 0.587888 | Docs: Pytorch_34150 | C | [
"setup",
"cleanup",
"train",
"main"
] | 4 | [
[
"train",
"cleanup"
],
[
"train",
"setup"
]
] | 2 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"torch"
] | false | b3fe392e753cbe675c8b9976db5736f5c35e92db | a3ec8196a179daba15fe8cda6d0e16107f276bbc | |||
v1.0 | complete | Docs | Docs: Pytorch_34393_C | import torch
def masked_tensor_sum(tensor: torch.Tensor, mask_condition: str) -> torch.Tensor:
""" Compute the sum of elements in the tensor subject to a complex masking condition.
Args:
tensor (torch.Tensor): 2D tensor of shape `(N, M)` containing float elements.
mask_condition (str): A string specif... | import torch
# Placeholder functions to mock the behavior of mask creation utilities
def create_block_mask(tensor):
return torch.ones_like(tensor, dtype=torch.bool)
def create_nested_block_mask(tensor):
return torch.ones_like(tensor, dtype=torch.bool)
def noop_mask(tensor):
return torch.ones_like(tensor,... | from solution import masked_tensor_sum
import torch
def test_masked_tensor_sum():
tensor = torch.tensor([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]])
# Test BLOCK condition: Here, we'll assume all elements are included based on the mock create_block... | [
{
"docstring": null,
"function_declaration": "def create_block_mask(tensor):",
"function_name": "create_block_mask",
"parameter_list": "(tensor)"
},
{
"docstring": null,
"function_declaration": "def create_nested_block_mask(tensor):",
"function_name": "create_nested_block_mask",
... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.nn.attention.flex_attention import create_block_mask, create_nested_block_mask, and_masks, or_masks, noop_mask\n\ndef masked_tensor_sum(tensor:... | trial_gpt4o_2 | {
"original_instruction": "### Masked Tensor Sum with PyTorch\n\nUsing the PyTorch library and the given block mask utilities from `torch.nn.attention.flex_attention`, write a function `masked_tensor_sum` that computes the sum of elements in a tensor subject to a complex masking condition.\n\n#### Function Signature:... | 0.478583 | Docs: Pytorch_34393 | C | [
"create_block_mask",
"create_nested_block_mask",
"noop_mask",
"and_masks",
"or_masks",
"masked_tensor_sum"
] | 6 | [
[
"masked_tensor_sum",
"and_masks"
],
[
"masked_tensor_sum",
"create_block_mask"
],
[
"masked_tensor_sum",
"create_nested_block_mask"
],
[
"masked_tensor_sum",
"noop_mask"
],
[
"masked_tensor_sum",
"or_masks"
]
] | 5 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 26834b5d07cfea417e533b58571dbafe722339dd | b313bb6613a5aef43cfcfdcfcc3761baffef52c2 | |||
v1.0 | complete | Docs | Docs: Python310_33538_C | import asyncio
import random
from typing import List
async def fetch_page(url: str) -> str:
"""
Simulates fetching a web page by sleeping for a random amount of time between 1 and 3 seconds.
>>> import asyncio
>>> import random
>>> from typing import List
>>> async def fetch_page(url: str) -> s... | import asyncio
import random
from typing import List
async def fetch_page(url: str) -> str:
"""
Simulates fetching a web page by sleeping for a random amount of time between 1 and 3 seconds.
"""
await asyncio.sleep(random.uniform(1, 3))
return f"<html><head><title>{url}</title></head><body>{'Hello ... | import pytest
from solution import fetch_page, process_page, scrape
import asyncio
@pytest.mark.asyncio
async def test_fetch_page():
url = "http://example.com"
content = await fetch_page(url)
assert content.startswith(f"<html><head><title>{url}</title></head><body>")
assert content.endswith("</body></h... | [] | [
0,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\nfrom typing import List\n\nasync def fetch_page(url: str) -> str:\n await asyncio.sleep(random.uniform(1, 3)) # Simulated network del... | trial_gpt4o_4 | {
"original_instruction": "#### Title: Concurrent Web Scraper with asyncio\n\n#### Objective\nImplement a concurrent web scraper using Python's `asyncio` library. Your scraper should fetch web pages concurrently and extract data from them.\n\n#### Problem Statement\nYou are required to implement a concurrent web scra... | 0.648648 | Docs: Python310_33538 | C | [
"fetch_page",
"process_page",
"fetch_and_process",
"scrape"
] | 4 | [
[
"fetch_and_process",
"fetch_page"
],
[
"fetch_and_process",
"process_page"
],
[
"scrape",
"fetch_and_process"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | a54c98ca85ccd0d385a76e462af791a821c51c08 | 1dc4dbc5ef5b224dc17ef68f407877c5ed36b021 | |||
v1.0 | complete | Docs | Docs: Python310_34217_C | import traceback
import sys
from typing import Optional
def custom_traceback_formatter(limit: Optional[int] = None, capture_locals: bool = False) -> str:
"""
Captures a formatted traceback of any exception that occurs within its scope.
Parameters:
limit (Optional[int]): Maximum number of stack... | import traceback
import sys
def custom_traceback_formatter(limit=None, capture_locals=False):
"""
Captures a formatted traceback of any exception that occurs within its scope.
Parameters:
limit (Optional[int]): Maximum number of stack trace entries to show. If None, show all entries.
c... | import pytest
from solution import custom_traceback_formatter
def test_traceback_no_limit_no_locals():
output = custom_traceback_formatter()
assert "ValueError: An intentional error!" in output
assert "File" in output
def test_traceback_with_limit_no_locals():
output = custom_traceback_formatter(limit... | [
{
"docstring": "Captures a formatted traceback of any exception that occurs within its scope.\n\nParameters:\n limit (Optional[int]): Maximum number of stack trace entries to show. If None, show all entries.\n capture_locals (bool): Determines whether to capture local variables in the stack trace.\n\nRetu... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def custom_traceback_formatter(limit=None, capture_locals=False):\n import traceback\n import sys\n\n try:\n # Example code to intentionally raise an ex... | trial_gpt4o_9 | {
"original_instruction": "### Coding Assessment: Custom Traceback Handling and Formatting\n\n#### Objective:\nTo demonstrate your understanding of the `traceback` module in Python, you will implement a custom error handling and logging mechanism that formats stack traces and exception information in a specific manne... | 0.555856 | Docs: Python310_34217 | C | [
"custom_traceback_formatter",
"test_custom_traceback_formatter"
] | 2 | [
[
"test_custom_traceback_formatter",
"custom_traceback_formatter"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b5e094d00fa181ed9c52b54ab9f0fc1dcf68ee4f | 32affb5b1f390272844ba677036ae48bdfb5bee0 | |||
v1.0 | complete | Docs | Docs: Python310_34242_C | def calculate_averages(students: list) -> dict:
""" Returns a dictionary with student names as keys and their average scores as values.
>>> calculate_averages([("Alice", [95, 80, 87]), ("Bob", [75, 85, 90]), ("Charlie", [80, 85, 80])])
{"Alice": 87.33, "Bob": 83.33, "Charlie": 81.67}
"""
def top_scorer... | def calculate_averages(students):
"""
Returns a dictionary with student names as keys and their average scores as values.
"""
return {name: round(sum(scores) / len(scores), 2) for name, scores in students}
def top_scorers_by_subject(students):
"""
Returns a dictionary with subject indices as ke... | from solution import calculate_averages, top_scorers_by_subject, overall_top_scorer, score_threshold_check
def test_calculate_averages():
students = [("Alice", [95, 80, 87]), ("Bob", [75, 85, 90]), ("Charlie", [80, 85, 80])]
expected_output = {"Alice": 87.33, "Bob": 83.33, "Charlie": 81.67}
assert calculat... | [
{
"docstring": "Returns a dictionary with student names as keys and their average scores as values.",
"function_declaration": "def calculate_averages(students):",
"function_name": "calculate_averages",
"parameter_list": "(students)"
},
{
"docstring": "Returns a dictionary with subject indice... | [
1,
0,
0,
0,
0,
1,
1,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_averages(students):\n \"\"\"\n Returns the average score for each student.\n \"\"\"\n return {name: round(sum(scores) / len(scores), 2) for na... | trial_gpt4o_9 | {
"original_instruction": "### Python Built-in Functions Assessment\n\n**Objective:**\nTo demonstrate your understanding and ability to integrate Python's built-in functions in solving a given problem.\n\n**Problem Statement:**\n\nYou are provided with a list of tuples, each containing a student's name and their resp... | 0.728593 | Docs: Python310_34242 | C | [
"calculate_averages",
"top_scorers_by_subject",
"overall_top_scorer",
"score_threshold_check"
] | 4 | [
[
"overall_top_scorer",
"calculate_averages"
],
[
"score_threshold_check",
"calculate_averages"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4d5af627745839f1599e70f62bf9198a2803b154 | 91d820262026256832e954fbbc1de4f0220b126c | |||
v1.0 | complete | Docs | Docs: Python310_34842_C | import types
def create_animal_classes():
"""
Dynamically creates Animal and its subclasses Dog and Cat.
Returns the Animal, Dog, and Cat classes.
"""
# Code to create and define Animal, Dog, Cat classes
def interact_with_animals(animal_dicts):
"""
Takes a list of dictionaries with animal ... | import types
def create_animal_classes():
"""
Dynamically creates Animal and its subclasses Dog and Cat.
Returns the Animal, Dog, and Cat classes.
"""
# Create the Animal base class dynamically
def animal_exec(ns):
def speak(self):
raise NotImplementedError("Subclasses must ... | def test_create_animal_classes():
Animal, Dog, Cat = create_animal_classes()
assert issubclass(Dog, Animal)
assert issubclass(Cat, Animal)
assert Dog().speak() == "Woof!"
assert Cat().speak() == "Meow!"
try:
Animal().speak()
except NotImplementedError:
assert T... | [] | [
1,
1,
0,
1,
0,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import types\n\ndef create_animal_classes():\n # Step 1: Creating the Animal base class dynamically\n def animal_exec(ns):\n def speak(self):\n ... | trial_gpt4o_6 | {
"original_instruction": "### Question: Dynamic Class and Type Management in Python\n\nIn this task, you will leverage the `types` module in Python 3.10 to dynamically create and manage classes and their interactions.\n\n#### Task Overview\n1. **Dynamic Class Creation**: Create two new classes dynamically:\n - `An... | 0.500997 | Docs: Python310_34842 | C | [
"create_animal_classes",
"interact_with_animals"
] | 2 | [
[
"interact_with_animals",
"create_animal_classes"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | d66d18168b96ff40b329e1c7b6ddf5ae75a3b87c | 1f13edaa8e77021603d0e0a0dbc3aa508351c141 | |||
v1.0 | complete | Docs | Docs: Python310_34282_C | import gettext
def set_language(language_code: str):
"""
Sets the current language of the application.
"""
pass
def display_message(language_code: str, message_id: str) -> str:
"""
Returns the translated message for the given language code and message ID.
"""
pass
def get_deferred_tra... | import gettext
# Dictionary to simulate the translation files (.mo files)
translations = {
'fr': {
'greeting': 'Bonjour',
'farewell': 'Au revoir',
'thanks': 'Merci'
},
'es': {
'greeting': 'Hola',
'farewell': 'Adiós',
'thanks': 'Gracias'
}
}
# Define a va... | import pytest
from solution import set_language, display_message, get_deferred_translation
def test_display_message_french():
assert display_message('fr', 'greeting') == 'Bonjour'
assert display_message('fr', 'farewell') == 'Au revoir'
assert display_message('fr', 'thanks') == 'Merci'
def test_display_mes... | [
{
"docstring": "Sets the current language of the application.",
"function_declaration": "def set_language(language_code):",
"function_name": "set_language",
"parameter_list": "(language_code)"
},
{
"docstring": "Returns the translated message for the given language code and message ID.",
... | [
1,
0,
1,
0,
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 gettext\nimport os\n\n# Simulate translation files by creating dictionaries\ntranslations = {\n 'en': {\n 'greeting': 'Hello',\n 'farewell': 'Go... | trial_gpt4o_2 | {
"original_instruction": "Internationalizing an Application\n\n#### Problem Statement\n\nYou are tasked with designing a Python application that supports multiple languages. Your application should allow the user to select a preferred language and display messages in that language. Implement the following functional... | 0.498323 | Docs: Python310_34282 | C | [
"set_language",
"display_message",
"get_deferred_translation"
] | 3 | [
[
"get_deferred_translation",
"display_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 141e1dc4dff1870f8546fc485c555aac53048a67 | f07ba9daf98af43e78b717893c5e6b2b6a9e8ab7 | |||
v1.0 | complete | Docs | Docs: Python310_34497_C | import gettext
from gettext import NullTranslations
def prepare_translation_files():
""" Simulate the creation of .mo files.
>>> en, es = prepare_translation_files()
>>> en
{"Hello World!": "Hello World!", "Welcome to the program.": "Welcome to the program."}
>>> es
{"Hello World!": "¡Hola Mund... | import gettext
from gettext import NullTranslations
# Since we cannot create actual .mo files in this environment, we will simulate it with in-memory translations
def prepare_translation_files():
"""
Simulate the creation of .mo files by using dictionaries to represent translations.
"""
translations_e... | import io
from contextlib import redirect_stdout
from solution import prepare_translation_files, load_translations, main_language_program
def test_prepare_translation_files():
en, es = prepare_translation_files()
assert en == {"Hello World!": "Hello World!", "Welcome to the program.": "Welcome to the program."... | [] | [
1,
0,
1,
1,
1,
1,
0,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import gettext\n\ndef prepare_translation_files():\n \"\"\"\n Dummy function to simulate creating .mo files.\n \"\"\"\n pass\n\ndef load_translations(langua... | trial_gpt4o_5 | {
"original_instruction": "### Internationalization with `gettext` in Python\n\n**Objective:**\n\nDevelop a Python module that supports multiple languages using the GNU `gettext` and its class-based API. Create application logic that dynamically switches between two languages: English and Spanish. \n\n**Problem State... | 0.559689 | Docs: Python310_34497 | C | [
"prepare_translation_files",
"load_translations",
"main_language_program"
] | 3 | [
[
"load_translations",
"prepare_translation_files"
],
[
"main_language_program",
"load_translations"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0441623d7c958fa0e72e5e4e27b7b7dad3396b17 | 5c8d00febb83a70affe427d9ae4cbfaf55355f65 | |||
v1.0 | complete | Docs | Docs: Python310_34568_C | import crypt
import hmac
def register_user(username: str, password: str) -> dict:
""" Register a user with a hashed password.
Args:
username (str): The username of the user.
password (str): The plaintext password of the user.
Returns:
dict: A dictionary with the username as the key an... | import crypt
import hmac
def register_user(username: str, password: str) -> dict:
"""
Registers a user by hashing the password and storing it in a dictionary.
"""
salt = generate_salt(crypt.METHOD_SHA512)
hashed_password = crypt.crypt(password, salt)
return {username: hashed_password}
def veri... | import pytest
from solution import register_user, verify_user, generate_salt, crypt
def test_register_user():
user_db = register_user("john_doe", "securepassword123")
assert "john_doe" in user_db
assert user_db["john_doe"].startswith("$6$") # SHA-512 identifier
def test_verify_user_correct_password():
... | [
{
"docstring": "Registers a user by hashing the password and storing it in a dictionary.",
"function_declaration": "def register_user(username, password):",
"function_name": "register_user",
"parameter_list": "(username, password)"
},
{
"docstring": "Verifies a user's password against the st... | [
1,
1,
1,
1,
0,
0,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import crypt\nimport hmac\n\ndef register_user(username: str, password: str) -> dict:\n \"\"\"Register a user with a hashed password.\"\"\"\n salt = crypt.mksalt(... | trial_gpt4o_9 | {
"original_instruction": "Password Management System\nYou are required to implement a simple password management system that allows users to register with a hashed password and later verify their login credentials. Your task is to create three functions using the `crypt` module:\n\n1. **`register_user(username: str,... | 0.730146 | Docs: Python310_34568 | C | [
"register_user",
"verify_user",
"generate_salt"
] | 3 | [
[
"register_user",
"generate_salt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5619b1f3d4914bf633fc4fe50aec34ae4e53b478 | 577095157853badf702f985a21b017268adbcc04 | |||
v1.0 | complete | Docs | Docs: Python310_34155_C | import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List, Dict
def fetch_content(url: str) -> (str, str):
"""Fetch the content of the provided URL.
Args:
url (str): The URL to fetch the content from.
Returns:
(str, str): A tuple containing the URL and... | import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List, Dict
def fetch_content(url: str) -> (str, str):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
return url, response.text
except (requests.ConnectionError, ... | from solution import concurrent_scraper
from unittest.mock import patch
def mock_requests_get(url, timeout=10):
class MockResponse:
def __init__(self, url):
self.url = url
if "fail" in url:
self.status_code = 404
self.text = None
else:
... | [
{
"docstring": null,
"function_declaration": "def fetch_content(url):",
"function_name": "fetch_content",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def concurrent_scraper(urls):",
"function_name": "concurrent_scraper",
"parameter_list": "(urls)"
... | [
1,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List, Dict\n\ndef fetch_content(url: str) -> (str, str):\n try:\... | trial_gpt4o_0 | {
"original_instruction": "**Concurrent Web Scraper with Thread Pool**\n\nYou are required to implement a web scraper that fetches the content from a list of URLs concurrently using the `concurrent.futures` module's `ThreadPoolExecutor`. Your task is to ensure efficient and thread-safe handling of the fetched data.\n... | 0.657646 | Docs: Python310_34155 | C | [
"fetch_content",
"concurrent_scraper"
] | 2 | [
[
"concurrent_scraper",
"fetch_content"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | a2af2947c6f361053a9df147e1b06811240f6956 | 0ebacbb2e00fe114588792bb09fa21335e5a20a0 | |||
v1.0 | complete | Docs | Docs: Python310_34881_C | import asyncio
import random
async def async_fetch_data(identifier):
""" Simulates fetching data for a given identifier by
asynchronously waiting for a random amount of time
and then returning a dictionary with the identifier and random data.
>>> asyncio.run(async_fetch_data(1))
Fetching data for... | import asyncio
import random
async def async_fetch_data(identifier):
"""
Simulates fetching data for a given identifier.
"""
print(f"Fetching data for id {identifier}")
await asyncio.sleep(random.uniform(0.1, 3))
data = {"id": identifier, "data": random.randint(100, 1000)}
return data
asyn... | import asyncio
import pytest
from solution import async_fetch_data, async_process_data
@pytest.mark.asyncio
async def test_async_fetch_data():
"""
Tests the async_fetch_data for a given identifier.
"""
result = await async_fetch_data(1)
assert "id" in result
assert "data" in result
assert r... | [
{
"docstring": "Sets up the asyncio event loop to run the async_process_data function with a sample list of identifiers.",
"function_declaration": "def main():",
"function_name": "main",
"parameter_list": "()"
}
] | [
1,
0,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\n\nasync def async_fetch_data(identifier):\n \"\"\"\n Coroutine to fetch data for given identifier.\n Simulates asynchronous I/O ... | trial_gpt4o_2 | {
"original_instruction": "**Asynchronous Execution with Coroutines**\n\n**Objective:**\nImplement a function that simulates asynchronous tasks using Python's coroutine and asyncio features. This task will assess the understanding of coroutines and the ability to work with asynchronous programming.\n\n**Instructions:... | 0.598748 | Docs: Python310_34881 | C | [
"async_fetch_data",
"async_process_data",
"main"
] | 3 | [
[
"async_process_data",
"async_fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a7bb295992b0e8b57a587ca1e5b3219c6fa025a7 | 48704e5d73fce6498e7dd9432a6b9a2cc5093321 | |||
v1.0 | complete | Docs | Docs: Python310_34378_C | import sqlite3
from typing import List, Tuple, Dict
def setup_database(file_path: str) -> None:
""" Set up the SQLite database with the required 'books' table.
Args:
file_path (str): Path to the SQLite database file.
Returns:
None
"""
def insert_books(file_path: str, books: List[Tupl... | import sqlite3
def setup_database(file_path):
"""
Set up the SQLite database with the required 'books' table.
"""
conn = sqlite3.connect(file_path)
cursor = conn.cursor()
create_table_query = """
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY,
title TEXT,
... | import os
import pytest
from solution import setup_database, insert_books, fetch_highly_rated_books, register_uppercase_function
DATABASE_PATH = 'test_library.db'
def setup_module(module):
# Setup database
setup_database(DATABASE_PATH)
def teardown_module(module):
# Clean up test database file
os.rem... | [
{
"docstring": "Set up the SQLite database with the required 'books' table.",
"function_declaration": "def setup_database(file_path):",
"function_name": "setup_database",
"parameter_list": "(file_path)"
},
{
"docstring": "Insert multiple book records into the 'books' table.",
"function_d... | [
1,
1,
1,
1,
1,
1,
0,
1,
0,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sqlite3\n\ndef setup_database(file_path):\n conn = sqlite3.connect(file_path)\n cursor = conn.cursor()\n cursor.execute('''\n CREATE TABLE books ... | trial_gpt4o_9 | {
"original_instruction": "#### Objective:\nThis coding question assesses the understanding and application of the `sqlite3` module's core functionalities, including database connections, executing SQL, and creating custom SQL functions.\n\n#### Problem Statement:\n\nAssume you are developing a personal library manag... | 0.630164 | Docs: Python310_34378 | C | [
"setup_database",
"insert_books",
"fetch_highly_rated_books",
"uppercase",
"register_uppercase_function"
] | 5 | [
[
"register_uppercase_function",
"uppercase"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c0217252ffb537c6cfb69c54362327cf21e4d9ec | 754acf59c9641735df76fbe8a4f00382b0aac739 | |||
v1.0 | complete | Docs | Docs: Python310_35067_C | import gc
def log_collection(phase, info):
pass
def analyze_memory_usage():
""" Analyzes and reports memory usage patterns using the gc module.
This function performs the following tasks:
1. Disables automatic garbage collection.
2. Registers a callback that logs the start and stop of garbage coll... | import gc
def log_collection(phase, info):
if phase == "start":
print(f"Garbage collection started for generation {info['generation']}")
elif phase == "stop":
print(f"Garbage collection finished: Collected: {info['collected']}, Uncollectable: {info['uncollectable']}")
def analyze_memory_usage(... | def test_analyze_memory_usage(capsys):
# Run the analysis
analyze_memory_usage()
# Capture the printed output
captured = capsys.readouterr()
# Check if the mandatory output lines are present
assert "Garbage collection started" in captured.out
assert "Garbage collection finished" in cap... | [
{
"docstring": null,
"function_declaration": "def log_collection(phase, info):",
"function_name": "log_collection",
"parameter_list": "(phase, info)"
},
{
"docstring": null,
"function_declaration": "def analyze_memory_usage():",
"function_name": "analyze_memory_usage",
"parameter... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import gc\n\ndef log_collection(phase, info):\n if phase == \"start\":\n print(f\"Garbage collection started for generation {info['generation']}\")\n elif ... | trial_gpt4o_0 | {
"original_instruction": "### Garbage Collection Management and Analysis\n\n#### Problem Statement:\nYou are tasked with writing a Python function that analyzes and reports memory usage patterns using the `gc` module. This function should:\n\n1. **Disable automatic garbage collection** to take full control of memory... | 0.426166 | Docs: Python310_35067 | C | [
"log_collection",
"analyze_memory_usage"
] | 2 | [
[
"analyze_memory_usage",
"log_collection"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 574a122951292509ff0e0dae3be5a4db61c5fcb0 | d124181f14bd092630d376b19a09f0c4eb465499 | |||
v1.0 | complete | Docs | Docs: Scikit_34427_C | from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, HashingVectorizer
def extract_features(reviews, vectorizer_type):
"""Implement feature extraction using CountVectorizer, TfidfVectorizer, or HashingVectorizer.
Args:
reviews (list of str): A list of movie reviews.
... | from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, HashingVectorizer
def extract_features(reviews, vectorizer_type):
if vectorizer_type == "CountVectorizer":
vectorizer = CountVectorizer()
elif vectorizer_type == "TfidfVectorizer":
vectorizer = TfidfVectorizer()
e... | import pytest
from solution import extract_features, compare_vectorizers
reviews = [
"The movie was fantastic! I loved it.",
"Quite dull and boring. Not my type.",
"An average movie with decent performances.",
]
def test_extract_features_countvectorizer():
features, feature_names = extract_features(re... | [
{
"docstring": null,
"function_declaration": "def extract_features(reviews, vectorizer_type):",
"function_name": "extract_features",
"parameter_list": "(reviews, vectorizer_type)"
},
{
"docstring": null,
"function_declaration": "def compare_vectorizers(reviews):",
"function_name": "c... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, HashingVectorizer\n\ndef extract_features(reviews, vectorizer_type):\n if vectorizer_ty... | trial_gpt4o_0 | {
"original_instruction": "**Title**: Implementing and Comparing Feature Extraction Techniques\n\n**Objective**: The goal of this assessment is to evaluate your understanding of feature extraction techniques provided by `scikit-learn` and your ability to implement and compare different methods on a text dataset.\n\n*... | 0.674308 | Docs: Scikit_34427 | C | [
"extract_features",
"compare_vectorizers"
] | 2 | [
[
"compare_vectorizers",
"extract_features"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sklearn"
] | false | be4217dd057613d33815c5364055e834cfea61e0 | 421da94e836855782837dc98cf79dec61c70036a | |||
v1.0 | complete | Docs | Docs: Pytorch_34758_C | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.utils.data as data
def setup_mps_device(seed: int) -> torch.device:
"""
Sets up the MPS device if available and sets the seed for reproducibility.
Args:
seed (int): The seed for random n... | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.utils.data as data
import time
def setup_mps_device(seed: int) -> torch.device:
"""
Sets up the MPS device if available and sets the seed for reproducibility.
Args:
seed (int): The seed ... | from solution import setup_mps_device, query_memory, empty_cache, train_network
import torch
import torch.nn as nn
import torch.utils.data as data
def test_setup_mps_device():
if torch.has_mps:
device = setup_mps_device(42)
assert device.type == "mps"
else:
try:
setup_mps_de... | [
{
"docstring": "Sets up the MPS device if available and sets the seed for reproducibility.\n\nArgs:\n seed (int): The seed for random number generation.\n\nReturns:\n torch.device: The MPS device object.\n\nRaises:\n RuntimeError: If MPS device is not available.",
"function_declaration": "def setup... | [
1,
1,
0,
1,
1,
0,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data\n\ndef setup_mps_device(seed: int) -> torch.device:\n \"\"\"\n Sets ... | trial_gpt4o_3 | {
"original_instruction": "### PyTorch MPS Memory Management and Profiling Task\n\n#### Objective\nImplement a PyTorch-based training loop for a simple neural network on an MPS device. The task is designed to assess your understanding of memory management, profiling, and handling random states in the context of Apple... | 0.516842 | Docs: Pytorch_34758 | C | [
"setup_mps_device",
"query_memory",
"empty_cache",
"train_network"
] | 4 | [
[
"train_network",
"empty_cache"
],
[
"train_network",
"query_memory"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 18f5d7dce3b6f2b4525a8d03794ba2af2cd853f3 | 24a2cb320a91f72467e1ac3934440c26ac3ba160 | |||
v1.0 | complete | Docs | Docs: Python310_34268_C | import argparse
import json
import os
def load_store(file):
"""Load the key-value store from a JSON file."""
if not os.path.exists(file):
return {}
with open(file, 'r') as f:
return json.load(f)
def save_store(file, store):
"""Save the key-value store to a JSON file."""
with open(f... | import argparse
import json
import os
def load_store(file):
if not os.path.exists(file):
return {}
with open(file, 'r') as f:
return json.load(f)
def save_store(file, store):
with open(file, 'w') as f:
json.dump(store, f, indent=4)
def add_entry(file, key, value):
store = load... | import os
import json
import pytest
from solution import add_entry, remove_entry, update_entry, get_entry
def setup_function(function):
""" Set up a clean slate for each test function by creating a fresh JSON file. """
initial_data = {"name": "Alice"}
with open('test_store.json', 'w') as f:
json.du... | [
{
"docstring": null,
"function_declaration": "def load_store(file):",
"function_name": "load_store",
"parameter_list": "(file)"
},
{
"docstring": null,
"function_declaration": "def save_store(file, store):",
"function_name": "save_store",
"parameter_list": "(file, store)"
},
... | [
1,
0,
1,
1,
1,
1,
1,
1,
0,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import argparse\nimport json\nimport os\n\ndef add_entry(file, key, value):\n if os.path.exists(file):\n with open(file, 'r') as f:\n data = json.l... | trial_gpt4o_6 | {
"original_instruction": "#### Problem Statement\n\nYou are tasked with creating a command-line utility using the `argparse` module in Python. This utility will be called `dbtool` and it will manage a simple key-value store in a JSON file. The utility should support the following sub-commands:\n\n1. **add**: Adds a ... | 0.680057 | Docs: Python310_34268 | C | [
"load_store",
"save_store",
"add_entry",
"remove_entry",
"update_entry",
"get_entry",
"dbtool"
] | 7 | [
[
"add_entry",
"load_store"
],
[
"add_entry",
"save_store"
],
[
"dbtool",
"add_entry"
],
[
"dbtool",
"get_entry"
],
[
"dbtool",
"remove_entry"
],
[
"dbtool",
"update_entry"
],
[
"get_entry",
"load_store"
],
[
"remove_entry",
... | 11 | [] | false | [] | false | pytest | true | [] | true | 53623e248c05468a6ccb9ef05ec05ada057756bf | 95d5f1cdb6bf24bc192793d8c48c5325759cbfe8 | |||
v1.0 | complete | Docs | Docs: Python310_34866_C | import asyncio
import logging
import random
from concurrent.futures import ThreadPoolExecutor
# Setup logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Enable debug mode for asyncio
asyncio.get_event_loop().set_debug(True)
async def io_task(task_id):
"""Simulate an I/O-bound... | import asyncio
import logging
import random
from concurrent.futures import ThreadPoolExecutor
# Setup logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Enable debug mode for asyncio
asyncio.get_event_loop().set_debug(True)
async def io_task(task_id):
logger.debug(f"Starting ... | import asyncio
import logging
from unittest.mock import patch
from solution import io_task, cpu_task, process_tasks
# Enable logging for unit tests
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def test_io_task_event_loop():
async def test_coroutine():
with patch('asyncio.s... | [
{
"docstring": null,
"function_declaration": "def cpu_task(task_id):",
"function_name": "cpu_task",
"parameter_list": "(task_id)"
}
] | [
0,
0,
0,
1,
1,
1,
1,
0,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport logging\nimport random\nfrom concurrent.futures import ThreadPoolExecutor\n\n# Setup logging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = ... | trial_gpt4o_3 | {
"original_instruction": "### Advanced Python 3.10 asyncio Programming Assessment\n\nIn this assessment, you will demonstrate your understanding of the asyncio library and advanced asynchronous programming concepts in Python. Specifically, you will need to implement an asynchronous solution that involves running tas... | 0.522731 | Docs: Python310_34866 | C | [
"io_task",
"cpu_task",
"process_tasks"
] | 3 | [
[
"process_tasks",
"cpu_task"
],
[
"process_tasks",
"io_task"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7c09f2b358fa4e46b0975195307dfad96e6048f2 | 05952eda7ef280f1c7d08eefe18f03284e3cd93e | |||
v1.0 | complete | Docs | Docs: Python310_34436_C | async def process_data(data):
""" Processes the input list of dictionaries to filter and transform data.
Filters people older than 25 years with a score greater than or equal to 70.
Returns their names in uppercase and emails in lowercase.
>>> data = [
... {'name': 'Alice', 'age': 30, 'email': 'A... | import asyncio
async def process_data(data):
for person in data:
if person['age'] > 25 and person['score'] >= 70:
yield {'name': person['name'].upper(), 'email': person['email'].lower()}
async def fetch_results(data):
results = []
async for result in process_data(data):
results... | import asyncio
from solution import process_data, fetch_results
def test_process_data():
data = [
{'name': 'Alice', 'age': 30, 'email': 'Alice@example.com', 'score': 85},
{'name': 'Bob', 'age': 22, 'email': 'Bob@example.com', 'score': 90},
{'name': 'Charlie', 'age': 27, 'email': 'Charlie@ex... | [] | [
1,
1,
1,
0,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def process_data(data):\n \"\"\"\n Asynchronous generator that processes the dataset based on given conditions.\n Yields a dictionary w... | trial_gpt4o_4 | {
"original_instruction": "#### Title: Advanced Data Processing with Generators and Comprehensions\n\n#### Objective:\nTo assess the student's ability to utilize comprehensions, generators, and asynchronous generators to process and manipulate data efficiently in Python.\n\n#### Problem Statement:\nYou are given a la... | 0.57296 | Docs: Python310_34436 | C | [
"process_data",
"fetch_results"
] | 2 | [
[
"fetch_results",
"process_data"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 19d0dd66a2b9a278d97a281a9a58aff563dce637 | ddb8fb9041e62b24f4086046596bd08ac29a9367 | |||
v1.0 | complete | Docs | Docs: Python310_35371_C | def calculate_sum(numbers):
"""
Returns the sum of the numbers in the input list.
"""
def mean_of_list(number_list):
"""
Returns the mean of the numbers in the input list.
Raises ValueError if the list is empty.
"""
def main():
"""
Main function to print the mean of a list of n... | def calculate_sum(numbers):
"""
Returns the sum of the numbers in the input list.
"""
total = 0
for num in numbers:
total += num
return total
def mean_of_list(number_list):
"""
Returns the mean of the numbers in the input list.
Raises ValueError if the list is empty.
"""... | from solution import calculate_sum, mean_of_list
def test_calculate_sum():
assert calculate_sum([1, 2, 3, 4]) == 10
assert calculate_sum([0]) == 0
assert calculate_sum([-1, -2, -3, -4]) == -10
def test_mean_of_list():
assert mean_of_list([1, 2, 3, 4]) == 2.5
assert mean_of_list([10, 20, 30, 40, 50... | [
{
"docstring": "Returns the sum of the numbers in the input list.",
"function_declaration": "def calculate_sum(numbers):",
"function_name": "calculate_sum",
"parameter_list": "(numbers)"
},
{
"docstring": "Returns the mean of the numbers in the input list.\nRaises ValueError if the list is e... | [
1,
1,
0,
0,
1,
1,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_sum(numbers):\n total = 0\n for num in numbers:\n total += num\n return total\n\ndef mean_of_list(number_list):\n if not number_list:\n... | trial_gpt4o_1 | {
"original_instruction": "### Python Debugger (pdb) Coding Assessment\n\n#### Objective:\nDemonstrate your understanding and practical skills of using the Python Debugger (`pdb` module) by debugging a given piece of code to analyze its flow, detect, and resolve an issue.\n\n#### Problem Statement:\nYou are provided ... | 0.597904 | Docs: Python310_35371 | C | [
"calculate_sum",
"mean_of_list",
"main"
] | 3 | [
[
"mean_of_list",
"calculate_sum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b7310c11ccab6d08a1a58abf3876522761655acd | 0d5f5021e2e95cac5e58fd0955c79a3c8548ad81 | |||
v1.0 | complete | Docs | Docs: Python310_35573_C | import os
from contextlib import contextmanager, ExitStack
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)... | import os
from contextlib import contextmanager, ExitStack
import logging
# Setup a logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.ad... | import os
import pytest
from solution import process_files, logger
def test_process_files_all_success(tmpdir):
file_paths = [os.path.join(tmpdir, f"file{i}.txt") for i in range(3)]
data = "Hello, World!"
process_files(file_paths, data, logger)
for file_path in file_paths:
with open(file_path, ... | [
{
"docstring": "A custom context manager to handle file operations.",
"function_declaration": "def FileManager(file_path, mode, logger):",
"function_name": "FileManager",
"parameter_list": "(file_path, mode, logger)"
},
{
"docstring": "Opens multiple files and writes data to them using ExitS... | [
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 os\nfrom contextlib import contextmanager, ExitStack\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n@context... | trial_gpt4o_1 | {
"original_instruction": "#### Objective\nDemonstrate your understanding and practical usage of the `contextlib` module from Python's standard library. Specifically, focus on creating custom context managers and using `ExitStack` to manage multiple resources.\n\n#### Problem Statement\n\nYou are tasked with writing ... | 0.494337 | Docs: Python310_35573 | C | [
"FileManager",
"process_files"
] | 2 | [
[
"process_files",
"FileManager"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 12dc875202b65c3f7f43520ef7e0dcad735b53e7 | 75c0aa2081616a4a9232acfe0395914fc2289395 | |||
v1.0 | complete | Docs | Docs: Python310_34263_C | import socket
import threading
def start_server(host: str, port: int) -> None:
""" Start a chat server that listens on the given host and port, and handles multiple clients.
>>> start_server('127.0.0.1', 12345)
"""
# TODO: Implement the server code here
def start_client(host: str, port: int) -> None:
... | import socket
import threading
clients = []
def broadcast(message, client_socket):
for client in clients:
if client != client_socket:
try:
client.send(message)
except:
remove(client)
def handle_client(client_socket):
while True:
try:
... | import threading
import socket
import time
from solution import start_server, start_client
# To avoid actual network use during tests, we'll need to mock networking.
# However, we'll provide a simple pattern for testing with real sockets for integration testing.
def test_start_server():
server_thread = threading.... | [
{
"docstring": null,
"function_declaration": "def broadcast(message, client_socket):",
"function_name": "broadcast",
"parameter_list": "(message, client_socket)"
},
{
"docstring": null,
"function_declaration": "def handle_client(client_socket):",
"function_name": "handle_client",
... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\nimport threading\n\nclients = []\n\ndef broadcast_message(message, sender_socket):\n for client in clients:\n if client != sender_socket:\n ... | trial_gpt4o_5 | {
"original_instruction": "<|Analysis Begin|>\n\nThe provided documentation focuses on Python's `socket` module, which is a low-level networking interface that allows Python programs to communicate over networks using the BSD socket interface. The module provides functions for creating socket objects, binding them to... | 0.664741 | Docs: Python310_34263 | C | [
"broadcast",
"handle_client",
"remove",
"start_server",
"start_client"
] | 5 | [
[
"broadcast",
"remove"
],
[
"handle_client",
"broadcast"
],
[
"handle_client",
"remove"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 175bd086b551ff55bb9c56a4c9e7f6ab1676728b | 8748f69852475bae8f58e26ce114711461f07fe2 | |||
v1.0 | complete | Docs | Docs: Python310_35490_C | import asyncio
async def handle_client(reader, writer):
"""
Function to handle communication with a client.
Parameters:
- reader: asyncio StreamReader object to read data from the client.
- writer: asyncio StreamWriter object to send data to the client.
Reads data sent by the client, reverses i... | import asyncio
# Function to handle client connections
async def handle_client(reader, writer):
addr = writer.get_extra_info('peername')
print(f"Connected with {addr}")
while True:
data = await reader.read(100)
message = data.decode()
if not data:
break
print(f"... | import pytest
import asyncio
from solution import handle_client, run_server, run_client
@pytest.mark.asyncio
async def test_server_client_interaction():
host = '127.0.0.1'
port = 8888
# Start the server
server_coroutine = run_server(host, port)
server_task = asyncio.create_task(server_coroutine)
... | [] | [
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\n# Function to handle client connections\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"Connecte... | trial_gpt4o_0 | {
"original_instruction": "#### Objective\nDemonstrate your understanding of Python 3.10's `asyncio` package by implementing an asynchronous TCP server and client that can communicate with each other. This will test your ability to manage event loops, create tasks, handle async networking, and properly use transports... | 0.683975 | Docs: Python310_35490 | C | [
"handle_client",
"run_server",
"run_client"
] | 3 | [
[
"run_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 21ec99717da415c643a4f90ef857d7715f35a524 | 5480041e5679ee740475157e2fefdcce5682e799 | |||
v1.0 | complete | Docs | Docs: Python310_34994_C | import functools
@functools.cache
def cached_factorial(n: int) -> int:
""" Computes and caches the factorial of a number using recursion.
>>> cached_factorial(0)
1
>>> cached_factorial(5)
120
"""
pass
def sum_of_factorials(number_list: List[int]) -> int:
""" Computes the sum of factori... | import functools
@functools.cache
def cached_factorial(n):
"""
Computes and caches the factorial of number n using recursion.
Parameters:
n (int): The number to compute the factorial of.
Returns:
int: The factorial of n.
"""
if n == 0:
return 1
else:
return... | from solution import cached_factorial, sum_of_factorials
def test_cached_factorial_base_case():
assert cached_factorial(0) == 1
def test_cached_factorial_small_numbers():
assert cached_factorial(1) == 1
assert cached_factorial(2) == 2
assert cached_factorial(3) == 6
assert cached_factorial(4) == 2... | [
{
"docstring": "Computes and caches the factorial of number n using recursion.\n\nParameters:\nn (int): The number to compute the factorial of.\n\nReturns:\nint: The factorial of n.",
"function_declaration": "def cached_factorial(n):",
"function_name": "cached_factorial",
"parameter_list": "(n)"
}... | [
0,
1,
1,
0,
1,
0,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import functools\n\n@functools.cache\ndef cached_factorial(n: int) -> int:\n \"\"\"\n Compute the factorial of a number using recursion and cache the results.\n ... | trial_gpt4o_9 | {
"original_instruction": "### Question: Caching and Functional Programming with `functools`\n\nYou are given a function `expensive_calculation()` that performs an expensive calculation and a list of numbers. Implement two functions, `cached_factorial()` to compute and cache the factorial of numbers using `functools.... | 0.707831 | Docs: Python310_34994 | C | [
"cached_factorial",
"sum_of_factorials"
] | 2 | [
[
"sum_of_factorials",
"cached_factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d1af809786540ec5a05696c03a2283488b3a0d82 | c99a41681a553fc34976f5d9d4d9d700a257c9a0 | |||
v1.0 | complete | Docs | Docs: Python310_35595_C | from typing import List, Tuple, Union
def fetch_urls_concurrently(urls: List[str]) -> List[Tuple[str, Union[str, None]]]:
""" Fetches the content of URLs concurrently.
Args:
urls (List[str]): A list of URLs.
Returns:
List[Tuple[str, Union[str, None]]]: A list of tuples where the fi... | from typing import List, Tuple, Union
import concurrent.futures
import requests
def fetch_url(url: str) -> Tuple[str, Union[str, None]]:
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # Check if the request was successful
return (url, response.text)
except req... | import pytest
from solution import fetch_urls_concurrently
def mock_requests_get(url, timeout):
if url == "https://example.com":
class MockResponse:
def raise_for_status(self):
pass
@property
def text(self):
return "Example Do... | [
{
"docstring": null,
"function_declaration": "def fetch_url(url):",
"function_name": "fetch_url",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def fetch_urls_concurrently(urls):",
"function_name": "fetch_urls_concurrently",
"parameter_list": "(urls)"... | [
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 typing import List, Tuple, Union\nimport concurrent.futures\nimport requests\n\ndef fetch_url(url: str) -> Tuple[str, Union[str, None]]:\n try:\n respons... | trial_gpt4o_0 | {
"original_instruction": "**Python Coding Assessment Question**\n\n**Objective:**\nImplement a function that launches multiple tasks in parallel to process a list of URLs concurrently, fetch their content, and return the results. Handle potential exceptions gracefully and ensure optimal performance.\n\n**Problem Sta... | 0.710019 | Docs: Python310_35595 | C | [
"fetch_url",
"fetch_urls_concurrently"
] | 2 | [
[
"fetch_urls_concurrently",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 161f339a8aa5d64f0a6f54490a0c8b9d1b841686 | e8b09d2bc69b277857c065c32d9589a878f0defc | |||
v1.0 | complete | Docs | Docs: Python310_35283_C | import sqlite3
from typing import List, Tuple
def manage_student_records(students: List[Tuple[int, str, List[int]]]) -> List[Tuple[int, str, List[int]]]:
""" Interact with an SQLite database to manage student records.
This function performs the following operations:
1. Create a new SQLite database fil... | import sqlite3
import json
from typing import List, Tuple
def adapt_list(lst):
return json.dumps(lst)
def convert_list(txt):
return json.loads(txt)
def manage_student_records(students: List[Tuple[int, str, List[int]]]) -> List[Tuple[int, str, List[int]]]:
# Register adapters and converters to handle list... | import sqlite3
import os
from solution import manage_student_records # assuming the function resides in solution.py
import pytest
def test_manage_student_records():
# Test data
students = [
(1, "Alice", [85, 90, 88]),
(2, "Bob", [78, 82, 85]),
(3, "Charlie", [92, 85, 87])
]
... | [
{
"docstring": null,
"function_declaration": "def adapt_list(lst):",
"function_name": "adapt_list",
"parameter_list": "(lst)"
},
{
"docstring": null,
"function_declaration": "def convert_list(txt):",
"function_name": "convert_list",
"parameter_list": "(txt)"
},
{
"docstri... | [
0,
1,
1,
0,
0,
0,
1,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sqlite3\nfrom typing import List, Tuple\n\n\ndef adapt_list(lst):\n return ','.join(map(str, lst))\n\n\ndef convert_to_list(scores_str):\n if scores_str:\n... | trial_gpt4o_7 | {
"original_instruction": "### SQLite3 Database Interaction and Custom Python Types\n\n**Objective:**\nImplement a Python function to interact with an SQLite database. This function should perform the following operations:\n1. Create a new SQLite database file (`students.db`).\n2. Create a table named `students` with... | 0.617021 | Docs: Python310_35283 | C | [
"adapt_list",
"convert_list",
"manage_student_records"
] | 3 | [
[
"manage_student_records",
"adapt_list"
],
[
"manage_student_records",
"convert_list"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1064a6eaba47da52f4eb8fe0997f4d2fe8a16230 | 16ead8148cc8aaa8143ff49762d52eb774b2a217 | |||
v1.0 | complete | Docs | Docs: Seaborn_35415_C | import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
def sinplot(n=10, flip=1):
x = np.linspace(0, 14, 100)
for i in range(1, n + 1):
plt.plot(x, np.sin(x + i * .5) * (n + 2 - i) * flip)
def customize_and_compare_plots(data: np.ndarray) -> None:
""" Generate and save various pl... | import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
def sinplot(n=10, flip=1):
x = np.linspace(0, 14, 100)
for i in range(1, n + 1):
plt.plot(x, np.sin(x + i * .5) * (n + 2 - i) * flip)
def customize_and_compare_plots(data: np.ndarray) -> None:
# Default plot
sns.set_theme... | import os
import numpy as np
from solution import customize_and_compare_plots
def test_customize_and_compare_plots():
data = np.random.rand(10, 3)
# Call the function to generate plots
customize_and_compare_plots(data)
# Check if all the required files are created
files = [
"default_plot.... | [
{
"docstring": null,
"function_declaration": "def sinplot(n=10, flip=1):",
"function_name": "sinplot",
"parameter_list": "(n=10, flip=1)"
},
{
"docstring": null,
"function_declaration": "def customize_and_compare_plots(data):",
"function_name": "customize_and_compare_plots",
"par... | [
0,
1,
0,
0,
0,
1,
0,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef sinplot(n=10, flip=1):\n x = np.linspace(0, 14, 100)\n for i in range(1, n + 1):... | trial_gpt4o_9 | {
"original_instruction": "### Question: Customize and Compare Plot Aesthetics using Seaborn\n\nYou are provided with a dataset and asked to create several plots to illustrate different aesthetic styles and figure contexts using the seaborn package. Your task is to demonstrate your understanding by implementing a fun... | 0.707838 | Docs: Seaborn_35415 | C | [
"sinplot",
"customize_and_compare_plots"
] | 2 | [
[
"customize_and_compare_plots",
"sinplot"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"seaborn"
] | false | b21f75da4972d237010cfcc8a4a891a988473581 | 406b6051395072c8ea8815c37c194261dc547182 | |||
v1.0 | complete | Docs | Docs: Python310_34987_C | import asyncio
import platform
async def run_platform_specific_tasks(interval: int, message: str):
"""Run a periodic task that prints a message at a given interval, with platform-specific event loop handling.
Args:
interval (int): The interval in seconds between each message print.
message (str): ... | import asyncio
import platform
async def run_periodic_task(interval, message):
while True:
print(message)
await asyncio.sleep(interval)
def run_platform_specific_tasks(interval, message):
# Configure the event loop based on the platform
if platform.system() == 'Windows':
loop = asy... | import asyncio
import pytest
import platform
from solution import run_platform_specific_tasks
@pytest.mark.asyncio
async def test_run_platform_specific_tasks():
async def test_task():
run_platform_specific_tasks(1, "Test message")
if platform.system() == 'Windows':
loop = asyncio.ProactorE... | [
{
"docstring": null,
"function_declaration": "def run_platform_specific_tasks(interval, message):",
"function_name": "run_platform_specific_tasks",
"parameter_list": "(interval, message)"
}
] | [
1,
0,
1,
1,
1,
0,
1,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport platform\n\nasync def run_platform_specific_tasks(interval, message):\n \"\"\"\n Runs a simple I/O-bound task that periodically prints a me... | trial_gpt4o_4 | {
"original_instruction": "#### Objective:\nYou are required to implement a cross-platform Python function using the `asyncio` module. The function should demonstrate your understanding of event loops and platform-specific constraints as highlighted in the provided documentation.\n\n#### Task:\nWrite a Python functio... | 0.587492 | Docs: Python310_34987 | C | [
"run_periodic_task",
"run_platform_specific_tasks"
] | 2 | [
[
"run_platform_specific_tasks",
"run_periodic_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3211a2fb0fa99cb46b410c33f99853f52a675f54 | 3cc5e61115ef21f9592bf0d274fc55afd80fd57a | |||
v1.0 | complete | Docs | Docs: Python310_34619_C | import hmac
import hashlib
def compute_hmac(filepath: str, key: bytes, digestmod: str) -> str:
"""
Computes the HMAC of a file.
Args:
filepath (str): The path to the file.
key (bytes): The secret key used for HMAC computation.
digestmod (str): The hash algorithm to use (e.g., "sha2... | import hmac
import hashlib
def compute_hmac(filepath, key, digestmod):
"""
Computes the HMAC of a file.
Args:
filepath (str): The path to the file.
key (bytes): The secret key used for HMAC computation.
digestmod (str): The hash algorithm to use (e.g., "sha256").
Returns:
... | import tempfile
import os
from solution import compute_hmac, check_file_integrity
def test_compute_hmac():
key = b'secret_key'
digestmod = 'sha256'
# Create a temporary file
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(b'Hello, this is a test file.')
... | [
{
"docstring": "Computes the HMAC of a file.\n\nArgs:\n filepath (str): The path to the file.\n key (bytes): The secret key used for HMAC computation.\n digestmod (str): The hash algorithm to use (e.g., \"sha256\").\n\nReturns:\n str: The computed HMAC as a hexadecimal string.",
"function_declar... | [
0,
1,
0,
0,
0,
1,
0,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hmac\nimport hashlib\n\ndef compute_hmac(filepath, key, digestmod):\n \"\"\"\n Compute the HMAC of a file using a given key and hash algorithm.\n\n Args... | trial_gpt4o_9 | {
"original_instruction": "### Secure File Integrity Checker using HMAC\n\nYou are required to implement a secure file integrity checker using the `hmac` module in Python. This program should read multiple files, compute their HMACs using a secret key and a specified hash algorithm, and verify if these files have bee... | 0.705266 | Docs: Python310_34619 | C | [
"compute_hmac",
"check_file_integrity"
] | 2 | [
[
"check_file_integrity",
"compute_hmac"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d39b39617264c31c54971d0d4633d3d831c9af94 | 9333fd2368c1736d3be4acad6133a08509945d8e | |||
v1.0 | complete | Docs | Docs: Python310_35378_C | from math import gcd
from typing import List
def prime_factorization_sum(n: int) -> int:
""" Calculate the sum of the greatest common divisors (GCDs)
of all unique pairs of the prime factors of n.
>>> prime_factorization_sum(18)
1
>>> prime_factorization_sum(28)
1
>>> prime_factorizati... | from math import gcd
def prime_factors(n):
"""
Return the prime factors of the given integer n.
"""
i = 2
factors = set()
while i * i <= n:
while (n % i) == 0:
factors.add(i)
n //= i
i += 1
if n > 1:
factors.add(n)
return factors
def prim... | import pytest
from solution import prime_factorization_sum
def test_prime_factorization_sum_basic():
assert prime_factorization_sum(18) == 1 # Prime factors: {2, 3}, GCD(2, 3) = 1
assert prime_factorization_sum(28) == 1 # Prime factors: {2, 7}, GCD(2, 7) = 1
assert prime_factorization_sum(100) == 1 # Pr... | [
{
"docstring": "Return the prime factors of the given integer n.",
"function_declaration": "def prime_factors(n):",
"function_name": "prime_factors",
"parameter_list": "(n)"
},
{
"docstring": "Calculate the sum of the greatest common divisors (GCDs)\nof all unique pairs of the prime factors ... | [
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": "from math import gcd\n\ndef prime_factors(n):\n factors = []\n # Checking for number of 2s that divide n\n while n % 2 == 0:\n if 2 not in factors:\n ... | trial_gpt4o_3 | {
"original_instruction": "## Problem Statement: Efficient Prime Factorization Sum\n\n### Objective\n\nWrite a Python function `prime_factorization_sum(n: int) -> int` that calculates the sum of the greatest common divisors (GCDs) of all unique pairs of the prime factors of a given integer `n`. The function should ut... | 0.758633 | Docs: Python310_35378 | C | [
"prime_factors",
"prime_factorization_sum"
] | 2 | [
[
"prime_factorization_sum",
"prime_factors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9d8402ad7c9f15beb0ce9e21595f1a6d3df69a30 | a37ecd8d60e89c03a62a69b942c649c035d1cf1a | |||
v1.0 | complete | Docs | Docs: Python310_34896_C | import asyncio
async def fetch_data(url: str) -> dict:
"""
Simulate an asynchronous network call to fetch data from a URL.
Parameters:
url (str): The URL to fetch data from.
Returns:
dict: A dictionary with the URL as the key and the fetched data as the value.
>>> asyncio.ru... | import asyncio
async def fetch_data(url: str) -> dict:
"""
Simulate an asynchronous network call to fetch data from a URL.
Parameters:
url (str): The URL to fetch data from.
Returns:
dict: A dictionary with the URL as the key and the fetched data as the value.
"""
await asynci... | import asyncio
from solution import fetch_data, gather_data
async def test_fetch_data():
url = "http://example.com/api/resource1"
expected_output = {url: f"data from {url}"}
assert await fetch_data(url) == expected_output
async def test_gather_data():
urls = [
"http://example.com/api/resource1... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def fetch_data(url: str) -> dict:\n \"\"\"\n Simulates an asynchronous network call to fetch data from a URL.\n \n Args:\n - url ... | trial_gpt4o_8 | {
"original_instruction": "Design a function that utilizes Python async/await syntax to perform asynchronous computations. The function should fetch data from multiple URLs concurrently, process this data, and return the results. This question will assess your understanding of Python's asynchronous programming facili... | 0.58375 | Docs: Python310_34896 | C | [
"fetch_data",
"gather_data"
] | 2 | [
[
"gather_data",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b3b01f11046f7808dd7d137ce614847d7091e98d | d0d75008f28bc7cfe1f0527c20df4a1fd5d73b99 | |||
v1.0 | complete | Docs | Docs: Python310_35379_C | from typing import List, Dict, Any
def parallel_web_scraping(urls: List[str], timeout: int) -> List[Dict[str, Any]]:
"""
Retrieve data from the given URLs concurrently using ThreadPoolExecutor.
[Example]
>>> urls = ["http://example.com/item1", "http://example.com/item2"]
>>> parallel_web_scraping(... | from typing import List, Dict, Any
import concurrent.futures
import requests
def fetch_data(url: str, timeout: int) -> Dict[str, Any]:
try:
response = requests.get(url, timeout=timeout)
response.raise_for_status()
data = response.json()
return {
"url": url,
"... | import pytest
from solution import parallel_web_scraping
from unittest.mock import patch
import requests
def mock_fetch_data(url: str, timeout: int):
if "timeout" in url:
raise requests.exceptions.Timeout()
elif "error" in url:
raise requests.exceptions.RequestException("General error")
el... | [
{
"docstring": null,
"function_declaration": "def fetch_data(url, timeout):",
"function_name": "fetch_data",
"parameter_list": "(url, timeout)"
},
{
"docstring": null,
"function_declaration": "def parallel_web_scraping(urls, timeout):",
"function_name": "parallel_web_scraping",
"... | [
0,
1,
1,
0,
1,
0,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict, Any\nimport concurrent.futures\nimport requests\n\ndef fetch_data(url: str, timeout: int) -> Dict[str, Any]:\n \"\"\"\n Fetches dat... | trial_gpt4o_8 | {
"original_instruction": "Parallel Web Scraping\n\n#### Context:\nYou are tasked with extracting specific data from multiple web pages concurrently. Each page contains items with structured data including `title`, `price`, and `availability`. You will use the `concurrent.futures` module to fetch and parse this data ... | 0.57796 | Docs: Python310_35379 | C | [
"fetch_data",
"parallel_web_scraping"
] | 2 | [
[
"parallel_web_scraping",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | f5e4bba9c6075d9ca710403b00bc79ce05942f44 | 1bf103ca37921e694f10ce1d3526757006bc6bc9 | |||
v1.0 | complete | Docs | Docs: Python310_35564_C | from typing import List
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch_content_length(url: str) -> str:
"""
Fetch the content of the URL and return the URL with its content length.
Returns a string "URL: length" or "URL: Error occurred".
"""
try:
r... | from typing import List
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch_content_length(url: str) -> str:
"""
Fetch the content of the URL and return the URL with its content length.
Returns a string "URL: length" or "URL: Error occurred".
"""
try:
r... | from solution import fetch_urls_concurrently, fetch_content_length
import requests
import pytest
from unittest.mock import patch
def test_fetch_content_length_success():
url = "http://example.com"
# Mock requests.get to return a response with content
with patch("requests.get") as mock_get:
mo... | [
{
"docstring": "Fetch the content of the URL and return the URL with its content length.\nReturns a string \"URL: length\" or \"URL: Error occurred\".",
"function_declaration": "def fetch_content_length(url):",
"function_name": "fetch_content_length",
"parameter_list": "(url)"
},
{
"docstrin... | [
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 concurrent.futures\nimport requests\nfrom typing import List\n\ndef fetch_url(url: str) -> str:\n try:\n response = requests.get(url)\n response... | trial_gpt4o_1 | {
"original_instruction": "**Objective:** Assess the student's understanding and ability to utilize the `concurrent.futures` module to manage parallel execution of tasks.\n\n**Problem Statement:**\n\nYou are tasked with processing a list of URLs to fetch their contents concurrently. Each URL must be fetched and its c... | 0.591898 | Docs: Python310_35564 | C | [
"fetch_content_length",
"fetch_urls_concurrently"
] | 2 | [
[
"fetch_urls_concurrently",
"fetch_content_length"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 0e33490b450e7ce3374e123bc7b72e8f62f0086c | 602868795084c1103d2d1b7c30bf8b46844e22bd | |||
v1.0 | complete | Docs | Docs: Pytorch_35167_C | import torch
import torch.nn as nn
def check_mps_availability():
""" Check for MPS Availability and set device
This function verifies if the MPS backend is available. If not, it handles the cases
where MPS backend is not available using appropriate error messages.
Raises:
EnvironmentError: If M... | import torch
import torch.nn as nn
def check_mps_availability():
if not torch.backends.mps.is_available():
if not torch.backends.mps.is_built():
message = "MPS not available because the current PyTorch install was not built with MPS enabled."
else:
message = "MPS not availab... | import pytest
import torch
from solution import check_mps_availability, tensor_operations_on_mps, run_neural_network_on_mps
def test_check_mps_availability():
try:
device = check_mps_availability()
assert str(device) == "mps"
except EnvironmentError:
assert True # If not available, the... | [] | [
0,
0,
1,
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": "import torch\nimport torch.nn as nn\n\n# Step 1: Check for MPS Availability and set device\nif not torch.backends.mps.is_available():\n if not torch.backends.mps.is_... | trial_gpt4o_7 | {
"original_instruction": "**Objective:**\n\nDesign a PyTorch program that utilizes the MPS backend for high-performance training on a MacOS device. Your program will create a neural network model, move it to the MPS device, and perform a series of tensor operations exclusively on the GPU. The program should also han... | 0.558242 | Docs: Pytorch_35167 | C | [
"check_mps_availability",
"tensor_operations_on_mps",
"run_neural_network_on_mps"
] | 3 | [
[
"run_neural_network_on_mps",
"check_mps_availability"
],
[
"tensor_operations_on_mps",
"check_mps_availability"
]
] | 2 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"torch"
] | false | 796dc43bf8b2e7b07a9cee7209e8a422d0296e28 | 1d16ca255091cbd75445980e64a093e53cc6feae | |||
v1.0 | complete | Docs | Docs: Python310_35599_C | import concurrent.futures
from typing import List, Dict
def count_word_in_files(word: str, file_paths: List[str]) -> Dict[str, int]:
"""
Count the occurrences of a word in a list of files concurrently using concurrent.futures.
Parameters:
word (str): The word to count in each file.
fil... | import concurrent.futures
from typing import List, Dict
def count_word_in_file(word: str, file_path: str) -> int:
"""
Helper function to count occurrences of a word in a single file.
"""
try:
with open(file_path, 'r') as file:
content = file.read()
return content.lower()... | import pytest
from solution import count_word_in_files
def test_count_word_in_files_single_file():
with open('test1.txt', 'w') as f:
f.write("example test example")
assert count_word_in_files("example", ["test1.txt"]) == {"test1.txt": 2}
def test_count_word_in_files_multiple_files():
with open... | [
{
"docstring": "Helper function to count occurrences of a word in a single file.",
"function_declaration": "def count_word_in_file(word, file_path):",
"function_name": "count_word_in_file",
"parameter_list": "(word, file_path)"
},
{
"docstring": "Count the occurrences of a word in a list of ... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\nfrom typing import List, Dict\n\ndef count_word_in_file(word: str, file_path: str) -> int:\n \"\"\"\n Helper function to count occurren... | trial_gpt4o_0 | {
"original_instruction": "#### Asynchronous File Processing\n\n**Objective:**\n\nImplement a function that processes a list of file paths in parallel to count the frequency of a specific word in each file. The function should use the `concurrent.futures` module to achieve parallelism, ensuring efficient processing. ... | 0.621968 | Docs: Python310_35599 | C | [
"count_word_in_file",
"count_word_in_files"
] | 2 | [
[
"count_word_in_files",
"count_word_in_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e048e02e3ec9b921489cbcccb78c6957cfdce90a | d18eea22c8679374ca7e372627b3e8d0eede6977 | |||
v1.0 | complete | Docs | Docs: Python310_34684_C | import math
from typing import List, Tuple, Dict
def compute_heavy_math(n: int) -> List[float]:
""" Performs extensive mathematical computations.
"""
pass
def profile_and_optimize(n: int) -> Tuple[List[float], Dict[str, float]]:
"""
Uses profiling and memory tracking to identify bottlenecks and o... | import cProfile
import tracemalloc
import math
from functools import lru_cache
from time import time
def compute_heavy_math(n):
result = []
for i in range(1, n+1):
val = math.factorial(i) ** 2 / math.sqrt(i)
result.append(val)
return result
def profile_and_optimize(n):
# Profiling the ... | import pytest
from solution import compute_heavy_math, profile_and_optimize
def test_compute_heavy_math():
results = compute_heavy_math(5)
expected = [
math.factorial(1) ** 2 / math.sqrt(1),
math.factorial(2) ** 2 / math.sqrt(2),
math.factorial(3) ** 2 / math.sqrt(3),
math.facto... | [
{
"docstring": null,
"function_declaration": "def compute_heavy_math(n):",
"function_name": "compute_heavy_math",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def profile_and_optimize(n):",
"function_name": "profile_and_optimize",
"parameter_list": "(n... | [
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 tracemalloc\nimport math\nfrom functools import lru_cache\nimport time\n\n# Original function\ndef compute_heavy_math(n):\n result = []\n ... | trial_gpt4o_5 | {
"original_instruction": "### Question: Analyzing and Optimizing Code with Python Profiling and Debugging Tools\n\nYou are given a function `compute_heavy_math` that performs extensive mathematical computations. This function is suspected of being inefficient and potentially having memory leaks. Your task is to use ... | 0.541693 | Docs: Python310_34684 | C | [
"compute_heavy_math",
"profile_and_optimize"
] | 2 | [
[
"profile_and_optimize",
"compute_heavy_math"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8d0a4c1a179dfc580ca1ee272f0d40aba51a7489 | e3c209f9cdea722655dda065a7034a2b91f8d3d6 | |||
v1.0 | complete | Docs | Docs: Pytorch_35361_C | import torch.futures
def compute_async(x: int) -> torch.futures.Future:
"""
Simulates an asynchronous computation that squares the input number.
Args:
x (int): The input number to be squared.
Returns:
torch.futures.Future: A future object that will hold the result of the computation.
... | import torch
import torch.futures
def compute_async(x: int) -> torch.futures.Future:
"""
Simulates an asynchronous computation that squares the input number.
Args:
x (int): The input number to be squared.
Returns:
torch.futures.Future: A future object that will hold the result of the ... | import pytest
from solution import compute_async, aggregate_futures
def test_compute_async():
future = compute_async(3)
assert future.wait() == 9
def test_aggregate_futures_single():
result = aggregate_futures([3])
assert result == 9
def test_aggregate_futures_multiple():
result = aggregate_futur... | [
{
"docstring": "Simulates an asynchronous computation that squares the input number.\n\nArgs:\nx (int): The input number to be squared.\n\nReturns:\ntorch.futures.Future: A future object that will hold the result of the computation.",
"function_declaration": "def compute_async(x):",
"function_name": "co... | [
1,
0,
0,
0,
0,
1,
1,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.futures\n\ndef compute_async(x: int) -> torch.futures.Future:\n \"\"\"\n Simulates an asynchronous computation that squares the input n... | trial_gpt4o_7 | {
"original_instruction": "**Asynchronous Computations with PyTorch Futures**\n\n**Objective:**\n\nYour task is to implement two functions using the `torch.futures` module to handle asynchronous computations. This will assess your understanding of managing futures and synchronizing their results.\n\n**Problem Stateme... | 0.517809 | Docs: Pytorch_35361 | C | [
"compute_async",
"aggregate_futures"
] | 2 | [
[
"aggregate_futures",
"compute_async"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 9f9b268e435a454dcd28f14dc562424a77d4222d | a6c4b138c709107de0feceb62973560a3c4f1f12 | |||
v1.0 | complete | Docs | Docs: Python310_35556_C | import asyncio
from typing import List
async def process_tasks(task_list: List[float], worker_count: int) -> float:
""" Process a list of tasks concurrently using asyncio.Queue with a given number of workers.
>>> asyncio.run(process_tasks([1.5, 2.0, 0.5, 3.0], 1)) >= sum([1.5, 2.0, 0.5, 3.0])
True
>>> ... | import asyncio
from typing import List
from time import time
async def worker(queue: asyncio.Queue):
while True:
task = await queue.get()
if task is None:
break
await asyncio.sleep(task)
queue.task_done()
async def process_tasks(task_list: List[float], worker_count: int... | import pytest
import asyncio
from time import time
from solution import process_tasks
def test_process_tasks_single_worker():
tasks = [1.5, 2.0, 0.5, 3.0]
workers = 1
expected_min_time = sum(tasks)
total_time = asyncio.run(process_tasks(tasks, workers))
assert total_time >= expected_min_time
def t... | [] | [
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\nfrom typing import List\nfrom time import time\n\nasync def worker(queue: asyncio.Queue):\n while True:\n task = await queue.get()\n if... | trial_gpt4o_0 | {
"original_instruction": "<|Analysis Begin|>\n\nThe provided documentation for the `asyncio` queues module outlines the functionality and usage of FIFO Queue, PriorityQueue, and LifoQueue for asynchronous programming in Python. The `asyncio.Queue` class is designed for tasks that require queueing operations and sync... | 0.535917 | Docs: Python310_35556 | C | [
"worker",
"process_tasks"
] | 2 | [
[
"process_tasks",
"worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 75a1c7d980a28472f04e4abb3e593d9b54463489 | d35345d155a30fd4426b6672e45a1f65244ad54b | |||
v1.0 | complete | Docs | Docs: Python310_35743_C | import asyncio
from typing import List, Tuple
async def schedule_tasks(tasks: List[Tuple[int, int]]) -> List[int]:
"""
Implement a function to schedule tasks where each task has a delay in seconds and a resultant value.
The function should return a list of results from all Future objects once they are al... | import asyncio
from typing import List, Tuple
async def _complete_future(future: asyncio.Future, delay: int, value: int):
"""
Helper function to simulate a delay and set the value for a Future object.
"""
await asyncio.sleep(delay)
future.set_result(value)
async def schedule_tasks(tasks: List[Tupl... | import asyncio
from solution import schedule_tasks
async def test_schedule_tasks_single_task():
tasks = [(1, 42)]
result = await schedule_tasks(tasks)
assert result == [42]
async def test_schedule_tasks_multiple_tasks():
tasks = [(1, 10), (2, 20), (3, 30)]
result = await schedule_tasks(tasks)
... | [] | [
1,
0,
1,
1,
1,
1,
1,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def set_future_value(future: asyncio.Future, delay: int, value: int):\n await asyncio.sleep(delay)\n futur... | trial_gpt4o_6 | {
"original_instruction": "### Question:\n\n#### Background:\nYou are developing a task scheduling system using the `asyncio` module in Python 3.10. You need to perform multiple asynchronous computations where results depend on each other in a complex manner. To achieve this, you need to effectively utilize `asyncio.... | 0.662043 | Docs: Python310_35743 | C | [
"_complete_future",
"schedule_tasks"
] | 2 | [
[
"schedule_tasks",
"_complete_future"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d213fd7bae95f915480b91fa025223309b815871 | cf942a511515a0a2cbf802c06c676da1c0d7103e | |||
v1.0 | complete | Docs | Docs: Pytorch_35519_C | import torch
def create_mask(tensor):
"""
Mock function to create a simple mask from the input tensor.
For simplicity, we assume the mask is 1 where tensor values are non-zero and 0 otherwise.
"""
return (tensor != 0).float()
def and_masks(mask1, mask2):
"""
Mock function to perform logica... | import torch
# Assuming the following utilities exist and have been correctly imported
# from torch.nn.attention.flex_attention import create_mask, and_masks, or_masks
# Mock implementations of the `create_mask`, `and_masks`, and `or_masks` functions
# as they do not exist in the actual PyTorch library
def create_mas... | import torch
from solution import generate_attention_masks, apply_attention
def test_generate_attention_masks():
tensor_a = torch.tensor([[1.0, 0.0], [3.0, 4.0]])
tensor_b = torch.tensor([[1.0, 2.0], [0.0, 0.0]])
basic_mask, and_mask, or_mask = generate_attention_masks(tensor_a, tensor_b)
expected_ba... | [
{
"docstring": "Mock function to create a simple mask from the input tensor.\nFor simplicity, we assume the mask is 1 where tensor values are non-zero and 0 otherwise.",
"function_declaration": "def create_mask(tensor):",
"function_name": "create_mask",
"parameter_list": "(tensor)"
},
{
"doc... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef create_mask(tensor):\n \"\"\" Simple example of creating a mask based on positive values in tensor\"\"\"\n return (tensor > 0).float()\n\ndef ... | trial_gpt4o_1 | {
"original_instruction": "## Problem Statement\n\nIn this assessment, you are required to implement a flexible attention mechanism using PyTorch's `torch.nn.attention.flex_attention` module. Specifically, your task is to dynamically create and manipulate attention masks using block mask utilities. This will demonstr... | 0.494637 | Docs: Pytorch_35519 | C | [
"create_mask",
"and_masks",
"or_masks",
"generate_attention_masks",
"apply_attention"
] | 5 | [
[
"generate_attention_masks",
"and_masks"
],
[
"generate_attention_masks",
"create_mask"
],
[
"generate_attention_masks",
"or_masks"
]
] | 3 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 447babf53fe2a58cc1caec8b06c246ecfc1b51c5 | 05fb654801b19a6e017e537de8d97a30cc08ae85 | |||
v1.0 | complete | Docs | Docs: Python310_34712_C | def main():
"""Main function to start the program."""
pass # Your implementation
def function_1():
""" Function 1 does a task """
pass # Your implementation
def function_2():
""" Function 2 calls Function 3 """
pass # Your implementation
def function_3():
""" Function 3 does another ta... | def main():
"""Main function to start the program."""
print("Entering main")
function_1()
function_2()
print("Exiting main")
def function_1():
""" Function 1 does a task """
print("Entering function_1")
# Simulate a task
print("Exiting function_1")
def function_2():
""" Functio... | def test_main(capsys):
main()
captured = capsys.readouterr()
assert "Entering main" in captured.out
assert "Exiting main" in captured.out
def test_function_1(capsys):
function_1()
captured = capsys.readouterr()
assert "Entering function_1" in captured.out
assert "Exiting function_1" in ... | [
{
"docstring": "Main function to start the program.",
"function_declaration": "def main():",
"function_name": "main",
"parameter_list": "()"
},
{
"docstring": "Function 1 does a task ",
"function_declaration": "def function_1():",
"function_name": "function_1",
"parameter_list": ... | [
0,
1,
0,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def main():\n \"\"\"Main function to start the program.\"\"\"\n print(\"Main Function Start\")\n function_1()\n function_2()\n print(\"Main Function End\... | trial_gpt4o_1 | {
"original_instruction": "**Title:** Implementing and Interacting with SystemTap/DTrace Probes in a Python Script\n\n**Problem Statement:**\n\nYou are a developer tasked with analyzing the performance of a Python application using SystemTap or DTrace. The goal is to write a Python script that utilizes static markers... | 0.573894 | Docs: Python310_34712 | C | [
"main",
"function_1",
"function_2",
"function_3"
] | 4 | [
[
"function_2",
"function_3"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | d1474c42c99ee30ff0469614fec57298e8827297 | 96780e006d5bea1b3b9e98a66543c3837f0c99d1 | |||
v1.0 | complete | Docs | Docs: Python310_35799_C | import os
import readline
import atexit
completion_words = ["apple", "banana", "grape", "orange", "watermelon"]
def setup_history():
"""
Sets up the command-line history management.
Loads the history from the .my_python_history file and ensures the history is saved on exit.
"""
histfile = os.path.... | import os
import readline
import atexit
# User-defined list of words for auto-completion
completion_words = ["apple", "banana", "grape", "orange", "watermelon"]
def setup_history():
"""
Sets up the command-line history management.
Loads the history from the .my_python_history file and ensures the history ... | import os
import readline
import pytest
from solution import setup_history, setup_completion, completer
def test_setup_history(monkeypatch):
histfile = os.path.join(os.path.expanduser("~"), ".my_python_history")
if os.path.exists(histfile):
os.remove(histfile)
setup_history()
readline.add_... | [
{
"docstring": "Sets up the command-line history management.\nLoads the history from the .my_python_history file and ensures the history is saved on exit.",
"function_declaration": "def setup_history():",
"function_name": "setup_history",
"parameter_list": "()"
},
{
"docstring": "Custom comp... | [
0,
0,
0,
1,
1,
1,
1,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import readline\nimport os\nimport atexit\n\nHISTORY_FILE = os.path.join(os.path.expanduser(\"~\"), \".my_python_history\")\nCOMPLETION_LIST = [\"apple\", \"banana\", \... | trial_gpt4o_3 | {
"original_instruction": "**Python Coding Assessment: Implementing Command-Line History and Custom Auto-Completion**\n\n### Objective:\nYou are to implement a Python script that utilizes the `readline` module to achieve the following:\n1. Manage the command-line history.\n2. Implement a custom auto-completion functi... | 0.497351 | Docs: Python310_35799 | C | [
"setup_history",
"completer",
"setup_completion"
] | 3 | [
[
"setup_completion",
"completer"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cdcca30ed848c4e9bbcde1f2db3284e7b7bfb2ce | 150e46ab9c799c8ffe9f4bce6f48d6098dc1e208 | |||
v1.0 | complete | Docs | Docs: Python310_35559_C | import random
def optimized_inefficient_function():
"""Optimized version of inefficient_function.
Uses generator instead of list comprehension to save memory and improve speed.
>>> optimized_inefficient_function() == sum(range(10000))
True
"""
def optimized_memory_intensive_function():
""... | import time
import random
import cProfile
import timeit
import tracemalloc
import trace
def optimized_inefficient_function():
"""
Optimized version of inefficient_function.
Uses generator instead of list comprehension to save memory and improve speed.
"""
result = sum(i for i in range(10000))
... | from solution import optimized_inefficient_function, optimized_memory_intensive_function
def test_optimized_inefficient_function_runtime():
import timeit
result = timeit.timeit('optimized_inefficient_function()', globals=globals(), number=10)
assert result < 1.0, f"Function took too long: {result} seconds"... | [
{
"docstring": "Optimized version of inefficient_function. \nUses generator instead of list comprehension to save memory and improve speed.",
"function_declaration": "def optimized_inefficient_function():",
"function_name": "optimized_inefficient_function",
"parameter_list": "()"
},
{
"docst... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cProfile\nimport timeit\nimport trace\nimport tracemalloc\nimport random\n\ndef inefficient_function():\n result = sum(range(10000))\n return result\n\ndef... | trial_gpt4o_2 | {
"original_instruction": "#### Objective:\nDemonstrate proficiency in debugging, profiling, and tracing Python code using the provided tools and modules.\n\n#### Task:\nYou are provided with a piece of Python code that has multiple functions performing various tasks. Some functions might be bottlenecks due to ineffi... | 0.470419 | Docs: Python310_35559 | C | [
"optimized_inefficient_function",
"optimized_memory_intensive_function",
"profile_functions",
"measure_optimization",
"memory_allocation_analysis",
"display_top",
"main"
] | 7 | [
[
"memory_allocation_analysis",
"display_top"
],
[
"memory_allocation_analysis",
"optimized_memory_intensive_function"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c3b9892059dd318632ae1355b4d06cbbffb46186 | d580a2fa1e6658ea896bb2158f03de8a08c620aa | |||
v1.0 | complete | Docs | Docs: Python310_36178_C | from typing import List
def parallel_matrix_multiplication(matrix_a: List[List[int]], matrix_b: List[List[int]]) -> List[List[int]]:
""" Perform matrix multiplication using multiprocessing for parallel computation.
>>> matrix_a = [
[1, 2],
[3, 4]
]
matrix_b = [
... | from multiprocessing import Pool
def matrix_multiply_worker(args):
i, j, matrix_a, matrix_b = args
return sum(matrix_a[i][k] * matrix_b[k][j] for k in range(len(matrix_b)))
def parallel_matrix_multiplication(matrix_a, matrix_b):
# Get dimensions of input matrices
m = len(matrix_a) # Number of rows... | from solution import parallel_matrix_multiplication
def test_parallel_matrix_multiplication_basic():
matrix_a = [
[1, 2],
[3, 4]
]
matrix_b = [
[5, 6],
[7, 8]
]
result = parallel_matrix_multiplication(matrix_a, matrix_b)
expected = [
[19, 22],
[43... | [
{
"docstring": null,
"function_declaration": "def matrix_multiply_worker(args):",
"function_name": "matrix_multiply_worker",
"parameter_list": "(args)"
},
{
"docstring": null,
"function_declaration": "def parallel_matrix_multiplication(matrix_a, matrix_b):",
"function_name": "paralle... | [
1,
1,
0,
1,
1,
1,
1,
0,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import multiprocessing as mp\n\ndef multiply_row_by_matrix(row, matrix_b):\n result_row = []\n num_columns_b = len(matrix_b[0])\n for j in range(num_columns_b)... | trial_gpt4o_1 | {
"original_instruction": "### Question: Parallel Matrix Multiplication\n\nIn this task, you are required to implement a function for matrix multiplication using the \"multiprocessing\" module. The function should leverage multiple processes to parallelize the computation and improve performance.\n\n### Function Spec... | 0.634029 | Docs: Python310_36178 | C | [
"matrix_multiply_worker",
"parallel_matrix_multiplication"
] | 2 | [
[
"parallel_matrix_multiplication",
"matrix_multiply_worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c38fcc43b176f41af5e4381747439826c9f027ec | f510cf006567be029500ec8a752c3a1d2ce649ba | |||
v1.0 | complete | Docs | Docs: Python310_35507_C | import curses
from datetime import datetime
def main_menu(stdscr):
# Main function to display the menu and navigate through options
curses.curs_set(0)
options = ["Show Date and Time", "Enter Text", "Exit"]
current_option = 0
while True:
stdscr.clear()
height, width = stdscr.getmaxy... | import curses
from datetime import datetime
def main_menu(stdscr):
curses.curs_set(0)
options = ["Show Date and Time", "Enter Text", "Exit"]
current_option = 0
while True:
stdscr.clear()
height, width = stdscr.getmaxyx()
for idx, option in enumerate(options):
x = w... | import curses
import pytest
from datetime import datetime
# As python `curses` module is used for terminal/console UI,
# direct unit tests for curses UI might not be viable through standard pytest interface.
# However, testing of the logic without dependency on `curses` can be done by creating mocks and simulating th... | [
{
"docstring": null,
"function_declaration": "def main_menu(stdscr):",
"function_name": "main_menu",
"parameter_list": "(stdscr)"
},
{
"docstring": null,
"function_declaration": "def show_date_time(stdscr):",
"function_name": "show_date_time",
"parameter_list": "(stdscr)"
},
... | [
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 curses\nimport time\nfrom datetime import datetime\n\ndef print_menu(stdscr, selected_idx):\n stdscr.clear()\n menu_items = [\"Show Date and Time\", \"Ente... | trial_gpt4o_2 | {
"original_instruction": "#### Objective:\nImplement a simple text-based user interface using the `curses` module in Python. The interface should allow a user to navigate through a menu, display current date and time, and enable text input.\n\n#### Requirements:\n1. **Main Menu:**\n - Create a main menu with three... | 0.463163 | Docs: Python310_35507 | C | [
"main_menu",
"show_date_time",
"enter_text",
"main"
] | 4 | [
[
"main_menu",
"enter_text"
],
[
"main_menu",
"show_date_time"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 69574e97ad7d1d5188dd7797f392091164df4a23 | 470e81a9c641f10b5dcd5971c1ca66cc4bad8d7a | |||
v1.0 | complete | Docs | Docs: Python310_36086_C | import asyncio
async def task_manager(task_times):
""" Implement a task orchestrator that schedules execution of tasks with specific constraints using asyncio primitives.
Each task should append "Task {task_number} finished" to the result list after completing.
>>> result = asyncio.run(task_manager([2, 3, ... | import asyncio
async def task(worker_id, duration, start_event, semaphore, lock, result):
await start_event.wait() # Wait until the orchestrator allows to start
async with semaphore: # Ensure no more than 3 concurrent tasks
await asyncio.sleep(duration) # Simulate work
async with lock: # En... | import asyncio
from solution import task_manager
def test_task_manager():
task_times = [2, 3, 1, 4, 2]
expected_results = {'Task 0 finished', 'Task 1 finished', 'Task 2 finished', 'Task 3 finished', 'Task 4 finished'}
result = asyncio.run(task_manager(task_times))
assert set(result) == expected_r... | [] | [
1,
1,
1,
1,
1,
0,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def task_manager(task_times):\n lock = asyncio.Lock()\n event = asyncio.Event()\n semaphore = asyncio.Semaphore(3)\n result = []\n\n... | trial_gpt4o_8 | {
"original_instruction": "#### Objective:\nDemonstrate your understanding of asyncio synchronization primitives by solving a problem that coordinates multiple tasks using `Lock`, `Event`, and `Semaphore`.\n\n#### Problem Statement:\nYou are required to implement a task orchestrator that schedules the execution of mu... | 0.610487 | Docs: Python310_36086 | C | [
"task",
"task_manager"
] | 2 | [
[
"task_manager",
"task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9bf592a82803f65c18a8200658ebc781648d2baa | cc9549008f44b6d845a7533c7e67ebca664f9176 | |||
v1.0 | complete | Docs | Docs: Python310_36035_C | import asyncio
import inspect
def is_coroutine(func):
"""
Checks if the given function is a coroutine.
:param func: Function to be checked
:return: True if the function is a coroutine, False otherwise
"""
pass
async def simple_coroutine(num, value):
"""
Asynchronous coroutine that... | import asyncio
import inspect
def is_coroutine(func):
"""
Checks if the given function is a coroutine.
:param func: Function to be checked
:return: True if the function is a coroutine, False otherwise
"""
return inspect.iscoroutinefunction(func)
async def simple_coroutine(num, value):
... | from solution import is_coroutine, run_coroutine
def test_is_coroutine():
async def sample_coroutine():
await asyncio.sleep(1)
def normal_function():
return "I'm just a regular function"
assert is_coroutine(sample_coroutine) == True
assert is_coroutine(normal_function) == Fals... | [
{
"docstring": "Checks if the given function is a coroutine.\n\n:param func: Function to be checked\n:return: True if the function is a coroutine, False otherwise",
"function_declaration": "def is_coroutine(func):",
"function_name": "is_coroutine",
"parameter_list": "(func)"
},
{
"docstring"... | [
1,
1,
1,
1,
1,
0,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport inspect\n\ndef is_coroutine(func):\n \"\"\"\n Check if a given function is a coroutine function.\n \n Parameters: \n - func: a Pyt... | trial_gpt4o_9 | {
"original_instruction": "### Advanced Coding Challenge\n\n#### Background\nIn Python, coroutines are functions that use the `async` keyword. When called, these functions return a coroutine object. Coroutines are primarily used to run asynchronous code, allowing for non-blocking operations.\n\nHandling coroutines ef... | 0.545309 | Docs: Python310_36035 | C | [
"is_coroutine",
"simple_coroutine",
"run_coroutine"
] | 3 | [
[
"run_coroutine",
"simple_coroutine"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4a5c3e56a86cd5f6606010c7fc5cf2cdd04956ad | e81f17af781941259a2f74ea79455ee40347becb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.