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_36154_C | import hmac
import hashlib
def sign_message(key: bytes, message: str, digestmod: str) -> str:
"""Sign the message with the given key using the specified digest module.
>>> key = b'secret_key'
>>> message = 'This is a test message'
>>> digestmod = 'sha256'
>>> signed_message = sign_message(key, mess... | import hmac
import hashlib
def sign_message(key: bytes, message: str, digestmod: str) -> str:
"""
Sign the message with the given key using the specified digest module.
"""
if not key or not isinstance(key, (bytes, bytearray)):
raise ValueError("Key must be a non-empty bytes or bytearray object... | from solution import sign_message, verify_message
import pytest
def test_sign_message_valid():
key = b'secret_key'
message = 'This is a test message'
digestmod = 'sha256'
signed_message = sign_message(key, message, digestmod)
assert isinstance(signed_message, str)
assert len(signed_message) == ... | [
{
"docstring": "Sign the message with the given key using the specified digest module.",
"function_declaration": "def sign_message(key, message, digestmod):",
"function_name": "sign_message",
"parameter_list": "(key, message, digestmod)"
},
{
"docstring": "Verify the message with the provide... | [
1,
1,
1,
0,
1,
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 hmac\nimport hashlib\n\ndef sign_message(key: bytes, message: str, digestmod: str) -> str:\n \"\"\"\n Sign the message with the provided key using HMAC and... | trial_gpt4o_8 | {
"original_instruction": "**Objective**: Implement a secure message signing and verification system using the HMAC algorithm described in the provided documentation.\n\n### Problem Statement\n\nYou are required to create two functions: `sign_message` and `verify_message` to sign messages using a secret key and verif... | 0.806112 | Docs: Python310_36154 | C | [
"sign_message",
"verify_message"
] | 2 | [
[
"verify_message",
"sign_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b7295cedd45feb92f3ac26f49319f8aaa85fbf0e | e91d675c4cff4c4c43d2baba734e5e22f85f0faf | |||
v1.0 | complete | Docs | Docs: Python310_35847_C | import socket
import threading
from select import select
# Dictionary to keep track of client sockets and addresses
clients = {}
# Broadcasts a message to all clients except the sender
def broadcast(message, sender_socket):
"""Broadcast a message to all clients except the sender."""
for client_socket in clien... | import socket
import threading
from select import select
# Dictionary to keep track of client sockets and addresses
clients = {}
# Broadcasts a message to all clients except the sender
def broadcast(message, sender_socket):
for client_socket in clients:
if client_socket != sender_socket:
try:
... | import socket
import threading
import time
# Start the server in a separate thread to test it
def start_test_server():
server_thread = threading.Thread(target=lambda: start_server(12345), daemon=True)
server_thread.start()
time.sleep(1) # Allow server to start up
return server_thread
# Connects to th... | [
{
"docstring": null,
"function_declaration": "def broadcast(message, sender_socket):",
"function_name": "broadcast",
"parameter_list": "(message, sender_socket)"
},
{
"docstring": null,
"function_declaration": "def handle_client(client_socket, client_address):",
"function_name": "han... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\nimport threading\nimport select\nimport sys\n\n# List to keep track of connected client sockets\nclients = []\n\ndef broadcast(message, source_socket):\n... | trial_gpt4o_2 | {
"original_instruction": "You are required to implement a non-blocking, multithreaded chat server using Python sockets. This server should handle multiple clients simultaneously, allowing them to send messages to the server, which will then broadcast the message to all other connected clients. Each client should rec... | 0.698145 | Docs: Python310_35847 | C | [
"broadcast",
"handle_client",
"start_server"
] | 3 | [
[
"handle_client",
"broadcast"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | a371021f7a151f39fe60bd3df06be9e553bba1d7 | 5759a49522de7775ba20a6e840c6dbe09c6a4391 | |||
v1.0 | complete | Docs | Docs: Python310_35630_C | import argparse
from functools import reduce
import operator
def arithmetic_tool():
parser = argparse.ArgumentParser(
description='Command-Line Arithmetic Tool. Perform basic arithmetic operations on a list of numbers from either command-line or a file.'
)
parser.add_argument(
'numbers... | import argparse
import sys
from functools import reduce
import operator
def arithmetic_tool():
parser = argparse.ArgumentParser(
description='Command-Line Arithmetic Tool. Perform basic arithmetic operations on a list of numbers from either command-line or a file.'
)
parser.add_argument(
... | from solution import calculate_sum, calculate_prod, calculate_max, calculate_min
def test_calculate_sum():
assert calculate_sum([1, 2, 3, 4]) == 10
assert calculate_sum([0, 0, 0, 0]) == 0
assert calculate_sum([-1, -2, -3, -4]) == -10
assert calculate_sum([1, -1, 1, -1]) == 0
def test_calculate_prod():... | [
{
"docstring": null,
"function_declaration": "def arithmetic_tool():",
"function_name": "arithmetic_tool",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def calculate_sum(numbers):",
"function_name": "calculate_sum",
"parameter_list": "(numbers)"
},
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import argparse\nimport sys\nfrom functools import reduce\nimport operator\n\ndef arithmetic_tool():\n parser = argparse.ArgumentParser(\n description='Comman... | trial_gpt4o_0 | {
"original_instruction": "<|Analysis Begin|>\n\nThe provided documentation is an extensive and detailed description of the `argparse` module, which is a Python library used for creating command-line interfaces. It includes explanations and examples of various functions and methods such as creating a parser, adding a... | 0.646428 | Docs: Python310_35630 | C | [
"arithmetic_tool",
"calculate_sum",
"calculate_prod",
"calculate_max",
"calculate_min"
] | 5 | [
[
"arithmetic_tool",
"calculate_max"
],
[
"arithmetic_tool",
"calculate_min"
],
[
"arithmetic_tool",
"calculate_prod"
],
[
"arithmetic_tool",
"calculate_sum"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 42db98fd29e59655ea9cede9fad095df1fec81b1 | 09612148838db5dfb3b2ff955fa66a9ac856d544 | |||
v1.0 | complete | Docs | Docs: Python310_36233_C | class CustomFileError(Exception):
"""Custom exception class for file-related errors."""
pass
def read_file(file_content: str) -> str:
"""
Simulates reading from a file.
Args:
- file_content (str): The simulated content of the file.
Returns:
- str: The file content if not empty.
Rais... | class CustomFileError(Exception):
"""Custom exception class for file-related errors."""
def __init__(self, message):
super().__init__(message)
def read_file(file_content: str) -> str:
"""
Simulates reading from a file.
Args:
- file_content (str): The simulated content of the file.
R... | from solution import CustomFileError, read_file, process_data, main_function
def test_read_file_non_empty_content():
content = "This is some content"
assert read_file(content) == content
def test_read_file_empty_content():
try:
read_file("")
except CustomFileError as error:
assert str(... | [] | [
1,
0,
0,
0,
0,
1,
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": "class CustomFileError(Exception):\n pass\n\ndef read_file(file_content: str) -> str:\n try:\n if not file_content:\n raise CustomFileError(\"Fil... | trial_gpt4o_9 | {
"original_instruction": "### Custom Exception Handling and Propagation\n\nIn this coding assignment, you need to create a Python module that simulates a simplified file processing system. This system should be able to read from a 'file', process the input data, and handle various types of potential errors using Pyt... | 0.553485 | Docs: Python310_36233 | C | [
"read_file",
"process_data",
"main_function"
] | 3 | [
[
"main_function",
"process_data"
],
[
"main_function",
"read_file"
]
] | 2 | [
"process_data"
] | false | [
"CustomFileError"
] | true | pytest | true | [] | true | f88445f64e79feb08f8f8192b1d92622835808f4 | df3024fd10cdefc16abb5aa9fab3b38bbea15537 | |||
v1.0 | complete | Docs | Docs: Pytorch_36296_C | import torch
from torch.autograd import gradcheck, gradgradcheck
# Step 1: Implement the custom loss function
def custom_loss(x):
"""
Compute the custom loss function.
Args:
x (torch.Tensor): Input tensor of size (N,).
Returns:
torch.Tensor: Scalar tensor representing the loss.
... | import torch
from torch.autograd import gradcheck, gradgradcheck
# Step 1: Implement the custom loss function
def custom_loss(x):
"""
Compute the custom loss function.
Args:
x (torch.Tensor): Input tensor of size (N,).
Returns:
torch.Tensor: Scalar tensor representing the loss.
... | from solution import custom_loss, verify_gradcheck, verify_gradgradcheck
def test_custom_loss():
x = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float64, requires_grad=True)
expected_loss = sum(xi**2 + torch.sin(xi) for xi in x)
assert custom_loss(x).item() == expected_loss.item()
def test_gradcheck():
... | [
{
"docstring": "Compute the custom loss function.\n\nArgs:\n x (torch.Tensor): Input tensor of size (N,).\n\nReturns:\n torch.Tensor: Scalar tensor representing the loss.",
"function_declaration": "def custom_loss(x):",
"function_name": "custom_loss",
"parameter_list": "(x)"
},
{
"docs... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.autograd import gradcheck, gradgradcheck\n\n# Step 1: Implement the custom loss function\ndef custom_loss(x):\n \"\"\"\n Compute the cust... | trial_gpt4o_8 | {
"original_instruction": "### Gradient Checking in PyTorch\n\n**Objective:**\nImplement a custom loss function using PyTorch, and verify the correctness of its gradient computations using `torch.autograd.gradcheck` and `torch.autograd.gradgradcheck`.\n\n**Instructions:**\n\n1. **Implement a Custom Loss Function:**\n... | 0.566371 | Docs: Pytorch_36296 | C | [
"custom_loss",
"verify_gradcheck",
"verify_gradgradcheck"
] | 3 | [
[
"verify_gradcheck",
"custom_loss"
],
[
"verify_gradgradcheck",
"custom_loss"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | b11c84b405f951a0a17ae6261d558a6198ac6d4d | 79f2d5a0cd3a5ccefe6b6d5694b91c5f316a4cac | |||
v1.0 | complete | Docs | Docs: Python310_36488_C | import asyncio
def run_event_loop_with_task_handling():
""" Create and manage multiple asynchronous tasks, handle scheduling of callbacks, and incorporate custom error handling in an asyncio event loop.
>>> # Expected Output
>>> # Task 1 completed after 1 seconds
>>> # Task 2 completed after 2 seconds
... | import asyncio
async def task(number, delay):
await asyncio.sleep(delay)
print(f"Task {number} completed after {delay} seconds")
def all_tasks_done_callback():
print("All tasks completed!")
def custom_exception_handler(loop, context):
exception = context.get('exception')
print(f"Custom Exception ... | import asyncio
import time
from solution import run_event_loop_with_task_handling
def test_run_event_loop_with_task_handling(capfd):
start_time = time.time()
run_event_loop_with_task_handling()
out, _ = capfd.readouterr()
end_time = time.time()
# Ensure output contains the expected m... | [
{
"docstring": null,
"function_declaration": "def all_tasks_done_callback():",
"function_name": "all_tasks_done_callback",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def custom_exception_handler(loop, context):",
"function_name": "custom_exception_handler... | [
0,
0,
0,
0,
1,
0,
0,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def async_task(task_number, delay):\n await asyncio.sleep(delay)\n print(f\"Task {task_number} completed after {delay} seconds\")\n\ndef a... | trial_gpt4o_4 | {
"original_instruction": "**Coding Assessment Question: Advanced Task Scheduling and Error Handling in asyncio**\n\n### Objective\nImplement a Python function using the `asyncio` package to create and manage multiple asynchronous tasks, handle scheduling of callbacks, and incorporate custom error handling in an asyn... | 0.522735 | Docs: Python310_36488 | C | [
"task",
"all_tasks_done_callback",
"custom_exception_handler",
"run_event_loop_with_task_handling"
] | 4 | [
[
"run_event_loop_with_task_handling",
"all_tasks_done_callback"
],
[
"run_event_loop_with_task_handling",
"custom_exception_handler"
],
[
"run_event_loop_with_task_handling",
"task"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ffba36f4a09f2e88e1721cf6d9f9dd613cfd46d7 | b9491389d2ed5ee847b5b9b8106a6cfa05a5a927 | |||
v1.0 | complete | Docs | Docs: Python310_35914_C | from functools import lru_cache
from typing import List, Dict
@lru_cache(maxsize=32)
def fetch_content(url: str) -> str:
"""
Fetch the content of the web page at the given URL.
Uses caching to avoid repeated fetches of the same URL.
:param url: URL of the web page to fetch.
:return: Content o... | from functools import lru_cache
from typing import List, Dict
@lru_cache(maxsize=32)
def fetch_content(url: str) -> str:
"""
Fetch the content of the web page at the given URL.
Uses caching to avoid repeated fetches of the same URL.
:param url: URL of the web page to fetch.
:return: Content of... | from solution import fetch_content, fetch_multiple_contents
def test_fetch_content():
assert fetch_content('https://example.com/page_a') == 'Content of page A'
assert fetch_content('https://example.com/page_b') == 'Content of page B'
assert fetch_content('https://example.com/unknown_page') == 'Content of o... | [
{
"docstring": "Fetch the content of the web page at the given URL.\nUses caching to avoid repeated fetches of the same URL.\n\n:param url: URL of the web page to fetch.\n:return: Content of the web page.",
"function_declaration": "def fetch_content(url):",
"function_name": "fetch_content",
"paramet... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef fetch_content(url: str) -> str:\n \"\"\"\n Fetches the content of the web page at the given URL.\... | trial_gpt4o_8 | {
"original_instruction": "### Optimizing a Web Scraping Tool with `functools`\n\n**Problem Statement:**\n\nYou are required to implement a web scraping tool that fetches the content of several web pages. However, to optimize performance and avoid repeated fetches of the same web pages, you should utilize the caching... | 0.626361 | Docs: Python310_35914 | C | [
"fetch_content",
"fetch_multiple_contents"
] | 2 | [
[
"fetch_multiple_contents",
"fetch_content"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a99597628664574983330d1ce12ba7f7a41b05eb | c29413fc246b9adb8b47c9268554c000bf7c5b2a | |||
v1.0 | complete | Docs | Docs: Python310_36091_C | import socket
import select
def chat_server():
"""
Chat server using non-blocking sockets and select for handling multiple clients.
- Create a non-blocking TCP server socket that listens on any available IP address and port 12345.
- Accept multiple client connections.
- Use the select method to ma... | import socket
import select
def chat_server():
"""
Chat server using non-blocking sockets and select for handling multiple clients.
"""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("0.0.... | import socket
import threading
from time import sleep
# the server should be run in a separate thread to be able to test the client
def run_server():
import chat_server
chat_server.chat_server()
def run_client(message):
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.c... | [
{
"docstring": "Chat server using non-blocking sockets and select for handling multiple clients.",
"function_declaration": "def chat_server():",
"function_name": "chat_server",
"parameter_list": "()"
},
{
"docstring": "Broadcast a message to all clients\n:param sender_socket: The socket that... | [
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 socket\nimport select\n\ndef chat_server():\n \"\"\"\n Chat server using non-blocking sockets and select for handling multiple clients.\n \"\"\"\n se... | trial_gpt4o_0 | {
"original_instruction": "### Python Socket Programming Assessment\n\n#### Objective:\nYou are tasked with writing a Python program that demonstrates your understanding of socket programming, including both blocking and non-blocking sockets, as well as handling multiple client connections concurrently.\n\n#### Probl... | 0.693512 | Docs: Python310_36091 | C | [
"chat_server",
"broadcast_message",
"disconnect_socket"
] | 3 | [
[
"chat_server",
"broadcast_message"
],
[
"chat_server",
"disconnect_socket"
]
] | 2 | [] | false | [] | false | pytest | false | [
"chat_server"
] | false | be12249b9f54dcb76ec2d8c78fb55fc0d47eaa3e | 3b4903910f1169573917be86bdd0ad33e0fb8bd1 | |||
v1.0 | complete | Docs | Docs: Python310_36561_C | import heapq
def add_task(priority_queue, task, priority):
"""
Adds a new task with a given priority.
"""
# Implementation here
def remove_task(priority_queue, task, task_finder, removed_marker):
"""
Marks a task as removed in the priority queue by using a unique marker.
"""
# Implemen... | import heapq
def add_task(priority_queue, task, priority):
"""
Adds a new task with a given priority.
"""
entry = [priority, task]
heapq.heappush(priority_queue, entry)
def remove_task(priority_queue, task, task_finder, removed_marker):
"""
Marks a task as removed in the priority queue by ... | import pytest
import heapq
from solution import add_task, remove_task, pop_task, change_task_priority
REMOVED = '<removed-task>'
@pytest.fixture
def setup_priority_queue():
priority_queue = []
task_finder = {}
return priority_queue, task_finder
def test_add_task(setup_priority_queue):
priority_queue... | [
{
"docstring": "Adds a new task with a given priority.",
"function_declaration": "def add_task(priority_queue, task, priority):",
"function_name": "add_task",
"parameter_list": "(priority_queue, task, priority)"
},
{
"docstring": "Marks a task as removed in the priority queue by using a uniq... | [
0,
0,
1,
0,
0,
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 heapq\n\ndef add_task(priority_queue, task, priority):\n \"\"\"\n Add a new task to the priority queue.\n \"\"\"\n entry = [priority, task]\n heap... | trial_gpt4o_2 | {
"original_instruction": "You are given a list of tasks, each with a priority and a description. Your task is to implement a priority queue using the `heapq` module, which supports the following operations:\n1. Adding a new task with a given priority.\n2. Removing a task with a given description.\n3. Pop and return ... | 0.583371 | Docs: Python310_36561 | C | [
"add_task",
"remove_task",
"pop_task",
"change_task_priority"
] | 4 | [
[
"change_task_priority",
"add_task"
],
[
"change_task_priority",
"remove_task"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b66fd2bb9b6be74dec4450b547faded0d6f62ac5 | 7dfc7ae4dc5a2a2115f14ddfd98a83b544e1d4b6 | |||
v1.0 | complete | Docs | Docs: Pytorch_34756_C | import torch
def matmul_and_svd(matrix_a, matrix_b, precision):
"""Performs matrix multiplication and SVD decomposition with specified precision.
Parameters:
matrix_a (torch.Tensor): A 2D tensor.
matrix_b (torch.Tensor): A 2D tensor.
precision (str): The desired floating-point precision ('floa... | import torch
def matmul_and_svd(matrix_a, matrix_b, precision):
"""
Performs matrix multiplication and SVD decomposition with specified precision.
Parameters:
- matrix_a: torch.Tensor
- matrix_b: torch.Tensor
- precision: str
Returns:
- dict: containing 'product', 'u', 's', 'v... | import torch
from solution import matmul_and_svd, compare_precisions
def test_matmul_and_svd():
matrix_a = torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtype=torch.float32)
matrix_b = torch.tensor([[5.0, 6.0], [7.0, 8.0]], dtype=torch.float32)
result = matmul_and_svd(matrix_a, matrix_b, 'float32')
# Che... | [
{
"docstring": "Performs matrix multiplication and SVD decomposition with specified precision.\n\nParameters:\n- matrix_a: torch.Tensor\n- matrix_b: torch.Tensor\n- precision: str\n\nReturns:\n- dict: containing 'product', 'u', 's', 'v'",
"function_declaration": "def matmul_and_svd(matrix_a, matrix_b, preci... | [
0,
0,
0,
0,
1,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef matmul_and_svd(matrix_a, matrix_b, precision):\n \"\"\"\n Perform matrix multiplication and Singular Value Decomposition (SVD) \n on the re... | trial_gpt4o_4 | {
"original_instruction": "### Problem: Implementing and Verifying Numerically Stable Linear Algebra Operations with PyTorch\n\nIn this assignment, you are required to implement functions that perform linear algebra operations using PyTorch and demonstrate the difference in results when using different floating-point... | 0.601778 | Docs: Pytorch_34756 | C | [
"matmul_and_svd",
"compare_precisions"
] | 2 | [
[
"compare_precisions",
"matmul_and_svd"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 65cb84fc09f96c2ee83a785676fc9c33f1f3a9ee | 338797149db44a731175186f7f547ae7217109de | |||
v1.0 | complete | Docs | Docs: Python310_36378_C | import random
def roll_dice() -> int:
"""
Simulate rolling two six-sided dice and return the sum of the rolls.
Returns:
int: The sum of the two dice rolls.
"""
pass
def play_game(target_score: int, num_players: int) -> int:
"""
Simulate a dice game where players roll dice to r... | import random
def roll_dice() -> int:
"""
Simulate rolling two six-sided dice and return the sum of the rolls.
Returns:
int: The sum of the two dice rolls.
"""
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
return dice1 + dice2
def play_game(target_score: int, num_player... | from solution import roll_dice, play_game
def test_roll_dice():
random.seed(0)
result = roll_dice()
assert 2 <= result <= 12
def test_roll_dice_distribution():
random.seed(0)
results = [roll_dice() for _ in range(1000)]
assert all(2 <= result <= 12 for result in results)
assert sum(results... | [
{
"docstring": "Simulate rolling two six-sided dice and return the sum of the rolls.\nReturns:\n int: The sum of the two dice rolls.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulate a dice game where players rol... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice() -> int:\n \"\"\"\n Simulate rolling two six-sided dice and return the sum of the rolls.\n Returns:\n int: The sum of th... | trial_gpt4o_9 | {
"original_instruction": "### Advanced Python Coding Assessment: Working with the Random Module\n\nYou have been given the task to simulate a simplistic version of a dice-based board game. In this game, each player rolls two six-sided dice per turn and moves forward by the sum of the dice values. The first player to... | 0.583222 | Docs: Python310_36378 | C | [
"roll_dice",
"play_game"
] | 2 | [
[
"play_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f8e07aa9165463e13776f18b637d2b5a2749c2ea | 2a5ac6bf1c0bf32fd476424f1ed3f62926125e01 | |||
v1.0 | complete | Docs | Docs: Python310_36029_C | import math
from typing import List, Tuple, Dict, Any
def analyze_points(points: List[Tuple[float, float]]) -> Dict[str, Any]:
"""
Compute several geometric and statistical properties of a given dataset of points in a 2D plane.
>>> points = [(1, 2), (3, 4), (5, 6), (7, 8)]
>>> result = analyze_points(... | import math
def euclidean_distance(p1, p2):
return math.dist(p1, p2)
def analyze_points(points):
if len(points) < 2:
raise ValueError("At least two points are required to compute distances.")
# Compute distances
n = len(points)
distances = [[0.0] * n for _ in range(n)]
min_distance = ... | from solution import analyze_points
import math
def test_analyze_points_basic():
points = [(0, 0), (3, 4)]
result = analyze_points(points)
assert result['closest_pair'] == ((0, 0), (3, 4))
assert result['centroid'] == (1.5, 2.0)
expected_distance = math.dist(points[0], points[1])
assert math.is... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(p1, p2):",
"function_name": "euclidean_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": null,
"function_declaration": "def analyze_points(points):",
"function_name": "analyze_points",
"parameter_list": ... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nimport itertools\n\ndef analyze_points(points):\n def euclidean_distance(p1, p2):\n return math.dist(p1, p2)\n \n # Compute distances\n ... | trial_gpt4o_8 | {
"original_instruction": "### Advanced Coding Assessment: Geometric and Statistical Computations\n\n#### Objective:\nYou will implement a function that computes several geometric and statistical properties of a given dataset.\n\n#### Problem Statement:\nGiven a list of tuples representing points in a 2D plane, imple... | 0.628987 | Docs: Python310_36029 | C | [
"euclidean_distance",
"analyze_points"
] | 2 | [
[
"analyze_points",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 70a3aa3ae4ccceb312b746d653cf6b4a57566918 | 0a2ce7dc99212816c2b4403c0acf7cd7cea2194f | |||
v1.0 | complete | Docs | Docs: Python310_35698_C | import plistlib
def load_plist(file_path, fmt=None):
"""
Read a property list file from a given file path and return the content as a dictionary.
:param file_path: Path to the plist file to read.
:param fmt: Format of the plist file. Default is None (autodetect format).
:return: Dictionary contain... | import plistlib
def load_plist(file_path, fmt=None):
"""
Read a property list file from a given file path and return the content as a dictionary.
:param file_path: Path to the plist file to read.
:param fmt: Format of the plist file. Default is None (autodetect format).
:return: Dictionary contain... | import os
import plistlib
import datetime
from solution import load_plist, save_plist, convert_plist
def test_load_plist():
data = {
"name": "John Doe",
"age": 30,
"is_student": False,
"exam_results": {
"math": 95,
"science": 88
},
"graduatio... | [
{
"docstring": "Read a property list file from a given file path and return the content as a dictionary.\n\n:param file_path: Path to the plist file to read.\n:param fmt: Format of the plist file. Default is None (autodetect format).\n:return: Dictionary containing the content of the plist file.",
"function... | [
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 plistlib\n\ndef load_plist(file_path, fmt=None):\n \"\"\"\n Read a property list file from a given file path and return the content as a dictionary.\n\n ... | trial_gpt4o_0 | {
"original_instruction": "**Objective:** Demonstrate understanding and practical usage of the `plistlib` module for reading, writing, and manipulating property list files in both XML and binary formats.\n\n#### Problem Statement\n\nYou are tasked with writing functions to process property list files used by Apple. W... | 0.50575 | Docs: Python310_35698 | C | [
"load_plist",
"save_plist",
"convert_plist"
] | 3 | [
[
"convert_plist",
"load_plist"
],
[
"convert_plist",
"save_plist"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ad39b600a226ef2d4fbd4450dd78fd347f03c072 | 5424488e4cccff7036b615bacdb6151f0d638896 | |||
v1.0 | complete | Docs | Docs: Python310_36534_C | import asyncio
import aiohttp
import random
async def fetch_url(session, url):
"""
Asynchronously fetches the content of a URL.
>>> import aiohttp
>>> async with aiohttp.ClientSession() as session:
>>> await fetch_url(session, "http://example.com")
'Example Content'
"""
# Your imple... | import asyncio
import aiohttp
import random
async def fetch_url(session, url):
"""
Asynchronously fetches the content of a URL.
"""
try:
async with session.get(url) as response:
return await response.text()
except Exception as e:
print(f"Failed to fetch {url}: {e}")
... | import pytest
import asyncio
from unittest.mock import AsyncMock
import aiohttp
from solution import fetch_url, process_data, fetch_and_process
@pytest.mark.asyncio
async def test_fetch_url():
session = AsyncMock(aiohttp.ClientSession)
url = "http://example.com"
session.get.return_value.__aenter__.re... | [] | [
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": "import asyncio\nimport aiohttp\nimport random\n\nasync def fetch_url(session, url):\n \"\"\"\n Takes an aiohttp client session and a URL string to perform an HTTP... | trial_gpt4o_3 | {
"original_instruction": "You are required to implement a small concurrent application that fetches data from multiple URLs and processes it asynchronously. The goal is to efficiently handle multiple HTTP requests and aggregate the results using asyncio.\n\n#### Requirements:\n\n1. Implement an asynchronous function... | 0.562212 | Docs: Python310_36534 | C | [
"fetch_url",
"process_data",
"fetch_and_process"
] | 3 | [
[
"fetch_and_process",
"fetch_url"
],
[
"fetch_and_process",
"process_data"
]
] | 2 | [
"process_data"
] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 5a7c235846f0a3f3b95a565e29d0ad7433545dc3 | 6553ed4d801884c26ebc8c51fa5da8125b900771 | |||
v1.0 | complete | Docs | Docs: Python310_36369_C | import signal
import time
import os
# Global variable to control the task state
task_paused = False
task_running = True
def timeout_handler(signum, frame):
"""Called when the task exceeds the allowed time."""
print("Timeout! Task taking too long.")
# Implementation to handle timeout
def pause_handler(sig... | import signal
import time
import os
# Global variable to control the task state
task_paused = False
task_running = True
def timeout_handler(signum, frame):
print("Timeout! Task taking too long.")
raise TimeoutError("Task exceeded the allowed time limit.")
def pause_handler(signum, frame):
global task_pau... | import os
import signal
import subprocess
import time
# NOTE: Due to the nature of signal handling, these tests will need to run in a separate process context.
def test_task_timeout():
process = subprocess.Popen(['python', 'solution.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait(15) # Wai... | [
{
"docstring": null,
"function_declaration": "def timeout_handler(signum, frame):",
"function_name": "timeout_handler",
"parameter_list": "(signum, frame)"
},
{
"docstring": null,
"function_declaration": "def pause_handler(signum, frame):",
"function_name": "pause_handler",
"para... | [
1,
1,
1,
0,
0,
1,
1,
0,
0
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\nimport time\nimport os\n\n# global flag to control the paused state\npaused = False\n\ndef timeout_handler(signum, frame):\n print(\"Timeout! Task tak... | trial_gpt4o_2 | {
"original_instruction": "### Python Signal Handling Exercise\n\n#### Problem Statement\nYou are tasked with building a simplified watchdog timer system to monitor and manage a long-running task. The watchdog should be able to:\n1. Start a task and set a timeout using an alarm.\n2. Handle custom signals to pause, re... | 0.621174 | Docs: Python310_36369 | C | [
"timeout_handler",
"pause_handler",
"resume_handler",
"interrupt_handler",
"start_task"
] | 5 | [
[
"start_task",
"interrupt_handler"
],
[
"start_task",
"pause_handler"
],
[
"start_task",
"resume_handler"
],
[
"start_task",
"timeout_handler"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 66cb0524737ffc54b16ba93033fffcecc1db638a | a463ab17f9cb07393f3ee12cd9eec98ae990d0f6 | |||
v1.0 | complete | Docs | Docs: Pytorch_36623_C | import torch
import torch.fx
def custom_relu(x):
"""
Custom ReLU activation function.
Returns element-wise maximum between x and 0, plus a small epsilon.
"""
epsilon = 1e-6
return torch.max(x, torch.tensor(0.0)) + epsilon
def replace_relu_with_custom_relu(model: torch.nn.Module) -> torch.nn.Mo... | import torch
import torch.fx
from torch.fx import Tracer
def custom_relu(x):
"""
Custom ReLU activation function.
Returns element-wise maximum between x and 0, plus a small epsilon.
"""
epsilon = 1e-6
return torch.max(x, torch.tensor(0.0)) + epsilon
def replace_relu_with_custom_relu(model: tor... | import torch
import pytest
from solution import custom_relu, replace_relu_with_custom_relu
class BaseModel(torch.nn.Module):
def __init__(self):
super(BaseModel, self).__init__()
self.layer1 = torch.nn.Linear(10, 10)
self.relu = torch.nn.ReLU()
self.layer2 = torch.nn.Linear(10, 10)
... | [] | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.fx\nfrom torch.fx import Tracer\n\n\ndef custom_relu(x):\n epsilon = 1e-6\n return torch.max(x, torch.tensor(0.0, device=x.device)) + e... | trial_gpt4o_7 | {
"original_instruction": "#### Objective\nImplement a custom PyTorch transformation using `torch.fx`, where the goal is to replace every instance of a `torch.nn.ReLU` activation in a model with a custom-defined function `custom_relu`.\n\n#### Problem Statement\nYou are provided with a base PyTorch model that may con... | 0.56367 | Docs: Pytorch_36623 | C | [
"custom_relu",
"replace_relu_with_custom_relu"
] | 2 | [
[
"replace_relu_with_custom_relu",
"custom_relu"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 575fb2d2bf1ee71077f6dd4ad1403d752c65c8a7 | 20899086d6e7c515a6e14cb0e642b2396c8c86b4 | |||
v1.0 | complete | Docs | Docs: Python310_36742_C | from typing import List
import aiohttp
import asyncio
async def fetch_data(urls: List[str], timeout: float) -> List[str]:
""" Perform asynchronous HTTP requests to fetch data from given URLs within a specified timeout.
Handle specific asyncio exceptions including TimeoutError, CancelledError, InvalidStateErro... | from typing import List
import aiohttp
import asyncio
async def fetch_url(session, url, timeout):
try:
async with session.get(url, timeout=timeout) as response:
return await response.text()
except asyncio.TimeoutError:
return f"TimeoutError: Operation exceeded the given deadline"
... | import pytest
import asyncio
from solution import fetch_data
@pytest.mark.asyncio
async def test_fetch_data_success():
urls = ["https://httpbin.org/get"]
result = await fetch_data(urls, 3)
assert "url" in result[0], "URL content expected in response"
@pytest.mark.asyncio
async def test_fetch_data_timeout(... | [] | [
1,
1,
0,
1,
1,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport aiohttp\nimport asyncio\n\nasync def fetch_data(urls: List[str], timeout: float) -> List[str]:\n async def fetch(url: str):\n ... | trial_gpt4o_5 | {
"original_instruction": "**Objective:**\n\nDesign a function to demonstrate the comprehension of handling various asyncio exceptions. This question focuses on simulating realistic scenarios in asynchronous operations and managing the exceptions raised effectively.\n\n**Question:**\n\nYou are required to implement a... | 0.585503 | Docs: Python310_36742 | C | [
"fetch_url",
"fetch_data"
] | 2 | [
[
"fetch_data",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 50dbf0b4da259024e8eaf5e1a05974c0a18bbd15 | 0be7aa30b0a344044f26302de218662a2a87d06e | |||
v1.0 | complete | Docs | Docs: Python310_36292_C | import asyncio
async def start_server(host: str, port: int) -> None:
"""Start an asynchronous server that listens on the specified host and port.
The server should handle multiple client connections concurrently, each
sending a message and receiving an acknowledgment message.
Args:
host (str):... | import asyncio
async def handle_client(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message} from {addr}")
response = f"Received: {message}"
writer.write(response.encode())
await writer.drain()
w... | import asyncio
import pytest
from solution import start_server, client_send_message
@pytest.fixture(scope="module")
def event_loop():
loop = asyncio.new_event_loop()
yield loop
loop.close()
@pytest.fixture(scope="module")
async def server(event_loop):
host = '127.0.0.1'
port = 8888
server_task... | [] | [
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 asyncio\n\nasync def handle_client(reader, writer):\n data = await reader.read(100)\n message = data.decode()\n addr = writer.get_extra_info('peername')... | trial_gpt4o_5 | {
"original_instruction": "### Asynchronous Task Management with Network I/O in Python asyncio\n\n**Objective:**\nWrite a Python function that demonstrates the use of asyncio for managing tasks and handling network I/O operations concurrently.\n\n**Problem Statement:**\nYou are required to implement a server-client m... | 0.66179 | Docs: Python310_36292 | C | [
"handle_client",
"start_server",
"client_send_message",
"main"
] | 4 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8a5029defad56290597b09b486d28f99c58d2c65 | 043ad3b3109a60fab0ea4dd9439fefa736e41393 | |||
v1.0 | complete | Docs | Docs: Python310_36515_C | import hashlib
import secrets
import hmac
def hash_password(password: str) -> str:
"""
Hash the given password using SHA256.
>>> hashed = hash_password('secure_password')
>>> verify_password('secure_password', hashed)
True
"""
pass
def verify_password(password: str, hashed_password: str) ... | import hashlib
import secrets
import hmac
def hash_password(password: str) -> str:
"""
Hash the given password using SHA256.
"""
hash_object = hashlib.sha256(password.encode())
hashed_password = hash_object.hexdigest()
return hashed_password
def verify_password(password: str, hashed_password: ... | from solution import hash_password, verify_password, generate_token, authenticate_message, verify_message
def test_hash_password():
password = "secure_password"
hashed = hash_password(password)
assert isinstance(hashed, str)
assert len(hashed) == 64 # Length of SHA-256 hash in hexadecimal
def test_ve... | [
{
"docstring": "Hash the given password using SHA256.",
"function_declaration": "def hash_password(password):",
"function_name": "hash_password",
"parameter_list": "(password)"
},
{
"docstring": "Verify the given password against the hashed password.",
"function_declaration": "def verify... | [
1,
1,
1,
1,
1,
0,
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 hashlib\nimport hmac\nimport secrets\n\ndef hash_password(password: str) -> str:\n \"\"\"\n Hashes a password using SHA-256 algorithm.\n \"\"\"\n ret... | trial_gpt4o_8 | {
"original_instruction": "**Cryptographic Services Assessment**\n\nYou are required to implement a secure authentication system using Python's cryptographic services. The system needs to perform the following tasks:\n\n1. **Password Hashing and Verification**:\n - Implement a function to securely hash a user's pas... | 0.796016 | Docs: Python310_36515 | C | [
"hash_password",
"verify_password",
"generate_token",
"authenticate_message",
"verify_message"
] | 5 | [
[
"verify_message",
"authenticate_message"
],
[
"verify_password",
"hash_password"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 09d241e21eb132ca488094cb2ea24af5ca180028 | 24d88a4a54c17f7becf6e2023037a5c5c17d9fc0 | |||
v1.0 | complete | Docs | Docs: Scikit_36525_C | import pandas as pd
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.metrics import accuracy_score
def load_and_preprocess_data(file_path):
"""
Loads the d... | import pandas as pd
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.metrics import accuracy_score
def load_and_preprocess_data(file_path):
"""
Loads the d... | import pytest
from solution import load_and_preprocess_data, create_pipeline, train_and_evaluate_model
@pytest.fixture
def sample_data(tmp_path):
# Create a sample dataset
data = """label,feature1,feature2,feature3
0,1.0,2.0,3.0
1,4.0,5.0,6.0
0,7.0,8.0,9.0
... | [
{
"docstring": "Loads the dataset and preprocesses it by splitting into train and test sets\nand scaling the feature values.",
"function_declaration": "def load_and_preprocess_data(file_path):",
"function_name": "load_and_preprocess_data",
"parameter_list": "(file_path)"
},
{
"docstring": "C... | [
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 pandas as pd\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardSca... | trial_gpt4o_9 | {
"original_instruction": "**Objective**: Demonstrate your understanding of scikit-learn's `SGDClassifier`, feature scaling, pipelines, and model evaluation.\n\n### Problem Statement\n\nYou are provided with a dataset containing features and class labels. Your task is to:\n\n1. Load and preprocess the data.\n2. Imple... | 0.7066 | Docs: Scikit_36525 | C | [
"load_and_preprocess_data",
"create_pipeline",
"train_and_evaluate_model"
] | 3 | [
[
"train_and_evaluate_model",
"create_pipeline"
],
[
"train_and_evaluate_model",
"load_and_preprocess_data"
]
] | 2 | [] | false | [] | false | pytest | true | [
"pandas",
"sklearn"
] | false | fb21dd89c69e5b8993a8d3e75bd0c4e7eae6d582 | 1a024b189859a3bfa795abd8b1714f748998195f | |||
v1.0 | complete | Docs | Docs: Scikit_36779_C | from typing import List, Tuple
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
def stream_data(batch_size: int, num_batches: int) -> Tuple[List[str], List[int]]:
"""
Simulates streaming data by yielding mini... | from typing import List, Tuple
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
def stream_data(batch_size: int, num_batches: int) -> Tuple[List[str], List[int]]:
"""
Simulates streaming data by yielding mini... | import pytest
from solution import stream_data, train_incremental_classifier
def test_stream_data():
batch_size = 10
num_batches = 3
data_batches = list(stream_data(batch_size, num_batches))
assert len(data_batches) == num_batches
for texts, labels in data_batches:
assert len(texts) ==... | [
{
"docstring": "Simulates streaming data by yielding mini-batches of text documents and labels.",
"function_declaration": "def stream_data(batch_size, num_batches):",
"function_name": "stream_data",
"parameter_list": "(batch_size, num_batches)"
},
{
"docstring": "Trains an incremental classi... | [
1,
1,
0,
1,
1,
0,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\nfrom typing i... | trial_gpt4o_4 | {
"original_instruction": "### Out-of-Core Learning Challenge\n\n**Objective:**\nImplement an out-of-core learning system for a text classification task using scikit-learn.\n\n**Problem Statement:**\nYou are given a large dataset of text documents and their associated labels. The dataset is too large to fit into memo... | 0.57828 | Docs: Scikit_36779 | C | [
"stream_data",
"train_incremental_classifier"
] | 2 | [
[
"train_incremental_classifier",
"stream_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sklearn"
] | false | 37fbcacaf86b549f51ca20b55e4c457f9f48340a | 00e51a317289a3706e41292833f2f5ee23aafecb | |||
v1.0 | complete | Docs | Docs: Python310_36427_C | import asyncio
async def create_task(fut, delay, value):
"""
Coroutine that takes a Future object `fut`, sleeps for `delay` seconds,
and then sets `value` as the result of `fut`.
Parameters:
- fut (asyncio.Future): Future object to set the result for.
- delay (int): Number of seconds to sleep ... | import asyncio
async def create_task(fut, delay, value):
"""
Coroutine that takes a Future object `fut`, sleeps for `delay` seconds,
and then sets `value` as the result of `fut`.
Parameters:
- fut (asyncio.Future): Future object to set the result for.
- delay (int): Number of seconds to sleep ... | import pytest
import asyncio
from solution import create_task, task_scheduler, main
@pytest.mark.asyncio
async def test_create_task():
fut = asyncio.Future()
await create_task(fut, 1, 'Test Task')
assert fut.result() == 'Test Task'
@pytest.mark.asyncio
async def test_task_scheduler_all_completed():
lo... | [] | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def create_task(fut, delay, value):\n \"\"\"\n Coroutine that takes a Future object `fut`, sleeps for `delay` seconds,\n and then sets ... | trial_gpt4o_0 | {
"original_instruction": "**Objective**: Assess the understanding of asyncio Future objects and their manipulation in an asynchronous context.\n\n**Problem Statement**:\n\nYou are required to implement an asynchronous task scheduler using asyncio.Future objects. The scheduler will handle multiple asynchronous tasks ... | 0.58129 | Docs: Python310_36427 | C | [
"create_task",
"task_scheduler",
"main"
] | 3 | [
[
"task_scheduler",
"create_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f399d1ecb9bf6559292ff7b28fee4e6c00032bb2 | 597dda1c1b919f1b7fafa5af15ad0693f079f5da | |||
v1.0 | complete | Docs | Docs: Pytorch_36838_C | import torch
from torch.utils.dlpack import from_dlpack, to_dlpack
import dlpack
def convert_to_pytorch(dlpack_tensor: "dlpack") -> torch.Tensor:
"""
Converts a DLPack tensor to a PyTorch tensor.
"""
pass
def convert_to_dlpack(pytorch_tensor: torch.Tensor) -> "dlpack":
"""
Converts a PyTorch t... | import torch
from torch.utils.dlpack import from_dlpack, to_dlpack
def convert_to_pytorch(dlpack_tensor: "dlpack") -> torch.Tensor:
"""
Converts a DLPack tensor to a PyTorch tensor.
"""
return from_dlpack(dlpack_tensor)
def convert_to_dlpack(pytorch_tensor: torch.Tensor) -> "dlpack":
"""
Conve... | import torch
from torch.utils.dlpack import to_dlpack
from solution import convert_to_pytorch, convert_to_dlpack, verify_conversion
def test_convert_to_pytorch():
torch_tensor = torch.tensor([1, 2, 3, 4], dtype=torch.float32)
dlpack_tensor = to_dlpack(torch_tensor)
converted_tensor = convert_to_pytorch(dlp... | [
{
"docstring": "Converts a DLPack tensor to a PyTorch tensor.",
"function_declaration": "def convert_to_pytorch(dlpack_tensor):",
"function_name": "convert_to_pytorch",
"parameter_list": "(dlpack_tensor)"
},
{
"docstring": "Converts a PyTorch tensor to a DLPack tensor.",
"function_declar... | [
0,
1,
0,
1,
0,
0,
1,
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 torch\nfrom torch.utils.dlpack import from_dlpack, to_dlpack\n\ndef convert_to_pytorch(dlpack_tensor):\n \"\"\"\n Converts a DLPack tensor to a PyTorch ten... | trial_gpt4o_6 | {
"original_instruction": "**Objective:** Demonstrate your understanding of tensor operations and interoperability by utilizing PyTorch and DLPack.\n\n**Problem Statement:**\n\nYou are provided with a function that generates a DLPack tensor. Your task is to define two functions:\n1. `convert_to_pytorch(dlpack_tensor:... | 0.457574 | Docs: Pytorch_36838 | C | [
"convert_to_pytorch",
"convert_to_dlpack",
"verify_conversion"
] | 3 | [
[
"verify_conversion",
"convert_to_dlpack"
],
[
"verify_conversion",
"convert_to_pytorch"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 4e288a79b562e6649bb197e22e47d115f6ac205c | d7792100bc6df569b32ca48087431dcc3b817132 | |||
v1.0 | complete | Docs | Docs: Python310_36991_C | import curses
def run_curses_interface(stdscr):
""" Implement a text-based user interface using the curses module.
The interface includes a main menu with the option to display a message or quit.
- Main menu options:
- 'd': Display a message in a new window
- 'q': Quit
- Message window ... | import curses
def run_curses_interface(stdscr):
# Initialize the curses application
curses.curs_set(0) # hide cursor
curses.noecho()
curses.cbreak()
stdscr.keypad(True)
# Start color functionality
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
# Ma... | import pytest
from solution import run_curses_interface_wrapper
def test_curses_interface():
# Testing curses apps is done manually because
# they rely on interactive user input.
# This is a placeholder for any necessary setup/teardown.
try:
run_curses_interface_wrapper()
except:
# ... | [
{
"docstring": null,
"function_declaration": "def run_curses_interface(stdscr):",
"function_name": "run_curses_interface",
"parameter_list": "(stdscr)"
},
{
"docstring": null,
"function_declaration": "def run_curses_interface_wrapper():",
"function_name": "run_curses_interface_wrappe... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import curses\n\ndef run_curses_interface(stdscr):\n # Basic initialization\n curses.noecho()\n curses.cbreak()\n stdscr.keypad(True)\n \n # Check if ... | trial_gpt4o_6 | {
"original_instruction": "#### Objective\nDemonstrate your understanding of the `curses` module by creating a simple text-based user interface application.\n\n#### Task\nImplement a Python function named `run_curses_interface` that uses the `curses` module to create a text-based user interface. The interface should ... | 0.379217 | Docs: Python310_36991 | C | [
"run_curses_interface",
"run_curses_interface_wrapper"
] | 2 | [
[
"run_curses_interface_wrapper",
"run_curses_interface"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c79808adb47b0bd7bd355165642301bc8f3d65e6 | e442a2da2098d497e94f3e0310eeafd89c4a55fa | |||
v1.0 | complete | Docs | Docs: Scikit_36330_C | import numpy as np
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.model_selection import cross_val_score
from typing import List, Tuple, Union
def train_ols(X_train: np.ndarray, y_train: np.ndarray) -> LinearRegression:
"""
Train Ordinary Least Squares (OLS) model on the training ... | import numpy as np
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.model_selection import cross_val_score
def train_ols(X_train, y_train):
"""
Train Ordinary Least Squares (OLS) model on the training data.
"""
model = LinearRegression()
model.fit(X_train, y_train)
r... | from solution import train_ols, train_ridge, train_lasso, select_best_model, fit_and_predict_best_model, main
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression, Ridge, Lasso
# Generate synthetic data for testing
def generate_data():
X_train, y_train =... | [
{
"docstring": "Train Ordinary Least Squares (OLS) model on the training data.",
"function_declaration": "def train_ols(X_train, y_train):",
"function_name": "train_ols",
"parameter_list": "(X_train, y_train)"
},
{
"docstring": "Train Ridge Regression model on the training data with given al... | [
1,
1,
1,
1,
0,
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 numpy as np\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso\nfrom sklearn.model_selection import cross_val_score\n\ndef train_ols(X_train, y_tra... | trial_gpt4o_3 | {
"original_instruction": "**Objective**: Assess the understanding and application of linear models using scikit-learn, focusing on model training, regularization, and evaluation.\n\n**Problem Statement**:\nYou are given a dataset represented by feature matrix `X` and target vector `y`. Your task is to implement func... | 0.711756 | Docs: Scikit_36330 | C | [
"train_ols",
"train_ridge",
"train_lasso",
"select_best_model",
"fit_and_predict_best_model",
"main"
] | 6 | [
[
"fit_and_predict_best_model",
"select_best_model"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 3df6324edf6655dbbdd60984eb71241589ba6f80 | 64e80cab131e96c34cd11fc0e947b413b541d623 | |||
v1.0 | complete | Docs | Docs: Python310_36942_C | def parallel_merge_sort(arr: list, pool_size: int) -> list:
""" Perform a parallel merge sort on a list of integers using multiprocessing.
Args:
- arr: A list of integers to be sorted.
- pool_size: An integer representing the number of worker processes in the pool.
Returns:
A sorted list of inte... | import multiprocessing as mp
def merge(left, right):
""" Merge two sorted lists into a single sorted list. """
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(... | from solution import parallel_merge_sort
def test_parallel_merge_sort_single_element():
assert parallel_merge_sort([1], 2) == [1]
def test_parallel_merge_sort_empty_list():
assert parallel_merge_sort([], 2) == []
def test_parallel_merge_sort_sorted_list():
assert parallel_merge_sort([1, 2, 3, 4, 5], 2) =... | [
{
"docstring": "Merge two sorted lists into a single sorted list. ",
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
},
{
"docstring": "Sequential merge sort function. ",
"function_declaration": "def merge_sort(arr):",
"f... | [
0,
0,
0,
1,
1,
0,
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 multiprocessing\n\ndef merge(left, right):\n result = []\n left_idx, right_idx = 0, 0\n\n while left_idx < len(left) and right_idx < len(right):\n ... | trial_gpt4o_4 | {
"original_instruction": "Parallel Merge Sort with Multiprocessing\n\n#### Objective:\nImplement a parallel version of the merge sort algorithm using the `multiprocessing` module. Your implementation should demonstrate the use of process pools to divide sorting tasks among multiple processes and correctly merge the ... | 0.56103 | Docs: Python310_36942 | C | [
"merge",
"merge_sort",
"parallel_merge_sort"
] | 3 | [
[
"merge_sort",
"merge"
],
[
"parallel_merge_sort",
"merge"
],
[
"parallel_merge_sort",
"merge_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 9de8be0a36fe66a413b45b2c7ffccc963d2bd99c | a23c0a037d47fce25e5800648ef2f0e53f2ce4ba | |||
v1.0 | complete | Docs | Docs: Python310_36455_C | import asyncio
class EchoServerProtocol(asyncio.Protocol):
def __init__(self):
self.transport = None
def connection_made(self, transport):
self.transport = transport
def data_received(self, data):
message = data.decode()
echo_message = f"Echo: {message}"
self.trans... | import asyncio
import signal
class EchoServerProtocol(asyncio.Protocol):
def __init__(self):
self.transport = None
def connection_made(self, transport):
self.transport = transport
def data_received(self, data):
message = data.decode()
echo_message = f"Echo: {message}"
... | import asyncio
import signal
import pytest
from contextlib import contextmanager
from solution import echo_server, EchoServerProtocol
@contextmanager
def does_not_raise():
yield
@pytest.fixture
async def start_echo_server():
server_task = asyncio.create_task(echo_server('127.0.0.1', 8888))
await asyncio.... | [] | [
0,
1,
1,
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 asyncio\nimport signal\n\nclass EchoServerProtocol(asyncio.Protocol):\n def connection_made(self, transport):\n self.transport = transport\n\n def d... | trial_gpt4o_6 | {
"original_instruction": "#### Objective:\nTo test your understanding of the essential `asyncio` concepts, event loops, task scheduling, and network communication using Python's `asyncio` library.\n\n#### Problem:\nWrite an asynchronous function `async def echo_server(host: str, port: int) -> None` that implements a... | 0.669274 | Docs: Python310_36455 | C | [
"echo_server",
"shutdown"
] | 2 | [
[
"echo_server",
"shutdown"
]
] | 1 | [] | false | [
"EchoServerProtocol"
] | true | pytest | true | [] | true | f529e1851b3b367ad2266d91d5d10ce02c12f488 | b01c39dc42178414182190cb31df3e8af6b84767 | |||
v1.0 | complete | Docs | Docs: Python310_36118_C | import urllib.request
from typing import List, Tuple, Optional
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def asynchronous_web_scraper(urls: List[str]) -> List[Tuple[str, Optional[bytes]]]:
""" Fetches the page contents for each URL in the urls list using ThreadPoolExecutor.
Args:
... | import urllib.request
from typing import List, Tuple, Optional
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def asynchronous_web_scraper(urls: List[str]) -> List[Tuple[str, Optional[bytes]]]:
def fetch(url: str) -> Tuple[str, Optional[bytes]]:
try:
with urllib.request.... | import pytest
from unittest.mock import patch
from solution import asynchronous_web_scraper, asynchronous_prime_calculator
def test_asynchronous_web_scraper_success():
urls = ['http://example.com', 'http://example.org']
contents = [b"<html>Example.com</html>", b"<html>Example.org</html>"]
def mock_urlopen... | [
{
"docstring": null,
"function_declaration": "def asynchronous_web_scraper(urls):",
"function_name": "asynchronous_web_scraper",
"parameter_list": "(urls)"
},
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
}... | [
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": "from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed\nfrom urllib.request import urlopen\nfrom typing import List, Tuple, Optional\n\nde... | trial_gpt4o_1 | {
"original_instruction": "### Asynchronous Web Scraping and Prime Number Calculation\n\n#### Problem Description\nYou are tasked with creating two functions that demonstrate the use of concurrency features in the `concurrent.futures` module: one for web scraping and one for prime number calculation. \n\n#### Part 1:... | 0.606862 | Docs: Python310_36118 | C | [
"asynchronous_web_scraper",
"is_prime",
"asynchronous_prime_calculator"
] | 3 | [
[
"asynchronous_prime_calculator",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 62b21219de0b55c8a794dffee86f572360c4459f | 6e8533b335d0097b6a071d1861f6787747e17ff4 | |||
v1.0 | complete | Docs | Docs: Seaborn_36682_C | import seaborn as sns
def set_plot_context(context_name, font_scale=1, rc_params=None):
"""
Sets the plotting context using seaborn.
:param context_name: The name of the context to set.
It can be one of the following: 'paper', 'notebook', 'talk', 'poster'.
:param font_sca... | import seaborn as sns
def set_plot_context(context_name, font_scale=1, rc_params=None):
"""
Sets the plotting context using seaborn.
:param context_name: The name of the context to set.
It can be one of the following: 'paper', 'notebook', 'talk', 'poster'.
:param font_sca... | from solution import set_plot_context, create_custom_plot
import pytest
def test_set_plot_context_valid():
set_plot_context('notebook', 1, {'lines.linewidth': 2})
def test_set_plot_context_invalid_name():
with pytest.raises(ValueError):
set_plot_context('invalid_context', 1, {'lines.linewidth': 2})
d... | [
{
"docstring": "Sets the plotting context using seaborn.\n\n:param context_name: The name of the context to set. \n It can be one of the following: 'paper', 'notebook', 'talk', 'poster'.\n:param font_scale: A value for scaling the size of the fonts relative to the default size.\n:param rc_pa... | [
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 seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef set_plot_context(context_name, font_scale, rc_params):\n \"\"\"\n Sets the plotting context using se... | trial_gpt4o_1 | {
"original_instruction": "### Question\n\nIn this task, you are going to demonstrate and implement seaborn functionality to customize plot contexts.\n\n#### Requirements\nYou need to implement the following functions:\n\n1. `set_plot_context(context_name, font_scale, rc_params)`: This function should set the plottin... | 0.706221 | Docs: Seaborn_36682 | C | [
"set_plot_context",
"create_custom_plot"
] | 2 | [
[
"create_custom_plot",
"set_plot_context"
]
] | 1 | [] | false | [] | false | pytest | true | [
"seaborn"
] | false | cb45f8e6b38f7eca15cbc7d1b8e24e44944689fe | 1191e03a691895c99f3054830728c73295c84546 | |||
v1.0 | complete | Docs | Docs: Python310_36928_C | import asyncio
from typing import AsyncGenerator, List, Generator
async def async_gen_squares(max_num: int) -> AsyncGenerator[int, None]:
"""Generate a sequence of squares of numbers asynchronously up to max_num (inclusive).
>>> result = [num async for num in async_gen_squares(5)]
>>> result
[1, 4... | import asyncio
from typing import AsyncGenerator, List, Generator
async def async_gen_squares(max_num: int) -> AsyncGenerator[int, None]:
for i in range(1, max_num + 1):
await asyncio.sleep(0.1) # Simulating asynchronous operation
yield i ** 2
def filter_even_numbers(sequence: List[int]) -> List[... | import pytest
import asyncio
from solution import async_gen_squares, filter_even_numbers, gen_cumulative_sum, async_sum_cumulative
@pytest.mark.asyncio
async def test_async_gen_squares():
expected_output = [1, 4, 9, 16, 25]
result = [num async for num in async_gen_squares(5)]
assert result == expected_out... | [
{
"docstring": null,
"function_declaration": "def filter_even_numbers(sequence):",
"function_name": "filter_even_numbers",
"parameter_list": "(sequence)"
},
{
"docstring": null,
"function_declaration": "def gen_cumulative_sum(sequence):",
"function_name": "gen_cumulative_sum",
"p... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def async_gen_squares(max_num: int):\n \"\"\"\n Asynchronous generator that yields squares of numbers from 1 to max_num inclusive.\n \"... | trial_gpt4o_3 | {
"original_instruction": "**Title:** Implementing an Asynchronous Data Processing Pipeline with Comprehensions.\n\n**Objective:** \n\nTo assess the understanding of asynchronous operations, comprehensions, and generator expressions in Python.\n\n**Task:**\n\nYou are tasked with implementing a complex data processing... | 0.604941 | Docs: Python310_36928 | C | [
"async_gen_squares",
"filter_even_numbers",
"gen_cumulative_sum",
"async_sum_cumulative"
] | 4 | [
[
"async_sum_cumulative",
"async_gen_squares"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7e65680faced7e891e44dacd7332526de63de7c4 | d3e1c5f152b6f29de01658b75d0756877ec6fe6e | |||
v1.0 | complete | Docs | Docs: Python310_36929_C | import asyncio
import random
from typing import List, Optional
class FetchError(Exception):
pass
async def fetch_url(fut: asyncio.Future, url: str):
"""Simulate fetching a URL with potential for random failure.
Args:
fut (asyncio.Future): Future object to store the result or exception.
url... | import asyncio
import random
from typing import List
class FetchError(Exception):
pass
async def fetch_url(fut: asyncio.Future, url: str):
try:
# Simulate network delay
await asyncio.sleep(random.uniform(0.1, 0.5))
# Randomly fail
if random.choice([True, False]):
ra... | import asyncio
import pytest
from solution import process_urls, FetchError
@pytest.mark.asyncio
async def test_fetch_success():
urls = ["http://example.com/success1", "http://example.com/success2"]
# Mock fetch_url to always succeed
async def mock_fetch_url(fut, url):
await asyncio.sleep(0.1)
... | [] | [
0,
1,
1,
0,
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 asyncio\nimport random\nfrom typing import List\n\nclass FetchError(Exception):\n pass\n\nasync def fetch_url(fut: asyncio.Future, url: str):\n try:\n ... | trial_gpt4o_5 | {
"original_instruction": "#### Objective:\nImplement an asynchronous task management system using Python's `asyncio.Future` objects. Your task is to create an asynchronous task that processes multiple tasks, manages future results, and handles exceptions appropriately.\n\n#### Problem Statement:\nYou are given a lis... | 0.585494 | Docs: Python310_36929 | C | [
"fetch_url",
"on_fetch_complete",
"process_urls"
] | 3 | [
[
"process_urls",
"fetch_url"
],
[
"process_urls",
"on_fetch_complete"
]
] | 2 | [] | false | [
"FetchError"
] | true | pytest | true | [] | true | 9920d8336ada05a764c85cc4c65474a9baf9e597 | 25032d96a0b5df9a1551228106e8f56f285fb6be | |||
v1.0 | complete | Docs | Docs: Pandas_36706_C | import pandas as pd
import numpy as np
from typing import List
def generate_time_series(start: str, end: str, freq: str, tz: str) -> pd.Series:
""" Create a time series with random sales data from `start` to `end` at a specified frequency and time zone.
>>> ts = generate_time_series("2023-01-01", "2023-01-07",... | import pandas as pd
import numpy as np
from pandas.tseries.offsets import CustomBusinessDay
from typing import List
def generate_time_series(start: str, end: str, freq: str, tz: str) -> pd.Series:
"""
Create a time series with random sales data from `start` to `end` at a specified frequency and time zone.
... | import pandas as pd
import numpy as np
from solution import generate_time_series, resample_and_aggregate, apply_custom_business_days, analyze_sales
def test_generate_time_series():
ts = generate_time_series("2023-01-01", "2023-01-07", "1H", "America/New_York")
assert len(ts) == 145, "Time series length should ... | [
{
"docstring": "Create a time series with random sales data from `start` to `end` at a specified frequency and time zone.",
"function_declaration": "def generate_time_series(start, end, freq, tz):",
"function_name": "generate_time_series",
"parameter_list": "(start, end, freq, tz)"
},
{
"doc... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport numpy as np\n\ndef generate_time_series(start: str, end: str, freq: str, tz: str) -> pd.Series:\n \"\"\"\n Create a time series with r... | trial_gpt4o_6 | {
"original_instruction": "### Time Series Analysis with Pandas\n\n#### Objective\nImplement a set of functions to demonstrate your mastery of pandas time series manipulation, focusing on creating time series, applying time zones, resampling data, and handling custom business days.\n\n#### Problem Statement\n\nYou ar... | 0.757082 | Docs: Pandas_36706 | C | [
"generate_time_series",
"resample_and_aggregate",
"apply_custom_business_days",
"analyze_sales"
] | 4 | [
[
"analyze_sales",
"resample_and_aggregate"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas"
] | false | 1b2eaa4d7d84c90cb2baf6d993d17d57ed26db35 | 439c6d79edd4c514ef0f9c1ce09a1a94804638f3 | |||
v1.0 | complete | Docs | Docs: Pytorch_36701_C | import torch
import torch.nn as nn
def generate_block_mask(shape: tuple) -> torch.Tensor:
"""
Generates a block mask with the given shape using `create_block_mask`.
Args:
shape (tuple): A tuple (height, width) representing the dimensions of the mask.
Returns:
torch.Tensor: The block m... | import torch
import torch.nn as nn
def create_block_mask(size):
# This is a simplified placeholder for the create_block_mask utility function.
# In a real scenario, you would import this from the utility module.
return torch.ones(size)
def generate_block_mask(shape: tuple) -> torch.Tensor:
"""
Gen... | from solution import generate_block_mask, SimpleAttention
def test_generate_block_mask():
mask = generate_block_mask((3, 3))
assert mask.size() == (3, 3)
assert torch.all(mask == 1)
def test_SimpleAttention():
embed_dim = 4
attention_layer = SimpleAttention(embed_dim=embed_dim)
query = ke... | [] | [
1,
0,
1,
1,
1,
1,
1,
1,
0,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\n\ndef create_block_mask(height: int, width: int) -> torch.Tensor:\n \"\"\"\n Utility function to create a block mask.\n \n... | trial_gpt4o_7 | {
"original_instruction": "#### Objective\nThe objective of this question is to assess the student's understanding of PyTorch's attention mechanisms and the use of block masks within these mechanisms. The tasks involve creating block masks and integrating them into a simplified attention layer.\n\n#### Problem Statem... | 0.49521 | Docs: Pytorch_36701 | C | [
"create_block_mask",
"generate_block_mask"
] | 2 | [
[
"generate_block_mask",
"create_block_mask"
]
] | 1 | [] | false | [
"SimpleAttention"
] | true | pytest | true | [
"torch"
] | false | fe2b6427ddff38e078ffe1a38fa0bcf4e70d81cd | 5b00e13108e0405f69f248a347973c5d390b32bf | |||
v1.0 | complete | Docs | Docs: Python310_37087_C | import os
import time
import argparse
import logging
from shutil import copy2
def setup_logger(log_file):
logging.basicConfig(filename=log_file, level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
def monitor_directories(source_dir, dest_dir):
""" Monitor the source... | import os
import time
import argparse
import logging
from shutil import copy2, rmtree
from filecmp import cmpfiles
def setup_logger(log_file):
logging.basicConfig(filename=log_file, level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
def get_all_files(directory):
a... | import os
import shutil
import logging
from solution import monitor_directories, setup_logger, synchronize_files
def test_synchronize_added_file(tmp_path, caplog):
source_dir = tmp_path / "source"
dest_dir = tmp_path / "dest"
log_file = tmp_path / "logfile.log"
source_dir.mkdir()
dest_dir.mkdi... | [
{
"docstring": null,
"function_declaration": "def setup_logger(log_file):",
"function_name": "setup_logger",
"parameter_list": "(log_file)"
},
{
"docstring": null,
"function_declaration": "def get_all_files(directory):",
"function_name": "get_all_files",
"parameter_list": "(direc... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport time\nimport argparse\nimport logging\nfrom shutil import copy2, rmtree\n\ndef setup_logger(log_file):\n logging.basicConfig(filename=log_file, lev... | trial_gpt4o_7 | {
"original_instruction": "### File Synchronizer and Logger\n\nYou are required to implement a Python script that synchronizes the contents of a source directory to a destination directory. Additionally, the script should log all major steps of its execution. Specifically, your script should:\n\n1. **Monitor**: Conti... | 0.657374 | Docs: Python310_37087 | C | [
"setup_logger",
"get_all_files",
"synchronize_files",
"monitor_directories"
] | 4 | [
[
"monitor_directories",
"synchronize_files"
],
[
"synchronize_files",
"get_all_files"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 57857c77e961a912cf949e581a1767baba74d4da | fa2f9ed46486bcb8a40750383e128da4edf29ffa | |||
v1.0 | complete | Docs | Docs: Python310_36763_C | from typing import List, Dict
import concurrent.futures
def download_url(url: str) -> str:
# Simulate network delay
import random
import time
time.sleep(random.uniform(0.1, 0.3))
# Simulate file content
return "This is the content of the file at " + url
def count_words(content: str) -> int:
... | import concurrent.futures
from typing import List, Dict
import random
import time
def download_url(url: str) -> str:
# Simulate network delay
time.sleep(random.uniform(0.1, 0.3))
# Simulate file content
return "This is the content of the file at " + url
def count_words(content: str) -> int:
"""
... | import pytest
from solution import parallel_url_processing
def test_parallel_url_processing_single_url():
urls = ["http://example.com/file1.txt"]
result = parallel_url_processing(urls)
assert result["http://example.com/file1.txt"] > 0 # Simple check for a valid word count
def test_parallel_url_processing... | [
{
"docstring": null,
"function_declaration": "def download_url(url):",
"function_name": "download_url",
"parameter_list": "(url)"
},
{
"docstring": "Given the content of a file as a string, return the number of words.",
"function_declaration": "def count_words(content):",
"function_n... | [
1,
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\nfrom typing import List, Dict\nimport random\nimport time\n\ndef download_url(url: str) -> str:\n # Simulate network delay\n time.sleep... | trial_gpt4o_0 | {
"original_instruction": "### Parallel Data Processing with `concurrent.futures`\n\nYou have been provided with a large dataset consisting of URLs. Each URL points to a file that needs to be downloaded, processed, and summarized. Processing each file involves reading its contents and calculating the number of words.... | 0.617534 | Docs: Python310_36763 | C | [
"download_url",
"count_words",
"process_url",
"parallel_url_processing"
] | 4 | [
[
"parallel_url_processing",
"process_url"
],
[
"process_url",
"count_words"
],
[
"process_url",
"download_url"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | e96dbc537c3c03490600bdc7e508701f60f5d469 | eaebab73eb8fe8de7c098ba01678936ef7a1cc7e | |||
v1.0 | complete | Docs | Docs: Python310_37487_C | import asyncio
async def async_file_reader(file_path: str) -> None:
"""
Asynchronously reads and processes each line of the given file.
:param file_path: Path to the file to be read asynchronously.
""" | import asyncio
import platform
async def process_line(line):
print(line.strip())
await asyncio.sleep(0.1)
async def async_file_reader(file_path: str) -> None:
system = platform.system()
if system == "Windows":
# Use ProactorEventLoop for Windows
asyncio.set_event_loop_policy(asyncio.Wi... | import asyncio
from solution import async_file_reader
import pytest
@pytest.mark.asyncio
async def test_async_file_reader(tmp_path):
test_file_path = tmp_path / "test.txt"
content = "Line 1\nLine 2\nLine 3\n"
test_file_path.write_text(content)
# Capture print output
from io import StringIO
imp... | [] | [
1,
0,
1,
1,
1,
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\nimport platform\n\nasync def async_file_reader(file_path: str) -> None:\n \"\"\"\n Asynchronously reads and processes each line of the given file.... | trial_gpt4o_4 | {
"original_instruction": "**Question: Implement an Asynchronous File Reader with Platform Constraints**\n\nYou are required to implement an asynchronous file reader using Python's `asyncio` module. The file reader should be capable of reading from a file and processing each line asynchronously. Your solution should ... | 0.437218 | Docs: Python310_37487 | C | [
"process_line",
"async_file_reader"
] | 2 | [
[
"async_file_reader",
"process_line"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dc6565b31343368b9e4598755940796d757f8f30 | 1df7c5382eb78dd3fb6252ff9a7eb6d0bb4ea52e | |||
v1.0 | complete | Docs | Docs: Python310_37256_C | import asyncio
from typing import List, Dict
import aiohttp
from bs4 import BeautifulSoup
async def fetch_all_links(urls: List[str]) -> Dict[str, List[str]]:
"""
Asynchronous web scraper that fetches HTML content from multiple URLs concurrently and processes the
content to extract all the hyperlink refere... | import asyncio
from typing import List, Dict
import aiohttp
from bs4 import BeautifulSoup
async def fetch_html(url: str) -> str:
"""
Fetches the HTML content of the given URL asynchronously.
"""
async with aiohttp.ClientSession() as session:
try:
async with session.get(url) as respo... | import pytest
import asyncio
from solution import fetch_all_links
@pytest.mark.asyncio
async def test_fetch_all_links_single_url():
urls = ["http://example.com"]
result = await fetch_all_links(urls)
assert "http://example.com" in result
assert isinstance(result["http://example.com"], list)
@pytest.mar... | [
{
"docstring": "Extracts all hyperlink references from the given HTML content.",
"function_declaration": "def extract_links(html):",
"function_name": "extract_links",
"parameter_list": "(html)"
}
] | [
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\nfrom typing import List, Dict\nimport aiohttp\nfrom bs4 import BeautifulSoup\n\nasync def fetch_html(url: str) -> str:\n \"\"\"\n Asynchronously f... | trial_gpt4o_7 | {
"original_instruction": "Asynchronous Web Scraper\n\nYou are required to write an asynchronous web scraper that can fetch HTML content from multiple URLs concurrently and process the content to extract all the hyperlink references (`<a href=\"\">` tags).\n\n#### Requirements\n\n1. **Input:**\n - A list of URLs. E... | 0.750581 | Docs: Python310_37256 | C | [
"fetch_html",
"extract_links",
"fetch_all_links"
] | 3 | [
[
"fetch_all_links",
"extract_links"
],
[
"fetch_all_links",
"fetch_html"
]
] | 2 | [] | false | [] | false | pytest | true | [
"aiohttp",
"bs4"
] | false | f9411be46bbcdcc8367a567f3989f730e5d12ad4 | ab26d84702af4415dae349b552c5e25b806ccf67 | |||
v1.0 | complete | Docs | Docs: Python310_37143_C | import asyncio
from typing import List
async def fetch_data(url: str) -> str:
""" Simulate downloading data from a given URL asynchronously.
"""
async def process_data(data: str) -> str:
""" Simulate processing the fetched data asynchronously.
"""
async def download_manager(urls: List[str]) -> List[s... | import asyncio
from typing import List
# Simulate downloading data with a given URL
async def fetch_data(url: str) -> str:
await asyncio.sleep(1) # Simulate network delay
return url
# Simulate processing fetched data
async def process_data(data: str) -> str:
await asyncio.sleep(0.5) # Simulate processin... | import asyncio
from solution import download_manager
def test_download_manager_with_multiple_urls():
urls = [
"http://example.com/1",
"http://example.com/2",
"http://example.com/3",
"http://example.com/4",
"http://example.com/5",
"http://example.com/6",
]
exp... | [] | [
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\nfrom typing import List\n\nasync def fetch_data(url: str) -> str:\n \"\"\"\n Simulates an asynchronous download of data from a given URL by sleepi... | trial_gpt4o_8 | {
"original_instruction": "### Question: Asynchronous Download Manager\n\nYou are tasked with implementing a basic download manager using the asyncio library. Your download manager should fetch data concurrently from multiple URLs and process this data asynchronously. \n\n#### Requirements:\n\n1. Implement a function... | 0.561965 | Docs: Python310_37143 | C | [
"fetch_data",
"process_data",
"download_manager"
] | 3 | [
[
"download_manager",
"fetch_data"
],
[
"download_manager",
"process_data"
]
] | 2 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 6f922d9dbfb46e9fdd971fc1fd61e1db4d67e5d0 | 10018e887f1e7938072fa0ab92c301e63a574787 | |||
v1.0 | complete | Docs | Docs: Pytorch_36966_C | import torch
def custom_attention(input_tensor: torch.Tensor, mask_type: str) -> torch.Tensor:
"""
Implement a custom attention mechanism using mask utilities.
Parameters
----------
input_tensor : torch.Tensor
A 2D input tensor of shape `[batch_size, seq_length]`.
mask_type : str
... | import torch
# Placeholder utility functions to simulate the mask operations from 'torch.nn.attention.flex_attention'
def create_block_mask(batch_size, seq_length):
return torch.ones((batch_size, seq_length))
def create_mask(batch_size, seq_length):
return torch.ones((batch_size, seq_length))
def and_masks(m... | import pytest
import torch
from solution import custom_attention
def test_custom_attention_and_mask():
input_tensor = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.float32)
output_tensor = custom_attention(input_tensor, "and")
# Since all masks are ones, the output tensor should be identical to the inpu... | [
{
"docstring": null,
"function_declaration": "def create_block_mask(batch_size, seq_length):",
"function_name": "create_block_mask",
"parameter_list": "(batch_size, seq_length)"
},
{
"docstring": null,
"function_declaration": "def create_mask(batch_size, seq_length):",
"function_name... | [
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 torch\nfrom torch.nn.attention.flex_attention import create_block_mask, create_mask, and_masks, or_masks, noop_mask\n\ndef custom_attention(input_tensor: torch.T... | trial_gpt4o_4 | {
"original_instruction": "### Question: Implementing a Custom Attention Mechanism using Mask Utilities\n\n#### Objective\nYour task is to implement a custom attention mechanism that uses provided mask utility functions from the PyTorch `torch.nn.attention.flex_attention` module. The custom attention mechanism should... | 0.446581 | Docs: Pytorch_36966 | C | [
"create_block_mask",
"create_mask",
"and_masks",
"or_masks",
"noop_mask",
"custom_attention"
] | 6 | [
[
"custom_attention",
"and_masks"
],
[
"custom_attention",
"create_block_mask"
],
[
"custom_attention",
"create_mask"
],
[
"custom_attention",
"noop_mask"
],
[
"custom_attention",
"or_masks"
]
] | 5 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 38fb757235a4c55afc41c1e57c981002622b4221 | 960c61057a205216104bd73d011138fbe262ce2e | |||
v1.0 | complete | Docs | Docs: Python310_37117_C | import threading
import multiprocessing
import requests
from typing import List, Dict, Any
def fetch_data_using_threads(urls: List[str]) -> Dict[str, Any]:
""" Fetch data concurrently from multiple URLs using threads.
Args:
urls (List[str]): List of URLs to fetch data from.
Returns:
Dict[s... | import threading
import multiprocessing
import requests
from typing import List, Dict, Any
import json
def fetch_data(url: str) -> Any:
"""
Fetch data from a URL and return the required field from the JSON response.
"""
try:
response = requests.get(url)
data = response.json()
re... | from solution import fetch_data_using_threads, fetch_data_using_multiprocessing
import pytest
import requests
from unittest.mock import patch
# Define test URLs and mock data
test_urls = [
"http://example.com/data1",
"http://example.com/data2",
"http://example.com/data3"
]
mock_responses = {
"http://e... | [
{
"docstring": "Fetch data from a URL and return the required field from the JSON response.",
"function_declaration": "def fetch_data(url):",
"function_name": "fetch_data",
"parameter_list": "(url)"
},
{
"docstring": "Fetch data from URLs using threads and return a dictionary mapping URLs to... | [
1,
1,
0,
1,
1,
1,
1,
1,
0
] | 7 | easy | 0.778 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import threading\nimport multiprocessing\nimport requests\nfrom typing import List, Dict, Any\n\ndef fetch_and_process(url: str) -> Any:\n \"\"\"\n Fetch data fro... | trial_gpt4o_7 | {
"original_instruction": "**Question: Implementing Concurrent Data Fetching with Threading and Multiprocessing**\n\nYou are tasked to design a system that concurrently fetches data from multiple URLs and processes the data fetched. You have to implement two versions of this system: one using thread-based parallelism... | 0.594953 | Docs: Python310_37117 | C | [
"fetch_data",
"fetch_data_using_threads",
"fetch_data_using_multiprocessing"
] | 3 | [
[
"fetch_data_using_multiprocessing",
"fetch_data"
],
[
"fetch_data_using_threads",
"fetch_data"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 960f8fbe2be6795ee797ae4964279b6e40645a9a | eb0e8ada22930f4f69eb9c4ba697cdea7ed57342 | |||
v1.0 | complete | Docs | Docs: Python310_37339_C | import sqlite3
import pickle
def collect_user_data() -> dict:
""" Collects user information from standard input and returns as a dictionary."""
pass
def serialize_data(data: dict) -> bytes:
"""Serializes the input dictionary using `pickle` and returns the serialized data as bytes."""
pass
def store_d... | import pickle
import sqlite3
import os
def collect_user_data():
"""
Collects user information from standard input and returns as a dictionary.
"""
user_data = {}
user_data['name'] = input("Enter your name: ")
user_data['age'] = int(input("Enter your age: "))
user_data['email'] = input("Ente... | import pytest
import os
import sqlite3
from solution import collect_user_data, serialize_data, store_data_in_db, retrieve_data_from_db, initialize_database
def test_serialize_and_deserialize_data():
user_data = {'name': 'Alice', 'age': 30, 'email': 'alice@example.com', 'address': '123 Main St'}
serialized_data... | [
{
"docstring": "Collects user information from standard input and returns as a dictionary.",
"function_declaration": "def collect_user_data():",
"function_name": "collect_user_data",
"parameter_list": "()"
},
{
"docstring": "Serializes the input dictionary using `pickle` and returns the seri... | [
1,
1,
1,
0,
1,
0,
1,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pickle\nimport sqlite3\n\ndef collect_user_data() -> dict:\n \"\"\"\n Collect user information from standard input.\n \"\"\"\n user_data = {}\n us... | trial_gpt4o_2 | {
"original_instruction": "### Advanced Coding Assessment: Serialization and Database Integration\n\n#### Objective\nImplement a Python program that demonstrates data persistence by using the `pickle` and `sqlite3` modules. The task is to create a program that stores and retrieves user data in a persistent manner.\n\... | 0.640157 | Docs: Python310_37339 | C | [
"collect_user_data",
"serialize_data",
"initialize_database",
"store_data_in_db",
"retrieve_data_from_db",
"main"
] | 6 | [
[
"store_data_in_db",
"initialize_database"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 85e704a97d7e9bd4e7445878d7689807d103df64 | 1aa96d86c9eb1bf56123f203521253e6e119fa30 | |||
v1.0 | complete | Docs | Docs: Python310_37405_C | import sysconfig
def fetch_installed_paths():
"""
Returns the default installation paths for the current platform.
>>> isinstance(fetch_installed_paths(), dict)
True
"""
pass
def fetch_configuration_variable(variable_name):
"""
Returns the value of a configuration variable.
... | import sysconfig
def fetch_installed_paths():
"""
Returns the default installation paths for the current platform.
"""
return sysconfig.get_paths()
def fetch_configuration_variable(variable_name):
"""
Returns the value of a configuration variable.
Args:
variable_name (str): The co... | from solution import fetch_installed_paths, fetch_configuration_variable, is_python_source_build, analyze_environment
def test_fetch_installed_paths():
paths = fetch_installed_paths()
assert isinstance(paths, dict)
# Checking if common keys exist in the paths dictionary
assert 'stdlib' in paths
ass... | [
{
"docstring": "Returns the default installation paths for the current platform.",
"function_declaration": "def fetch_installed_paths():",
"function_name": "fetch_installed_paths",
"parameter_list": "()"
},
{
"docstring": "Returns the value of a configuration variable.\n\nArgs:\nvariable_nam... | [
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.889 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sysconfig\n\ndef fetch_installed_paths():\n \"\"\"\n Returns the default installation paths for the current platform.\n \"\"\"\n return sysconfig.get... | trial_gpt4o_9 | {
"original_instruction": "### Python Coding Assessment\n\n#### Question: Analyze Python Installation Paths and Configuration Variables\n\nYou are tasked with writing a Python script that analyzes the current Python installation's configuration and paths to help in setting up a development environment or debugging in... | 0.645837 | Docs: Python310_37405 | C | [
"fetch_installed_paths",
"fetch_configuration_variable",
"is_python_source_build",
"analyze_environment"
] | 4 | [
[
"analyze_environment",
"fetch_configuration_variable"
],
[
"analyze_environment",
"fetch_installed_paths"
],
[
"analyze_environment",
"is_python_source_build"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | f215aef65f6e28d410304c3309de71bce771cc0f | 683dfbdb6ff2f3179676698da8aeffad2cc17942 | |||
v1.0 | complete | Docs | Docs: Python310_37391_C | import asyncio
import random
from typing import List
async def fetch_and_process(urls: List[str], max_concurrent_tasks: int) -> None:
"""Simulates a simplified concurrent web scraping system that fetches and processes data from a list of URLs.
Args:
urls (List[str]): List of URLs to be fetched.
max_co... | import asyncio
import random
from typing import List
async def fetch_data(url: str) -> str:
# Simulate network delay
await asyncio.sleep(random.uniform(0.5, 1.5))
return f"Data from {url}"
async def worker(semaphore: asyncio.Semaphore, queue: asyncio.Queue, url: str):
async with semaphore:
dat... | import asyncio
from solution import fetch_and_process
async def test_fetch_and_process():
urls = [
"http://example.com/page1",
"http://example.com/page2",
"http://example.com/page3"
]
max_concurrent_tasks = 2
await fetch_and_process(urls, max_concurrent_tasks)
# Funct... | [] | [
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 random\nfrom typing import List\n\nasync def fetch_url(url: str) -> str:\n # Simulating network delay of fetching data from url\n await asy... | trial_gpt4o_7 | {
"original_instruction": "**Objective**: Demonstrate the ability to utilize the asyncio module to perform asynchronous programming, manage multiple tasks, handle inter-task communication using asyncio queues, and ensure proper synchronization using asyncio synchronization primitives.\n\n**Question**:\n\nYou are task... | 0.547652 | Docs: Python310_37391 | C | [
"fetch_data",
"worker",
"process_data",
"fetch_and_process"
] | 4 | [
[
"fetch_and_process",
"process_data"
],
[
"fetch_and_process",
"worker"
],
[
"worker",
"fetch_data"
]
] | 3 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | c905bc7ec06a13e41a171accf32fa49e53dc8823 | 5ed322722a7aabaf948501a1355b79be857fa6a6 | |||
v1.0 | complete | Docs | Docs: Python310_37244_C | import asyncio
import contextvars
# function to process a request
def process_request(session_id: str, counter: int, session_var: str) -> dict:
""" Process a request by setting session variables in contextvars.
Args:
session_id (str): The session id for the request.
counter (int): Counter value fo... | import asyncio
import contextvars
session_id_var = contextvars.ContextVar("session_id")
counter_var = contextvars.ContextVar("counter")
session_var_entry = contextvars.ContextVar("session_var")
def process_request(session_id: str, counter: int, session_var: str) -> dict:
session_id_var.set(session_id)
counter... | import asyncio
from solution import process_request, main
def test_process_request():
result1 = process_request("user1", 0, "data1")
assert result1 == {"session_id": "user1", "counter": 1, "session_var": "data1"}
result2 = process_request("user2", 0, "data2")
assert result2 == {"session_id": "user... | [
{
"docstring": null,
"function_declaration": "def process_request(session_id, counter, session_var):",
"function_name": "process_request",
"parameter_list": "(session_id, counter, session_var)"
}
] | [
1,
0,
1,
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 asyncio\nimport contextvars\n\nsession_id_var = contextvars.ContextVar(\"session_id\")\ncounter_var = contextvars.ContextVar(\"counter\")\nsession_var_entry = co... | trial_gpt4o_0 | {
"original_instruction": "**Title: Context Variable Management in Asynchronous Tasks**\n\n#### Problem Statement\n\nYou are tasked to implement a system that simulates processing multiple user requests in an asynchronous server environment, while ensuring each request's context remains isolated. You will use the `co... | 0.495217 | Docs: Python310_37244 | C | [
"process_request",
"handle_request",
"main"
] | 3 | [
[
"handle_request",
"process_request"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f4faf3a0dcb88e6b47a3d23e36f6160c075b2b3c | 0dc89ccd9b35f2782efaea55bffe53b7fb57bacf | |||
v1.0 | complete | Docs | Docs: Seaborn_37146_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 styled_plots():
"""Generates and displays a set of subplots demonstrating different Sea... | 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 styled_plots():
sns.set_theme()
f = plt.figure(figsize=(12, 8))
gs = f.add... | def test_styled_plots():
import matplotlib.pyplot as plt
# Call the function
styled_plots()
# Check that a figure has been created
assert plt.get_fignums(), "No figure created"
# Check that the number of subplots is 4
figs = [plt.figure(num) for num in plt.get_fignums()]
f... | [
{
"docstring": null,
"function_declaration": "def sinplot(n=10, flip=1):",
"function_name": "sinplot",
"parameter_list": "(n=10, flip=1)"
},
{
"docstring": null,
"function_declaration": "def styled_plots():",
"function_name": "styled_plots",
"parameter_list": "()"
}
] | [
0,
1,
0,
1,
1,
0,
0,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import 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": "You are tasked with visualizing a dataset using Seaborn, ensuring that the plots are visually appealing and appropriately styled for different contexts. Write a function `styled_plots` that accomplishes the following:\n\n1. Generates and plots a set of subplots demonstrating four distinct S... | 0.738727 | Docs: Seaborn_37146 | C | [
"sinplot",
"styled_plots"
] | 2 | [
[
"styled_plots",
"sinplot"
]
] | 1 | [] | false | [] | false | pytest | false | [
"matplotlib",
"numpy",
"seaborn"
] | false | 27aaaa48a4a69907afbaaa9f2125172a32b12f38 | 31ec51566284485a6af9f89ca1306789d484b839 | |||
v1.0 | complete | Docs | Docs: Python310_37272_C | from email.parser import BytesParser, BytesFeedParser
from email.policy import default
def parse_email_message_from_file(file_path):
"""
Parses an email message from a file and returns its components.
Args:
file_path (string): Path to a text file containing the complete email message.
Returns... | from email.parser import BytesParser, BytesFeedParser
from email.policy import default
def parse_email_message_from_file(file_path):
"""
Parses an email message from a file and returns its components.
Args:
file_path (string): Path to a text file containing the complete email message.
... | import pytest
import os
from solution import parse_email_message_from_file, incremental_email_parser
def test_parse_email_message_from_file():
email_content = """\
From: test@example.com
To: recipient@example.com
Subject: Test Email
This is a test email message.
"""
file_path = "test_email.eml"
with open(... | [
{
"docstring": "Parses an email message from a file and returns its components.\n\nArgs:\n file_path (string): Path to a text file containing the complete email message.\n\nReturns:\n dict: Contains 'headers', 'body', 'is_multipart', and 'defects'.",
"function_declaration": "def parse_email_message_fr... | [
0,
0,
0,
0,
0,
0,
0,
1,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import email\nfrom email.parser import BytesParser, BytesFeedParser\nfrom email.policy import default\n\ndef parse_email_message_from_file(file_path):\n \"\"\"\n ... | trial_gpt4o_9 | {
"original_instruction": "## Coding Assessment Question\n\n### Objective\nTo gauge your understanding of email parsing functionalities in Python, specifically using the `email.parser` module's `Parser` and `FeedParser` APIs, including handling different types of email messages.\n\n### Question\n\n**Scenario:** You h... | 0.62279 | Docs: Python310_37272 | C | [
"parse_email_message_from_file",
"get_email_body",
"incremental_email_parser"
] | 3 | [
[
"incremental_email_parser",
"get_email_body"
],
[
"parse_email_message_from_file",
"get_email_body"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1eefa86daff870763fb1bac35aefecbba80cfd33 | 08b57937d95ba4e919331104ba74458c388b580b | |||
v1.0 | complete | Docs | Docs: Pytorch_37270_C | import torch
import torch.distributed.rpc as rpc
from typing import List
def simulate_rref_protocol(num_workers: int, owner_index: int, user_indices: List[int]) -> None:
""" Simulate RRef Protocol in a distributed environment.
Args:
- num_workers (int): Number of workers to initialize.
- owner_index (i... | import torch
import torch.distributed.rpc as rpc
from typing import List
import time
def run_worker(rank, world_size, owner_index, user_indices):
rpc.init_rpc(
name=f"worker{rank}",
rank=rank,
world_size=world_size
)
if rank == owner_index:
rref = rpc.RRef("This is an RRef ... | from solution import simulate_rref_protocol
def test_rref_protocol_simple():
num_workers = 3
owner_index = 0
user_indices = [1, 2]
simulate_rref_protocol(num_workers, owner_index, user_indices)
# Testing Guarantee G1 & G2 implicitly through running without errors
def test_rref_protocol_user_to_us... | [
{
"docstring": null,
"function_declaration": "def run_worker(rank, world_size, owner_index, user_indices):",
"function_name": "run_worker",
"parameter_list": "(rank, world_size, owner_index, user_indices)"
},
{
"docstring": null,
"function_declaration": "def use_rref(owner_rref):",
"... | [
0,
0,
1,
0,
1,
0,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.distributed.rpc as rpc\nfrom torch.distributed.rpc import RRef\nfrom typing import List\nimport time\nfrom threading import Event\n\n# This f... | trial_gpt4o_8 | {
"original_instruction": "### PyTorch Distributed RPC: Implementing and Testing RRef Protocol\n\n#### Objective:\nTo assess your understanding of PyTorch's distributed RPC framework, specifically the Remote Reference Protocol (RRef). You will need to implement a function to simulate creating, sharing, and managing R... | 0.401099 | Docs: Pytorch_37270 | C | [
"run_worker",
"use_rref",
"simulate_rref_protocol"
] | 3 | [
[
"run_worker",
"use_rref"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 2acad1084949ca8db7335fdbdadd0d259299b3d6 | 83c9ec769ef6b45315ead1d4d66918318c0c428a | |||
v1.0 | complete | Docs | Docs: Python310_37057_C | import hashlib
def calculate_file_hash(filepath, hash_type):
""" Calculate the hash of a file's content.
:param filepath: Path to the file to be hashed.
:param hash_type: Type of the hash algorithm (e.g., 'sha256', 'blake2b').
:return: The hexadecimal digest of the hashed file content.
"""
... | import hashlib
def calculate_file_hash(filepath, hash_type):
"""
Calculate the hash of a file content.
:param filepath: Path to the file to be hashed.
:param hash_type: Type of the hash algorithm (e.g., 'sha256', 'blake2b').
:return: The hexadecimal digest of the hashed file content.
"""
... | import os
import pytest
from solution import calculate_file_hash, verify_file_hash, sign_file
TEST_FILE_CONTENT = b"Hello, this is a test file for hashing."
TEST_FILE_PATH = "test_file.txt"
# Setup and Teardown for creating a temporary test file
@pytest.fixture(autouse=True)
def setup_and_teardown():
with open(TE... | [
{
"docstring": "Calculate the hash of a file content.\n\n:param filepath: Path to the file to be hashed.\n:param hash_type: Type of the hash algorithm (e.g., 'sha256', 'blake2b').\n:return: The hexadecimal digest of the hashed file content.",
"function_declaration": "def calculate_file_hash(filepath, hash_t... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import hashlib\n\ndef calculate_file_hash(filepath, hash_type):\n \"\"\"\n Calculate the hash of a file content.\n \n :param filepa... | trial_gpt4o_1 | {
"original_instruction": "#### Objective:\nDemonstrate understanding of the hashlib module's hashing methods, including creating and using hash objects, handling bytes-like data, and utilizing advanced features such as keyed hashing and salted hashing.\n\n#### Problem Statement:\nYou are tasked with creating a secur... | 0.722692 | Docs: Python310_37057 | C | [
"calculate_file_hash",
"verify_file_hash",
"sign_file"
] | 3 | [
[
"verify_file_hash",
"calculate_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b76c290f69f38257198921ba6036dd122f2d8f0d | efa7da256085a7e310d652c5ab06c6e45d50cb98 | |||
v1.0 | complete | Docs | Docs: Python310_36835_C | def add_score(data: dict, student: str, subject: str, score: float) -> None:
"""Adds a new score for a student in a given subject.
>>> data = {"Alice": {"Math": 90}}
>>> add_score(data, "Alice", "Science", 95)
>>> data["Alice"]["Science"] == 95
True
>>> add_score(data, "Bob", "Math", 85)
>>>... | def add_score(data, student, subject, score):
if student not in data:
data[student] = {}
data[student][subject] = score
def update_score(data, student, subject, score):
if student in data and subject in data[student]:
data[student][subject] = score
def delete_score(data, student, subject):... | import pytest
from solution import add_score, update_score, delete_score, average_score, top_student, subject_topper, students_with_minimum_score, transpose_scores
def test_add_score():
data = {"Alice": {"Math": 90}}
add_score(data, "Alice", "Science", 95)
assert data["Alice"]["Science"] == 95
add_sco... | [
{
"docstring": null,
"function_declaration": "def add_score(data, student, subject, score):",
"function_name": "add_score",
"parameter_list": "(data, student, subject, score)"
},
{
"docstring": null,
"function_declaration": "def update_score(data, student, subject, score):",
"functio... | [
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": "def add_score(data, student, subject, score):\n if student not in data:\n data[student] = {}\n data[student][subject] = score\n\ndef update_score(data, stu... | trial_gpt4o_9 | {
"original_instruction": "## Problem Statement\n\nYou are given a list of students with their scores in multiple subjects. Your task is to perform various operations such as adding new scores, updating existing scores, calculating the average score for each student, and performing some advanced queries and transform... | 0.560527 | Docs: Python310_36835 | C | [
"add_score",
"update_score",
"delete_score",
"average_score",
"top_student",
"subject_topper",
"students_with_minimum_score",
"transpose_scores"
] | 8 | [
[
"top_student",
"average_score"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f0a71ed026b32fd683b3ac222d813af6cd2ab2a4 | 6c88c5a2678ebe589c809a2ba7ce413b57a4a2ca | |||
v1.0 | complete | Docs | Docs: Python310_37682_C | import cProfile
import pstats
from typing import List
def is_prime(n: int) -> bool:
""" Check if a number is a prime number.
>>> is_prime(2) True
>>> is_prime(4) False
>>> is_prime(13) True
"""
# Profiling the initial implementation
def profile_is_prime():
profiler = cProfile.Profile()
pro... | import cProfile
import pstats
import math
def is_prime(n: int) -> bool:
"""
Check if a number is a prime number.
Parameters:
n (int): The number to be checked.
Returns:
bool: True if n is a prime number, False otherwise.
"""
if n <= 1:
return False
if n <= 3:
retur... | def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(13) == True
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert i... | [
{
"docstring": "Check if a number is a prime number.\n\nParameters:\nn (int): The number to be checked.\n\nReturns:\nbool: True if n is a prime number, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
... | [
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": "def is_prime(n: int) -> bool:\n \"\"\"\n Checks if a number is a prime number.\n \n Args:\n n (int): The number to check.\n \n Returns:\n bool: ... | trial_gpt4o_8 | {
"original_instruction": "### Question: Implementing and Profiling a Function for Prime Number Detection\n\n#### Background\n\nYou are required to implement a Python function that checks whether a given number is a prime number. You will then profile its performance to identify potential bottlenecks and suggest opti... | 0.599312 | Docs: Python310_37682 | C | [
"is_prime",
"profile_is_prime",
"is_prime_optimized",
"profile_is_prime_optimized"
] | 4 | [
[
"profile_is_prime",
"is_prime"
],
[
"profile_is_prime_optimized",
"is_prime_optimized"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | c0790aa735ff31ba4941ad9714ce6fcb63f1ed84 | eb132bed019df84e7b9c568f4c544b5916c0f9c7 | |||
v1.0 | complete | Docs | Docs: Python310_38243_C | import importlib
import inspect
from http.server import SimpleHTTPRequestHandler, HTTPServer
from html import escape
def generate_doc(module_name: str) -> str:
"""Generate documentation for the given module name.
Parameters:
- module_name: str
Returns:
- A string containing the documentation.
... | import inspect
import importlib
from http.server import SimpleHTTPRequestHandler, HTTPServer
from html import escape
def generate_doc(module_name: str) -> str:
"""
Generate documentation for the given module name.
Parameters:
- module_name: str
Returns:
- A string containing the documentation... | from solution import generate_doc
import pytest
def test_generate_doc_valid_module():
doc = generate_doc('sys')
assert "This module provides access to some objects used or maintained by the" in doc
def test_generate_doc_invalid_module():
doc = generate_doc('non_existent_module')
assert doc == "Module ... | [] | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import inspect\nimport importlib\nfrom http.server import SimpleHTTPRequestHandler, HTTPServer\nimport html\n\ndef generate_doc(module_name: str) -> str:\n \"\"\"\n ... | trial_gpt4o_7 | {
"original_instruction": "### Python Coding Assessment Question\n\n**Objective:** Implement a custom subset of the \"pydoc\" functionalities to demonstrate comprehension of generating and serving Python documentation.\n\n#### Problem Statement:\n\nYou are tasked with creating a simple version of the \"pydoc\" tool t... | 0.608024 | Docs: Python310_38243 | C | [
"generate_doc",
"serve_doc"
] | 2 | [
[
"serve_doc",
"generate_doc"
]
] | 1 | [] | false | [
"CustomHTTPRequestHandler"
] | true | pytest | true | [
"test_module"
] | false | 4fd5c3c4767c8607736754b80a9505e7a2ec50bc | ca0cde7515da7f9c6ea8cc467b05295794526778 | |||
v1.0 | complete | Docs | Docs: Python310_37166_C | from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from typing import List, Dict
def schedule_event(date: str, start_time: str, company_timezone: str, attendee_timezones: List[str]) -> Dict[str, str]:
""" Schedule an international event ensuring it does not clash with night hours in any timezon... | from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
def is_night_time(local_time):
if 22 <= local_time.hour or local_time.hour < 6:
return True
return False
def schedule_event(date, start_time, company_timezone, attendee_timezones):
company_datetime = datetime.strptime(f"{date} ... | from solution import schedule_event
def test_event_not_in_night_hours():
event_date = '2023-11-15'
proposed_start = '21:00'
company_tz = 'America/New_York'
attendees_tz = ['Europe/London', 'Asia/Tokyo', 'America/Los_Angeles']
scheduled_times = schedule_event(event_date, proposed_start, company... | [
{
"docstring": null,
"function_declaration": "def is_night_time(local_time):",
"function_name": "is_night_time",
"parameter_list": "(local_time)"
},
{
"docstring": null,
"function_declaration": "def schedule_event(date, start_time, company_timezone, attendee_timezones):",
"function_n... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from datetime import datetime, timedelta\nimport pytz\n\ndef is_night_hour(local_time):\n \"\"\"\n Checks if a given time is within night hours (10 PM to 6 AM).\n... | trial_gpt4o_7 | {
"original_instruction": "**Coding Challenge: International Event Scheduler**\n\n**Objective:**\nYou are required to design a function that schedules an international event for a company. The event must be scheduled such that it accommodates attendees from three different time zones and ensures that the event time d... | 0.723456 | Docs: Python310_37166 | C | [
"is_night_time",
"schedule_event"
] | 2 | [
[
"schedule_event",
"is_night_time"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a2e84315dc40c5059bb122063e5d8f2866c2edc2 | 45c5088bbe01756b58968fc7705163df2b51f0ad | |||
v1.0 | complete | Docs | Docs: Python310_37646_C | def detect_prime_numbers(numbers: list, filter_fn=None, prime_message="{} is a prime number", non_prime_message="{} is not a prime number") -> list:
"""
Analyze a list of integers and identify which are prime numbers with optional filtering.
:param numbers: List of integers to analyze
:param filter... | def is_prime(n):
"""
Check if a number is a prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
p = 3
while p * p <= n:
if n % p == 0:
return False
p += 2
return True
def detect_prime_numbers(numbe... | from solution import detect_prime_numbers
def test_detect_prime_numbers_no_filter():
assert detect_prime_numbers([2, 3, 4, 5, 6]) == [
'2 is a prime number',
'3 is a prime number',
'4 is not a prime number',
'5 is a prime number',
'6 is not a prime number']
def test_det... | [
{
"docstring": "Check if a number is a prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Analyze a list of integers and identify which are prime numbers with optional filtering.\n\n:param numbers: List of integers to ... | [
1,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def detect_prime_numbers(numbers: list, filter_fn=None, prime_message=\"{} is a prime number\", non_prime_message=\"{} is not a prime number\") -> list:\n def is_pri... | trial_gpt4o_7 | {
"original_instruction": "### Advanced Python Function Implementation\n\n**Problem Statement:**\n\nYou are required to implement a Python function `detect_prime_numbers` that analyzes a list of integers and identifies which of them are prime numbers. Additionally, the function should support customization for:\n- Nu... | 0.746467 | Docs: Python310_37646 | C | [
"is_prime",
"detect_prime_numbers"
] | 2 | [
[
"detect_prime_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 934496e0e5fdb0a4ddae5446b79a322caadbe048 | 252c4dd2f5eed49dffe7df9f7ba5001edeb3d43d | |||
v1.0 | complete | Docs | Docs: Python310_38302_C | import asyncio
async def handle_client(reader, writer):
"""
Handle incoming client connections and process HTTP GET requests.
- If the request is valid, respond with a HTML message.
- If the request is not valid, respond with a 400 Bad Request status.
Args:
reader (asyncio.StreamReader): Strea... | import asyncio
async def handle_client(reader, writer):
try:
data = await reader.readuntil(b'\r\n\r\n')
message = data.decode()
request_line = message.split("\r\n")[0]
method, path, version = request_line.split()
if method == 'GET':
response = 'HTTP/1.1 200 OK\r... | import asyncio
import socket
import pytest
@pytest.mark.asyncio
async def test_server_response():
server_task = asyncio.create_task(start_server())
await asyncio.sleep(1) # Let the server start
reader, writer = await asyncio.open_connection('localhost', 8080)
request = 'GET / HTTP/1.1\r\nHost: localh... | [] | [
0,
1,
1,
1,
1,
0,
0,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n try:\n request = await reader.readuntil(b'\\r\\n\\r\\n')\n except asyncio.IncompleteReadError:... | trial_gpt4o_1 | {
"original_instruction": "### Asynchronous Web Server Simulation\n\n#### Objective\nImplement a simple asynchronous web server that can handle multiple client connections concurrently using the `asyncio` module. The server should be able to process HTTP GET requests and respond with an appropriate message.\n\n#### T... | 0.584219 | Docs: Python310_38302 | C | [
"handle_client",
"start_server"
] | 2 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 89b4d78dd44d5ef49ad23f92efabadccd554fa17 | 85259db884ba8cd138ce913f30c131ad47ff58ba | |||
v1.0 | complete | Docs | Docs: Python310_37955_C | import selectors
import socket
import types
def accept(sock, mask):
"""
Accept a new client connection.
"""
pass
def service_connection(key, mask):
"""
Service an existing client connection, reading and echoing data back.
"""
pass
def start_server():
"""
Start the echo serve... | import selectors
import socket
import types
sel = selectors.DefaultSelector()
def accept(sock, mask):
conn, addr = sock.accept() # Should be ready
conn.setblocking(False)
data = types.SimpleNamespace(addr=addr, inb=b'', outb=b'')
events = selectors.EVENT_READ | selectors.EVENT_WRITE
sel.register(... | import socket
import threading
import time
# Start server in a separate thread
def run_server():
import solution
solution.start_server()
server_thread = threading.Thread(target=run_server, daemon=True)
server_thread.start()
time.sleep(1) # Ensure the server has time to start
def test_echo_single_message():
... | [
{
"docstring": null,
"function_declaration": "def accept(sock, mask):",
"function_name": "accept",
"parameter_list": "(sock, mask)"
},
{
"docstring": null,
"function_declaration": "def service_connection(key, mask):",
"function_name": "service_connection",
"parameter_list": "(key... | [
0,
1,
1,
1,
0,
1,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import selectors\nimport socket\n\ndef accept(sock, mask):\n conn, addr = sock.accept() # Should be ready\n print('Accepted connection from', addr)\n conn.set... | trial_gpt4o_1 | {
"original_instruction": "**Question: Implement an Echo Server using the `selectors` module**\n\nUsing the `selectors` module in Python, implement an echo server that can handle multiple client connections concurrently. The server should:\n\n1. Accept incoming client connections.\n2. Read data from connected clients... | 0.670699 | Docs: Python310_37955 | C | [
"accept",
"service_connection",
"start_server"
] | 3 | [
[
"start_server",
"accept"
],
[
"start_server",
"service_connection"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 208766550f82b1425ce1a085c92f2c208a13c064 | 6a0c0a8deafd00c4178d711d2169350bcd455965 | |||
v1.0 | complete | Docs | Docs: Python310_38131_C | import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def cpu_bound_task(data):
"""
Simulate a CPU-bound task by performing a computationally intensive operation.
"""
result = 0
for i in range(1, data * 10000):
result += i * i
return result
def io_bound_tas... | import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
# Simulate a CPU-bound task by performing a computationally intensive operation
def cpu_bound_task(data):
# Just a dummy function that performs some heavy computations
result = 0
for i in range(1, data * 10000):
resu... | from solution import cpu_bound_task, io_bound_task, process_tasks
def test_cpu_bound_task():
assert cpu_bound_task(1) == sum(i * i for i in range(1, 10000))
assert cpu_bound_task(2) == sum(i * i for i in range(1, 20000))
def test_io_bound_task():
assert io_bound_task(1) == 1
assert io_bound_task(5) ==... | [
{
"docstring": null,
"function_declaration": "def cpu_bound_task(data):",
"function_name": "cpu_bound_task",
"parameter_list": "(data)"
},
{
"docstring": null,
"function_declaration": "def io_bound_task(data):",
"function_name": "io_bound_task",
"parameter_list": "(data)"
},
... | [
1,
0,
0,
0,
1,
1,
0,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\n\ndef simulate_io_task(complexity):\n import time\n time.sleep(complexity)\n return com... | trial_gpt4o_7 | {
"original_instruction": "### Problem: Concurrent Execution and Resource Management\n\nYou are required to implement a Python function that processes a list of tasks using both threading and multiprocessing to optimize for both CPU-bound and IO-bound operations. The task list contains tuples where each tuple has the... | 0.641798 | Docs: Python310_38131 | C | [
"cpu_bound_task",
"io_bound_task",
"process_tasks"
] | 3 | [
[
"process_tasks",
"cpu_bound_task"
],
[
"process_tasks",
"io_bound_task"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8def36dc05f4ed5a41ac14659167d4400127542c | 3786758c6c39cad99563c630c5fac61464776b72 | |||
v1.0 | complete | Docs | Docs: Python310_38159_C | import asyncio
async def handle_echo(reader, writer):
"""Handle the echo functionality for a TCP server."""
...
# Implement your handler here
...
async def tcp_echo_server(host: str, port: int):
"""Start a TCP echo server."""
server = await asyncio.start_server(handle_echo, host, port)
asy... | import asyncio
async def handle_echo(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} from {addr!r}")
print(f"Send: {message!r}")
writer.write(data)
await writer.drain()
print("Close the conne... | import asyncio
import pytest
from asyncio import gather
from solution import tcp_echo_server, tcp_echo_client
@pytest.mark.asyncio
async def test_tcp_echo():
server_task = asyncio.create_task(tcp_echo_server('127.0.0.1', 8888))
await asyncio.sleep(1) # Give the server a second to start
client_message = ... | [] | [
0,
0,
1,
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 asyncio\n\nasync def handle_echo(reader, writer):\n data = await reader.read(100)\n message = data.decode()\n addr = writer.get_extra_info('peername')\n... | trial_gpt4o_6 | {
"original_instruction": "### Python Coding Assessment Question\n\n**Problem Statement:**\n\nYour task is to create both a TCP echo client and a TCP echo server using asyncio streams in Python. They should communicate such that the client sends a message to the server, the server echoes it back, and the client recei... | 0.706352 | Docs: Python310_38159 | C | [
"handle_echo",
"tcp_echo_server",
"tcp_echo_client",
"main"
] | 4 | [
[
"tcp_echo_server",
"handle_echo"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bfe0f25cccadd40c8032f010de7504be68ce74e1 | 4ba440e8a803d3419fbac8bfca0d25f04a523a5a | |||
v1.0 | complete | Docs | Docs: Python310_37867_C | import struct
import threading
import pprint
def create_binary_user_file(file_path):
"""Create a binary file containing records of users.
Each record contains:
- user_id: 4 bytes, unsigned integer.
- username_length: 1 byte, unsigned integer.
- username: variable length string based on username_len... | import struct
import threading
import pprint
def create_binary_user_file(file_path):
user_data = [
(1234, 'Alice'),
(5678, 'Bob'),
(91011, 'Charlie'),
(121314, 'David')
]
with open(file_path, 'wb') as f:
for user_id, username in user_data:
username_length... | from solution import create_binary_user_file, read_user_data, pretty_print_user_data, parallel_read_and_print
import os
def test_create_binary_user_file():
file_path = 'test_users.bin'
create_binary_user_file(file_path)
assert os.path.isfile(file_path)
os.remove(file_path)
def test_read_user_data():
... | [
{
"docstring": null,
"function_declaration": "def create_binary_user_file(file_path):",
"function_name": "create_binary_user_file",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def read_user_data(file_path):",
"function_name": "read_user_data",
... | [
0,
0,
0,
0,
0,
1,
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 struct\nimport threading\nimport os\nfrom pprint import pprint\n\ndef create_binary_user_file(file_path, user_data):\n with open(file_path, 'wb') as f:\n ... | trial_gpt4o_6 | {
"original_instruction": "### Question: Binary Data and Pretty Printing with Multithreading\n\nYou have been tasked with creating a program that reads binary data from a file, processes the data to extract specific information, and prints this information in a readable format while performing these tasks in parallel... | 0.509487 | Docs: Python310_37867 | C | [
"create_binary_user_file",
"read_user_data",
"pretty_print_user_data",
"parallel_read_and_print"
] | 4 | [
[
"parallel_read_and_print",
"pretty_print_user_data"
],
[
"parallel_read_and_print",
"read_user_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4bcbe77cbad245ffc30f4d749c5d06e4ac66ad36 | a9ffe2e6febd385cf28f7c313e2df8c042e73649 | |||
v1.0 | complete | Docs | Docs: Pytorch_37505_C | import torch
import torch.nn as nn
import torch.optim as optim
# Define a simple feedforward neural network
class SimpleNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU... | import torch
import torch.nn as nn
import torch.optim as optim
import os
from torch.distributed import init_process_group, destroy_process_group
# Define a simple feedforward neural network
class SimpleNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(SimpleNN, self).__init__()... | import os
import torch
import torch.nn as nn
import torch.optim as optim
from solution import SimpleNN, save_checkpoint, load_checkpoint
def test_save_load_checkpoint():
model = SimpleNN(input_size=10, hidden_size=20, output_size=1)
optimizer = optim.SGD(model.parameters(), lr=0.01)
checkpoint_path = './ch... | [] | [
0,
0,
1,
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 torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport os\nfrom torch.distributed.checkpoint import save, load\nimport torch.distributed.checkpoint as... | trial_gpt4o_2 | {
"original_instruction": "### Distributed Checkpoint in PyTorch\n\nYou are tasked with simulating a distributed training environment using PyTorch's `torch.distributed.checkpoint` module for saving and loading checkpoints. Your goal is to manage the state dictionaries of a model and optimizer across multiple devices... | 0.657706 | Docs: Pytorch_37505 | C | [
"save_checkpoint",
"load_checkpoint",
"run_training",
"main"
] | 4 | [
[
"run_training",
"load_checkpoint"
],
[
"run_training",
"save_checkpoint"
]
] | 2 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"torch"
] | false | 6b4f2b5be896b5669a7e48341e3ce88efa699517 | 8f2d61947de8edcd2519790754ac51ce5c1d5490 | |||
v1.0 | complete | Docs | Docs: Python310_38346_C | import asyncio
import os
async def run_command(command):
"""
Run a command in a subprocess and capture its output.
"""
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proce... | import asyncio
import os
async def run_command(command):
"""
Run a command in a subprocess and capture its output.
"""
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proce... | import pytest
from solution import run_command, run_tasks
import os
@pytest.mark.asyncio
async def test_run_command_ls():
"""
Test the `run_command` function with the 'ls' command.
"""
# Check for directory listing
command = "ls ./"
process = await asyncio.create_subprocess_shell(
comma... | [] | [
1,
1,
1,
0,
0,
1,
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 os\n\nasync def run_tasks(directory):\n async def run_command(command):\n process = await asyncio.create_subprocess_shell(\n ... | trial_gpt4o_8 | {
"original_instruction": "**Coding Assessment Question**\n\nWrite a Python program that creates two subprocesses asynchronously. Each subprocess will perform a different task and their outputs must be captured and displayed. One subprocess should list the contents of a directory, while the other should display the c... | 0.640451 | Docs: Python310_38346 | C | [
"run_command",
"run_tasks",
"main"
] | 3 | [
[
"run_tasks",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5e59727bcbbd17b85e106e78f05eecf51998160d | 685e309b29b339f35346429ed6603e33b9a8fe50 | |||
v1.0 | complete | Docs | Docs: Python310_37797_C | import asyncio
import aiohttp
from typing import List, Dict, Optional
async def fetch_all_contents(urls: List[str]) -> Dict[str, Optional[str]]:
"""
Given a list of URLs, fetch the contents concurrently using asyncio and aiohttp.
:param urls: List of strings representing the URLs to fetch.
:return: Di... | import asyncio
import aiohttp
from typing import List, Dict, Optional
async def fetch_content(session: aiohttp.ClientSession, url: str) -> Optional[str]:
"""
Fetch the content of a URL using the given session.
:param session: aiohttp ClientSession
:param url: URL to fetch content from
:return:... | import pytest
import asyncio
from solution import fetch_all_contents
@pytest.mark.asyncio
async def test_fetch_all_contents_valid_url():
urls = ['https://example.com']
result = await fetch_all_contents(urls)
assert 'https://example.com' in result
assert result['https://example.com'] is not None
@pytes... | [] | [
0,
1,
1,
0,
1,
0,
1,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport aiohttp\nfrom typing import List, Dict, Optional\n\nasync def fetch_content(session, url):\n try:\n async with session.get(url, timeout... | trial_gpt4o_4 | {
"original_instruction": "**Problem Statement:**\n\nImplement a function to concurrently fetch the contents of multiple URLs using the `asyncio` high-level API. The function should take a list of URLs and return a dictionary where the keys are the URLs and the values are the fetched contents. If a URL cannot be fetc... | 0.612435 | Docs: Python310_37797 | C | [
"fetch_content",
"fetch_all_contents"
] | 2 | [
[
"fetch_all_contents",
"fetch_content"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 4c6533f1543ba79b4ae6b9e5401d817febed63ff | 60870e5d42ec88bdc373154bccb57a81e6a15f8e | |||
v1.0 | complete | Docs | Docs: Python310_38286_C | import requests
from bs4 import BeautifulSoup
from multiprocessing import Pool
from typing import List, Dict
def fetch_data(url: str) -> str:
"""
Fetch HTML content from a given URL using the requests library.
Parameters:
url (str): The URL to fetch data from.
Returns:
str: HTML conte... | import requests
from bs4 import BeautifulSoup
from multiprocessing import Pool
from typing import List, Dict
def fetch_data(url: str) -> str:
"""
Fetch HTML content from a given URL.
Parameters:
url (str): The URL to fetch data from.
Returns:
str: HTML content of the page.
"""
... | from solution import fetch_data, concurrent_fetch, aggregate_data
def test_fetch_data():
url = 'http://example.com'
result = fetch_data(url)
assert isinstance(result, str)
assert '<html>' in result.lower() # Ensure it's an HTML document
def test_concurrent_fetch():
urls = ['http://example.com', '... | [
{
"docstring": "Fetch HTML content from a given URL.\n\nParameters:\nurl (str): The URL to fetch data from.\n\nReturns:\nstr: HTML content of the page.",
"function_declaration": "def fetch_data(url):",
"function_name": "fetch_data",
"parameter_list": "(url)"
},
{
"docstring": "Fetch all URLs... | [
0,
1,
0,
0,
1,
0,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nfrom multiprocessing import Pool\nfrom typing import List, Dict\nfrom bs4 import BeautifulSoup\n\ndef fetch_data(url: str) -> str:\n \"\"\"\n Fet... | trial_gpt4o_8 | {
"original_instruction": "### Multiprocessing-Based Web Scraper with Data Aggregation\n\n#### Objective\nYou need to write a Python script using the `multiprocessing` package to create a web scraper that fetches data from multiple URLs concurrently and aggregates the results.\n\n#### Task Description\n1. **Create a ... | 0.705802 | Docs: Python310_38286 | C | [
"fetch_data",
"concurrent_fetch",
"aggregate_data",
"main"
] | 4 | [
[
"concurrent_fetch",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"bs4",
"requests"
] | false | a4640cd49a2dd08791528f921acf3f7622c59222 | 22daebf02f6734c1fdeefabf194eb2a2cc08cd52 | |||
v1.0 | complete | Docs | Docs: Python310_37605_C | import asyncio
import subprocess
class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):
def get_event_loop(self):
"""Custom get_event_loop method
Logs a message each time it's called.
"""
print("Custom get_event_loop called")
return super().get_event_loop()
class MyThread... | import asyncio
import subprocess
class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):
def get_event_loop(self):
print("Custom get_event_loop called")
return super().get_event_loop()
class MyThreadedChildWatcher(asyncio.ThreadedChildWatcher):
def add_child_handler(self, pid, callback, *args... | import asyncio
import subprocess
from solution import MyEventLoopPolicy, MyThreadedChildWatcher, run_custom_event_loop
async def test_create_subprocess():
process = await create_subprocess()
assert process.returncode == 0
stdout, stderr = await process.communicate()
assert stdout.decode().strip() == 'h... | [] | [
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport subprocess\n\nclass MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):\n def get_event_loop(self):\n print(\"Custom get_event_loop call... | trial_gpt4o_0 | {
"original_instruction": "### Custom Asyncio Event Loop Policy with Process Watcher\n\n**Objective**:\nImplement a custom event loop policy that integrates a specialized process watcher capable of handling subprocess lifecycle events efficiently using threads.\n\n**Problem Statement**:\nYou are required to create a ... | 0.548813 | Docs: Python310_37605 | C | [
"create_subprocess",
"run_custom_event_loop"
] | 2 | [
[
"run_custom_event_loop",
"create_subprocess"
]
] | 1 | [] | false | [
"MyEventLoopPolicy",
"MyThreadedChildWatcher"
] | true | pytest | true | [] | true | 300da00ea8e20665b8f38024c186c0817aa5b72f | f9e1a2e62bfca045885dc69b02095b8a96b49dac | |||
v1.0 | complete | Docs | Docs: Python310_38397_C | import syslog
def configure_logging(ident: str, logoption: int, facility: int) -> None:
"""
Configures the syslog with the given identifier, log option, and facility.
"""
print(f"Configuring syslog with ident='{ident}', logoption={logoption}, facility={facility}...")
def log_messages() -> None:
""... | import syslog
def configure_logging(ident: str, logoption: int, facility: int) -> None:
"""
Configures the syslog with the given identifier, log option, and facility.
"""
print(f"Configuring syslog with ident='{ident}', logoption={logoption}, facility={facility}...")
syslog.openlog(ident, logoption... | import syslog
from unittest.mock import patch
def test_configure_logging():
with patch('syslog.openlog') as mocked_openlog:
configure_logging('test_ident', syslog.LOG_PID | syslog.LOG_CONS, syslog.LOG_USER)
mocked_openlog.assert_called_with('test_ident', syslog.LOG_PID | syslog.LOG_CONS, syslog.LOG... | [
{
"docstring": "Configures the syslog with the given identifier, log option, and facility.",
"function_declaration": "def configure_logging(ident, logoption, facility):",
"function_name": "configure_logging",
"parameter_list": "(ident, logoption, facility)"
},
{
"docstring": "Logs messages w... | [
1,
1,
0,
0,
1,
0,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import syslog\n\ndef configure_logging(ident: str, logoption: int, facility: int) -> None:\n \"\"\"\n Configures the syslog with the given identifier, log option,... | trial_gpt4o_8 | {
"original_instruction": "You are tasked with creating a Python script that demonstrates advanced logging capabilities using the `syslog` module. Your script should:\n\n1. **Open the syslog**:\n - Use `openlog` to customize the logging behavior with a custom identifier (`ident`) and log option (`logoption`).\n2. *... | 0.593338 | Docs: Python310_38397 | C | [
"configure_logging",
"log_messages",
"set_log_mask",
"reset_logging"
] | 4 | [
[
"reset_logging",
"configure_logging"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 2de2882acc4fdcb3e049ef1501a142971213a44c | 5114ab498564a769d7690a2145703c5a14b5f857 | |||
v1.0 | complete | Docs | Docs: Python310_38330_C | import functools
import time
@functools.cache
def cached_power(base: int, exponent: int) -> int:
"""
Calculates base raised to the power exponent with an artificial delay.
Args:
base (int): The base number.
exponent (int): The power to raise the base to.
Returns:
int: The result o... | import functools
import time
@functools.cache
def cached_power(base: int, exponent: int) -> int:
"""
Calculates base raised to the power exponent with an artificial delay.
Args:
base (int): The base number.
exponent (int): The power to raise the base to.
Returns:
int: The result o... | import time
from solution import cached_power, partial_cached_power
def test_cached_power_initial_call():
start_time = time.time()
assert cached_power(2, 10) == 1024
elapsed_time = time.time() - start_time
assert elapsed_time >= 2
def test_cached_power_cached_call():
start_time = time.time()
a... | [
{
"docstring": "Calculates base raised to the power exponent with an artificial delay.\n\nArgs:\nbase (int): The base number.\nexponent (int): The power to raise the base to.\n\nReturns:\nint: The result of base ** exponent.",
"function_declaration": "def cached_power(base, exponent):",
"function_name":... | [
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 functools\nimport time\n\n@functools.cache\ndef cached_power(base: int, exponent: int) -> int:\n \"\"\"\n Computes base raised to the power exponent with a... | trial_gpt4o_9 | {
"original_instruction": "### Question: Efficient Calculation and Caching using functools\n\nYou have been assigned a task to efficiently compute the result of a mathematical function with the help of caching and function manipulation.\n\n#### Problem:\nImplement a function `cached_power(base: int, exponent: int) ->... | 0.477211 | Docs: Python310_38330 | C | [
"cached_power",
"partial_cached_power"
] | 2 | [
[
"partial_cached_power",
"cached_power"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 99afebbf006f2878824756834b7bead49c277ee4 | 60e7a32bbc5c716352bf2815d3ae512eb7d31f8a | |||
v1.0 | complete | Docs | Docs: Python310_38294_C | import asyncio
from typing import List, Dict
async def run_commands(commands: List[str]) -> List[Dict[str, str]]:
"""
Execute a list of shell commands in parallel and capture their outputs and errors.
Parameters:
commands (List[str]): A list of shell commands to be executed.
Returns:
... | import asyncio
from typing import List, Dict
async def run_command(command: str) -> Dict[str, str]:
"""
Execute a single shell command and capture its outputs and errors.
Parameters:
command (str): The shell command to be executed.
Returns:
Dict[str, str]: A dictionary contain... | import asyncio
from solution import run_commands
def test_run_commands():
asyncio.run(test_run_commands_inner())
async def test_run_commands_inner():
commands = ["echo Hello", "invalid_command"]
results = await run_commands(commands)
assert len(results) == 2
result_1 = results[0]
as... | [] | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Dict\n\nasync def run_command(command: str) -> Dict[str, str]:\n process = await asyncio.create_subprocess_shell(\n c... | trial_gpt4o_9 | {
"original_instruction": "**Advanced Python Coding Assessment**\n\n### Problem Statement\n\nYou are required to implement an asynchronous Python function that executes multiple shell commands in parallel, captures their standard output and error streams, and returns the results in an organized manner. This function ... | 0.700285 | Docs: Python310_38294 | C | [
"run_command",
"run_commands",
"main"
] | 3 | [
[
"run_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4651c761299ee15392f8d401405f11c84aa539d1 | bb7ff7a741fdb406e3c7d0dfecad31d0e76725d2 | |||
v1.0 | complete | Docs | Docs: Pandas_37267_C | import pandas as pd
import numpy as np
from pandas.api.indexers import BaseIndexer
def load_data(filepath):
""" Loads the data from a CSV file and sets the date as an index.
Args:
filepath (str): Path to the CSV file.
Returns:
pd.DataFrame: Loaded DataFrame.
"""
df = pd.read_csv(filep... | import pandas as pd
import numpy as np
from pandas.api.indexers import BaseIndexer
def load_data(filepath):
df = pd.read_csv(filepath, parse_dates=['Date'])
df.set_index('Date', inplace=True)
return df
def calculate_7day_rolling_mean(df):
df['7Day_Rolling_Close_Mean'] = df.groupby('Company')['Close'].... | import pytest
import pandas as pd
from io import StringIO
from solution import (load_data, calculate_7day_rolling_mean, calculate_expanding_max,
calculate_ewma, calculate_custom_volume_sum, calculate_5day_rolling_corr)
csv_data = """
Date,Company,Open,Close,High,Low,Volume
2023-01-01,CompanyA,10... | [] | [
0,
1,
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 pandas as pd\nimport numpy as np\nfrom pandas.api.indexers import BaseIndexer\n\ndef load_data(filepath):\n \"\"\"\n Load stock prices data from a CSV file... | trial_gpt4o_1 | {
"original_instruction": "### Pandas Windowing Operations Assessment\n\n#### Objective\nTo test the understanding and application of pandas windowing operations, including rolling, expanding, exponentially weighted windows, and custom window functions.\n\n#### Problem Statement\n\nYou are provided with a dataset con... | 0.75276 | Docs: Pandas_37267 | C | [
"load_data",
"calculate_7day_rolling_mean",
"calculate_expanding_max",
"calculate_ewma",
"calculate_custom_volume_sum",
"calculate_5day_rolling_corr",
"process_stock_data"
] | 7 | [
[
"process_stock_data",
"calculate_5day_rolling_corr"
],
[
"process_stock_data",
"calculate_7day_rolling_mean"
],
[
"process_stock_data",
"calculate_custom_volume_sum"
],
[
"process_stock_data",
"calculate_ewma"
],
[
"process_stock_data",
"calculate_expanding_... | 6 | [] | false | [
"CustomIndexer"
] | true | pytest | true | [
"numpy",
"pandas"
] | false | a4e66ce714b3f503ab54a21e2d836d07b1be1f81 | 1269f7cdb3233f72f00299ae091b7181ed00441d | |||
v1.0 | complete | Docs | Docs: Pytorch_37968_C | import torch
from torch.utils.dlpack import from_dlpack, to_dlpack
def convert_to_dlpack(tensor):
""" Convert a PyTorch tensor to a DLPack tensor.
>>> tensor = torch.tensor([1, 2, 3], dtype=torch.float32)
>>> dlpack_tensor = convert_to_dlpack(tensor)
"""
pass
def convert_from_dlpack(dlpack_tensor)... | import torch
from torch.utils.dlpack import from_dlpack, to_dlpack
def convert_to_dlpack(tensor):
"""
Convert a PyTorch tensor to a DLPack tensor.
"""
return to_dlpack(tensor)
def convert_from_dlpack(dlpack_tensor):
"""
Convert a DLPack tensor to a PyTorch tensor.
"""
return from_dlpac... | from solution import convert_to_dlpack, convert_from_dlpack, interoperability_test
import torch
def test_convert_to_dlpack():
tensor = torch.tensor([1, 2, 3], dtype=torch.float32)
dlpack_tensor = convert_to_dlpack(tensor)
assert isinstance(dlpack_tensor, object) # Check if the returned object is non-trivi... | [
{
"docstring": "Convert a PyTorch tensor to a DLPack tensor.",
"function_declaration": "def convert_to_dlpack(tensor):",
"function_name": "convert_to_dlpack",
"parameter_list": "(tensor)"
},
{
"docstring": "Convert a DLPack tensor to a PyTorch tensor.",
"function_declaration": "def conve... | [
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 torch\nfrom torch.utils.dlpack import to_dlpack, from_dlpack\n\ndef convert_to_dlpack(tensor):\n \"\"\"\n Converts a given PyTorch tensor to a DLPack tenso... | trial_gpt4o_9 | {
"original_instruction": "<|Analysis Begin|>\n\nThe provided documentation describes two functions within the `torch.utils.dlpack` module: `from_dlpack` and `to_dlpack`. These functions facilitate data interchange between PyTorch tensors and other frameworks that support DLPack, a tensor format standard.\n\n- `from_... | 0.513145 | Docs: Pytorch_37968 | C | [
"convert_to_dlpack",
"convert_from_dlpack",
"interoperability_test"
] | 3 | [
[
"interoperability_test",
"convert_from_dlpack"
],
[
"interoperability_test",
"convert_to_dlpack"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 4af570d712360277f7e8940d2bb5d54e8839fa17 | ab40cef9c61ba724248f798bbd3b359c686c6e7d | |||
v1.0 | complete | Docs | Docs: Pytorch_37829_C | import os
import re
import subprocess
def set_environment_variables():
""" Sets the necessary environment variables for profiling with TorchInductor. """
os.environ['TORCHINDUCTOR_UNIQUE_KERNEL_NAMES'] = '1'
os.environ['TORCHINDUCTOR_BENCHMARK_KERNEL'] = '1'
def run_benchmark_script():
""" Executes th... | import os
import re
import subprocess
def set_environment_variables():
os.environ['TORCHINDUCTOR_UNIQUE_KERNEL_NAMES'] = '1'
os.environ['TORCHINDUCTOR_BENCHMARK_KERNEL'] = '1'
def run_benchmark_script():
command = "python -u benchmarks/dynamo/timm_models.py --backend inductor --amp --performance --dashboa... | import os
import subprocess
from unittest.mock import patch, mock_open
def test_set_environment_variables():
set_environment_variables()
assert os.environ['TORCHINDUCTOR_UNIQUE_KERNEL_NAMES'] == '1'
assert os.environ['TORCHINDUCTOR_BENCHMARK_KERNEL'] == '1'
@patch('subprocess.run')
def test_run_benchmark_... | [
{
"docstring": null,
"function_declaration": "def set_environment_variables():",
"function_name": "set_environment_variables",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def run_benchmark_script():",
"function_name": "run_benchmark_script",
"parameter... | [
1,
1,
0,
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 os\nimport subprocess\n\ndef set_environment_variables():\n \"\"\"\n Sets the required environment variables for TorchInductor.\n \"\"\"\n os.environ... | trial_gpt4o_6 | {
"original_instruction": "### PyTorch: Profiling Model Performance with TorchInductor\n\n#### Problem Statement\n\nYou are tasked with profiling the performance of a deep learning model using PyTorch's TorchInductor on a GPU. Specifically, you will:\n1. Set relevant environment variables.\n2. Run a benchmark script ... | 0.518267 | Docs: Pytorch_37829 | C | [
"set_environment_variables",
"run_benchmark_script",
"extract_compiled_module_path",
"analyze_performance_logs",
"extract_kernel_path",
"profile_individual_kernel",
"main"
] | 7 | [
[
"analyze_performance_logs",
"extract_compiled_module_path"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | b583163ad24c79bdbcac94da9d4f328e5a7cfe13 | c23800e40ce943e5532f86eb0f163cc5a34818d1 | |||
v1.0 | complete | Docs | Docs: Python310_38188_C | import setuptools
import os
def validate_files(data_files):
"""
Validates that all data files exist.
>>> validate_files(["data/file1.txt", "data/file2.txt"])
True
>>> validate_files(["data/file1.txt", "data/missing_file.txt"])
Traceback (most recent call last):
...
FileNotFoundErro... | import setuptools
import os
def validate_files(data_files):
"""
Validates that all data files exist.
"""
missing_files = [file for file in data_files if not os.path.exists(file)]
if missing_files:
raise FileNotFoundError(f"Data files not found: {missing_files}")
return True
def create_... | import pytest
import os
from solution import create_setup_script, validate_files
def setup_module(module):
"""
Setup the test environment by creating temporary files and directories.
"""
os.makedirs("data", exist_ok=True)
with open("data/file1.txt", "w") as f:
f.write("This is file1.")
... | [
{
"docstring": "Validates that all data files exist.",
"function_declaration": "def validate_files(data_files):",
"function_name": "validate_files",
"parameter_list": "(data_files)"
},
{
"docstring": "Creates a setup script using setuptools with given packages, extension module, and data fil... | [
1,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import setuptools\nimport os\n\ndef validate_files(data_files):\n \"\"\"\n Validates that all data files exist.\n \"\"\"\n missing_files = [file for file in... | trial_gpt4o_0 | {
"original_instruction": "**Objective:**\nThe goal of this task is to ensure you comprehend the fundamental and advanced concepts of distributing Python modules, both through legacy tools like Distutils and modern alternatives like Setuptools.\n\n**Task:**\nImplement a Python script that emulates a simplified versio... | 0.510858 | Docs: Python310_38188 | C | [
"validate_files",
"create_setup_script"
] | 2 | [
[
"create_setup_script",
"validate_files"
]
] | 1 | [] | false | [] | false | pytest | true | [
"setuptools"
] | false | 2f09bcc6621b15c2af766711fb9e8f9fab149321 | a0ccc6df3f20b234d22f43b36aa508177b1524c8 | |||
v1.0 | complete | Docs | Docs: Pytorch_38047_C | import torch
import time
def benchmark_matmul(size=2048) -> float:
"""
Measures and returns the time taken to perform a large matrix multiplication
using PyTorch.
Parameters:
size (int): The size of the square matrices to multiply.
Returns:
float: Time taken to perform the matrix multipli... | import torch
import time
def benchmark_matmul(size=2048):
"""
Measures and returns the time taken to perform a large matrix multiplication
using PyTorch.
Parameters:
size (int): The size of the square matrices to multiply.
Returns:
float: Time taken to perform the matrix multiplication.
... | def test_benchmark_matmul_cpu():
time_taken = benchmark_matmul()
assert time_taken > 0
def test_toggle_mixed_precision():
# Ensures API changes do not raise errors.
try:
toggle_mixed_precision(tf32=True, fp16=True, bf16=True)
toggle_mixed_precision(tf32=False)
toggle_mixed_preci... | [
{
"docstring": "Measures and returns the time taken to perform a large matrix multiplication\nusing PyTorch.\n\nParameters:\nsize (int): The size of the square matrices to multiply.\n\nReturns:\nfloat: Time taken to perform the matrix multiplication.",
"function_declaration": "def benchmark_matmul(size=2048... | [
0,
0,
0,
1,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport time\n\ndef benchmark_matmul(size=2048):\n \"\"\"\n Measures and returns the time taken to perform a large matrix multiplication using PyTorc... | trial_gpt4o_6 | {
"original_instruction": "### Question: PyTorch Backend Optimization for Matrix Multiplication\n\n#### Background\n\nIn this question, you will work with various PyTorch backend functionalities to control and optimize matrix multiplications on different hardware. Specifically, you will use `torch.backends.cuda` to t... | 0.497655 | Docs: Pytorch_38047 | C | [
"benchmark_matmul",
"toggle_mixed_precision",
"benchmark_with_settings"
] | 3 | [
[
"benchmark_with_settings",
"benchmark_matmul"
],
[
"benchmark_with_settings",
"toggle_mixed_precision"
]
] | 2 | [] | false | [] | false | pytest | false | [
"torch"
] | false | 2a56598c8945515370d1f2ec3bd477e45befe3ae | c01d34a3b24f5ac17ca2941bd5e166d4743a21b5 | |||
v1.0 | complete | Docs | Docs: Python310_37988_C | import sqlite3
class Review:
"""
Custom Review class to include review text and reviewer name.
"""
def __init__(self, text, reviewer):
self.text = text
self.reviewer = reviewer
def __repr__(self):
return f"Review({self.text}, {self.reviewer})"
def adapt_review(review):
... | import sqlite3
class Review:
def __init__(self, text, reviewer):
self.text = text
self.reviewer = reviewer
def __repr__(self):
return f'Review({self.text}, {self.reviewer})'
def adapt_review(review):
return f"{review.text};{review.reviewer}".encode()
def convert_review(s):
te... | import sqlite3
import pytest
from solution import setup_database, insert_sample_data, fetch_books_by_author, update_book_rating, Review, setup_review_conversion
def test_setup_database():
setup_database()
con = sqlite3.connect("books.db")
cur = con.cursor()
cur.execute("SELECT name FROM sqlite_master W... | [] | [
0,
0,
1,
1,
1,
1,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sqlite3\n\nclass Review:\n def __init__(self, text, reviewer):\n self.text = text\n self.reviewer = reviewer\n\n def __repr__(self):\n ... | trial_gpt4o_5 | {
"original_instruction": "**Question: Comprehensive Database Interaction Using `sqlite3`**\n\nYou're tasked with creating a mini application that manages a database of books using the `sqlite3` module. This application should allow for creating the database and table, inserting data, performing queries, editing entr... | 0.559307 | Docs: Python310_37988 | C | [
"adapt_review",
"convert_review",
"setup_database",
"insert_sample_data",
"fetch_books_by_author",
"update_book_rating",
"setup_review_conversion"
] | 7 | [
[
"setup_review_conversion",
"adapt_review"
],
[
"setup_review_conversion",
"convert_review"
]
] | 2 | [] | false | [
"Review"
] | true | pytest | true | [] | true | 38189adff7669b138cefb1e2b51428bddc04562c | e7f606951f7b87cdd121190452d64a07e3c21623 | |||
v1.0 | complete | Docs | Docs: Python310_38738_C | import errno
def retrieve_error_message(err_code: int) -> str:
"""
Returns a string that explains the error, or
an appropriate built-in exception name if the error code maps directly to one of Python’s built-in exceptions.
>>> retrieve_error_message(errno.EPERM) "PermissionError"
>>> retrieve_err... | import errno
def retrieve_error_message(err_code: int) -> str:
"""
Returns a string that explains the error, or
an appropriate built-in exception name if the error code maps directly to one of Python’s built-in exceptions.
"""
error_map = {
errno.EPERM: "PermissionError",
errno.ENO... | from solution import retrieve_error_message, describe_all_errors
import errno
def test_retrieve_error_message():
assert retrieve_error_message(errno.EPERM) == "PermissionError"
assert retrieve_error_message(errno.ENOENT) == "FileNotFoundError"
assert retrieve_error_message(errno.EBADF) == "Bad file descrip... | [
{
"docstring": "Returns a string that explains the error, or \nan appropriate built-in exception name if the error code maps directly to one of Python’s built-in exceptions.",
"function_declaration": "def retrieve_error_message(err_code):",
"function_name": "retrieve_error_message",
"parameter_list"... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import errno\n\ndef retrieve_error_message(err_code: int) -> str:\n \"\"\"\n Returns the error message for a given error code, or the exception name\n if the e... | trial_gpt4o_2 | {
"original_instruction": "**Objective**: Demonstrate the ability to work with system error codes and handle exceptions using the Python `errno` module.\n\n#### Problem Description\n\nYou are required to implement a function `retrieve_error_message` that takes an integer error code and returns either:\n- A string tha... | 0.542953 | Docs: Python310_38738 | C | [
"retrieve_error_message",
"describe_all_errors"
] | 2 | [
[
"describe_all_errors",
"retrieve_error_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c749043a6c45911b5ba202287a1fda5d1a8e27a0 | 03372d94f49aa34dbc44cb4b7400f2251a65b6f2 | |||
v1.0 | complete | Docs | Docs: Python310_38837_C | import sys
def process_file():
""" Process a text file specified as a command-line argument. This function
should properly manage resources to avoid any warnings in Python Development Mode.
"""
# Your modified code here
def process_lines(lines):
# Placeholder for line processing code
pass... | import sys
def process_file():
# Open the file using a with statement to ensure it is closed properly
with open(sys.argv[1]) as fp:
lines = fp.readlines()
process_lines(lines)
print("Processing complete")
def process_lines(lines):
# Placeholder for line processing code
pass
if __... | import os
import subprocess
import pytest
def create_temp_file(content):
filename = "temp_test_file.txt"
with open(filename, "w") as f:
f.write(content)
return filename
def test_process_file():
# Create a temporary file for the test
test_filename = create_temp_file("Line 1\nLine 2\nLine 3\... | [
{
"docstring": null,
"function_declaration": "def process_file():",
"function_name": "process_file",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def process_lines(lines):",
"function_name": "process_lines",
"parameter_list": "(lines)"
}
] | [
1,
1,
0,
1,
1,
1,
1,
0,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\n\ndef process_file():\n with open(sys.argv[1]) as fp:\n lines = fp.readlines()\n process_lines(lines)\n print(\"Processing complete\")\n... | trial_gpt4o_6 | {
"original_instruction": "### Python Development Mode and Resource Management\n\nYou are provided with a script that reads and processes a text file specified as a command-line argument. The current implementation, however, has some resource management issues that are only detected when Python Development Mode is en... | 0.543023 | Docs: Python310_38837 | C | [
"process_file",
"process_lines"
] | 2 | [
[
"process_file",
"process_lines"
]
] | 1 | [
"process_lines"
] | false | [] | false | pytest | false | [] | true | 94f6ec1c5f7605c3901650f996ebcd43e4be1282 | 54faf8ae2c64e94fd8ef66998e683807ea4d2f17 | |||
v1.0 | complete | Docs | Docs: Python310_37808_C | import multiprocessing
from queue import Empty
import requests
def fetch_url(url):
"""
Fetch the HTML content of the given URL.
Args:
- url (str): The URL to fetch.
Returns:
- str: HTML content of the URL.
"""
try:
response = requests.get(url)
return response.t... | import multiprocessing
from queue import Empty
import requests
def fetch_url(url):
"""
Fetch the HTML content of the given URL.
Args:
- url (str): The URL to fetch.
Returns:
- str: HTML content of the URL.
"""
try:
response = requests.get(url)
return response.t... | from solution import fetch_url, process_urls
def test_fetch_url_success(monkeypatch):
class MockResponse:
@staticmethod
def get(*args, **kwargs):
class MockResponseInner:
text = 'HTML content of the page'
return MockResponseInner()
monkeypatch.setatt... | [
{
"docstring": "Fetch the HTML content of the given URL.\n\nArgs:\n- url (str): The URL to fetch.\n\nReturns:\n- str: HTML content of the URL.",
"function_declaration": "def fetch_url(url):",
"function_name": "fetch_url",
"parameter_list": "(url)"
},
{
"docstring": "Worker function to fetch ... | [
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 multiprocessing\nfrom queue import Empty\nimport requests\n\ndef fetch_url(url):\n \"\"\"\n Fetch the HTML content of the given URL.\n \n Args:\n ... | trial_gpt4o_4 | {
"original_instruction": "**Objective:**\nYou are tasked with developing a concurrent program that processes a list of URLs to fetch their HTML content. This will assess your understanding of the \"multiprocessing\" package in Python.\n\n**Description:**\nWrite a Python program using the \"multiprocessing\" package ... | 0.621522 | Docs: Python310_37808 | C | [
"fetch_url",
"worker",
"process_urls"
] | 3 | [
[
"worker",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 1396cd1c383cf1a13953a04d82ef8fa1929d546d | b61c9e830118d96934e5483e7979539d40961809 | |||
v1.0 | complete | Docs | Docs: Python310_38011_C | import asyncio
from typing import List
async def fetch_data(url: str) -> str:
"""
Simulate fetching data from a URL by using asyncio.sleep.
Args:
url (str): The URL to fetch data from.
Returns:
str: Fetched data from the URL.
Example:
>>> asyncio.run(fetch_data("http://example.com"))... | import asyncio
from typing import List
async def fetch_data(url: str) -> str:
await asyncio.sleep(2) # simulate network delay
return f"Data from {url}"
async def process_data(data: str) -> str:
await asyncio.sleep(1) # simulate processing delay
return data[::-1].upper()
async def task_manager(urls:... | import asyncio
from solution import fetch_data, process_data, task_manager
def test_fetch_data():
async def wrapper():
result = await fetch_data("http://example.com")
assert result == "Data from http://example.com"
asyncio.run(wrapper())
def test_process_data():
async def wrapper(... | [] | [
1,
1,
1,
0,
0,
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 asyncio\nfrom typing import List\n\nasync def fetch_data(url: str) -> str:\n await asyncio.sleep(2) # simulate network delay\n return f\"Data from {url}\"... | trial_gpt4o_0 | {
"original_instruction": "#### Objective\nDemonstrate the practical application and understanding of asyncio in Python 3.10 by creating a simple concurrent task manager that includes network IO operations.\n\n#### Problem Statement\nYou are required to create an asynchronous task manager that performs multiple tasks... | 0.516404 | Docs: Python310_38011 | C | [
"fetch_data",
"process_data",
"task_manager"
] | 3 | [
[
"task_manager",
"fetch_data"
],
[
"task_manager",
"process_data"
]
] | 2 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | d1b0d85676cbde4685da44c1b70fa78f4c2936b1 | 1da646375e6386b860a6e6ae5dad0903e419b50d | |||
v1.0 | complete | Docs | Docs: Python310_38642_C | import concurrent.futures
import urllib.request
import urllib.error
def fetch_urls(urls, timeout, max_workers):
"""
Fetch the contents of multiple URLs asynchronously using ThreadPoolExecutor.
Args:
urls (list of str): A list of URLs to fetch.
timeout (int or float): The maximum number of ... | import concurrent.futures
import urllib.request
import urllib.error
def fetch_url(url, timeout):
try:
with urllib.request.urlopen(url, timeout=timeout) as response:
return len(response.read())
except Exception as e:
return f"Error: {e}"
def fetch_urls(urls, timeout, max_workers):
... | from solution import fetch_urls
def test_fetch_urls_valid():
urls = [
'http://httpbin.org/get',
'https://jsonplaceholder.typicode.com/posts',
'http://www.example.com',
]
results = fetch_urls(urls, timeout=5, max_workers=3)
for url in urls:
assert isinstance(results[url],... | [
{
"docstring": null,
"function_declaration": "def fetch_url(url, timeout):",
"function_name": "fetch_url",
"parameter_list": "(url, timeout)"
},
{
"docstring": null,
"function_declaration": "def fetch_urls(urls, timeout, max_workers):",
"function_name": "fetch_urls",
"parameter_l... | [
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 concurrent.futures\nimport urllib.request\nimport urllib.error\n\ndef fetch_url(url, timeout):\n try:\n with urllib.request.urlopen(url, timeout=timeou... | trial_gpt4o_0 | {
"original_instruction": "**Question: Asynchronous Web Scraping with Timeout Handling**\n\n**Objective:** \nImplement a function that asynchronously scrapes data from a list of URLs and handles potential exceptions, including timeouts and non-existent domains. Use `ThreadPoolExecutor` to manage concurrent requests a... | 0.652149 | Docs: Python310_38642 | C | [
"fetch_url",
"fetch_urls"
] | 2 | [
[
"fetch_urls",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a668f3632d031e365408ca8b40bdc791dafec99a | 7b0900a9be5074fa74410ded5e7e081126db05b0 | |||
v1.0 | complete | Docs | Docs: Python310_38019_C | import asyncio
async def handle_client(reader, writer):
"""
Handle an incoming client connection, read data, and echo it back to the client.
Args:
reader: StreamReader object to read incoming data.
writer: StreamWriter object to send data back to the client.
"""
pass
async def start_serve... | import asyncio
async def handle_client(reader, writer):
try:
while True:
data = await reader.read(100)
if not data:
break
writer.write(data)
await writer.drain()
except asyncio.CancelledError:
pass
except Exception as e:
... | import asyncio
import pytest
from solution import handle_client, start_server
@pytest.mark.asyncio
async def test_server_echo():
# Start the server
server_task = asyncio.create_task(start_server())
await asyncio.sleep(1)
reader, writer = await asyncio.open_connection('localhost', 8888)
test_messag... | [
{
"docstring": null,
"function_declaration": "def main():",
"function_name": "main",
"parameter_list": "()"
}
] | [
1,
0,
0,
1,
0,
0,
0,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n try:\n while True:\n data = await reader.read(100)\n if not data:\n ... | trial_gpt4o_0 | {
"original_instruction": "### Asyncio Networking and Task Management with Python 3.10\n\n#### Objective\nYour task is to create an echo server and client using Python's `asyncio` module. The server will accept connections from clients, read incoming data, and echo back the same data to the client. Additionally, you ... | 0.61418 | Docs: Python310_38019 | C | [
"handle_client",
"start_server",
"main"
] | 3 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1d8b499fcad757c9d59158123de8a0f4acd7dbdf | 01946ea88bd4392a245520ab16384b29982e3c47 | |||
v1.0 | complete | Docs | Docs: Python310_38496_C | import contextvars
from typing import Any, Callable
# Step 1: Initialize context variable
user_id = contextvars.ContextVar('user_id', default=None)
def set_user_id(new_id: int) -> contextvars.Token:
"""
Sets the user_id context variable to new_id and returns the token representing the context state before the... | import contextvars
from typing import Any, Callable
# Step 1: Initialize context variable
user_id = contextvars.ContextVar('user_id', default=None)
def set_user_id(new_id: int) -> contextvars.Token:
"""
Sets the user_id context variable to new_id and returns the token representing the context state before the... | import contextvars
from solution import set_user_id, reset_user_id, run_in_custom_context, user_id
def get_current_user_id():
"""
Helper function to return the current value of the user_id context variable.
"""
return user_id.get()
def test_set_user_id():
token = set_user_id(123)
assert get_cu... | [
{
"docstring": "Sets the user_id context variable to new_id and returns the token representing the context state before the call.",
"function_declaration": "def set_user_id(new_id):",
"function_name": "set_user_id",
"parameter_list": "(new_id)"
},
{
"docstring": "Resets the user_id context v... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import contextvars\nfrom typing import Any, Callable\n\n# Step 1: Initialize context variable\nuser_id = contextvars.ContextVar('user_id', default=None)\n\ndef set_user... | trial_gpt4o_2 | {
"original_instruction": "#### Context Management with `contextvars`\n\n**Objective:**\nIn this task, you will create a set of functions to manage context-local state using the `contextvars` module. Specifically, you will create functions that:\n1. Initialize context variables with default values.\n2. Modify the val... | 0.404589 | Docs: Python310_38496 | C | [
"set_user_id",
"reset_user_id",
"run_in_custom_context"
] | 3 | [
[
"run_in_custom_context",
"reset_user_id"
],
[
"run_in_custom_context",
"set_user_id"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3bd71d1ed451f4ed7e6193748e626cf05093c2b1 | 0d9f626ee01c589ff1cfc32fc60731b5de53b9c4 | |||
v1.0 | complete | Docs | Docs: Scikit_38415_C | import pandas as pd
import numpy as np
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRe... | import pandas as pd
import numpy as np
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRe... | from solution import load_and_preprocess_data, train_and_evaluate_models
import numpy as np
import pandas as pd
from sklearn.datasets import make_regression
# Create a synthetic dataset to simulate house prices
def create_synthetic_house_price_data():
X, y = make_regression(n_samples=100, n_features=10, noise=0.1)... | [
{
"docstring": null,
"function_declaration": "def load_and_preprocess_data(filepath):",
"function_name": "load_and_preprocess_data",
"parameter_list": "(filepath)"
},
{
"docstring": null,
"function_declaration": "def train_and_evaluate_models(filepath):",
"function_name": "train_and_... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncode... | trial_gpt4o_3 | {
"original_instruction": "You are provided with a dataset of house prices and various features describing the houses. Your task is to build a robust machine learning model using the scikit-learn library to predict house prices. Specifically, you are required to:\n\n1. **Load and preprocess the dataset:**\n - Handl... | 0.720153 | Docs: Scikit_38415 | C | [
"load_and_preprocess_data",
"train_and_evaluate_models"
] | 2 | [
[
"train_and_evaluate_models",
"load_and_preprocess_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | f08394450d0740dd87c000ab9cf130ecd3ea81ff | 2b4906bff8b88870bb59aecdb7b770575180558a | |||
v1.0 | complete | Docs | Docs: Python310_38567_C | import sqlite3
from datetime import datetime
class SensorReading:
def __init__(self, date, temperature, humidity):
self.date = date
self.temperature = temperature
self.humidity = humidity
def __repr__(self):
return f"SensorReading(date={self.date}, temperature={self.temperature... | import sqlite3
from datetime import datetime
class SensorReading:
def __init__(self, date, temperature, humidity):
self.date = date
self.temperature = temperature
self.humidity = humidity
def __repr__(self):
return f"SensorReading(date={self.date}, temperature={self.temperature... | import pytest
from solution import SensorReading, adapt_sensor_reading, convert_sensor_reading, setup_database, insert_data, fetch_data
def test_adapt_sensor_reading():
reading = SensorReading("2023-10-10", 23.5, 50.0)
adapted = adapt_sensor_reading(reading)
assert adapted == ("2023-10-10", 23.5, 50.0)
de... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sqlite3\n\nclass SensorReading:\n def __init__(self, date, temperature, humidity):\n self.date = date\n self.temperature = temperature\n ... | trial_gpt4o_1 | {
"original_instruction": "### Advanced SQLite Management in Python\n\nYou are given the task to manage an SQLite database using Python's `sqlite3` module. This database must handle frequent insertion of records, ensure data integrity, and make use of both custom data adapters and converters. The following coding tas... | 0.553527 | Docs: Python310_38567 | C | [
"adapt_sensor_reading",
"convert_sensor_reading",
"setup_database",
"insert_data",
"fetch_data",
"main"
] | 6 | [
[
"insert_data",
"adapt_sensor_reading"
]
] | 1 | [] | false | [
"SensorReading"
] | true | pytest | true | [] | true | bdfae3787af382c50ac8295c2d5f66845f079617 | c98a04d28cb1a81be97db9e8d369de60f1b38aa7 | |||
v1.0 | complete | Docs | Docs: Python310_38717_C | import asyncio
from typing import List
# Custom Exception for download errors
class DownloadError(Exception):
pass
async def download_file(url: str) -> str:
""" Simulates downloading a file from the given URL.
Raises DownloadError with a certain probability to simulate a download failure.
"""
pass... | import asyncio
import random
from typing import List
# Custom Exception for download errors
class DownloadError(Exception):
pass
async def download_file(url: str) -> str:
"""
Simulates downloading a file from the given URL.
It raises DownloadError with a 30% probability to simulate a download failure.... | import pytest
import asyncio
from solution import download_file, download_files, DownloadError
@pytest.mark.asyncio
async def test_download_file_success():
url = "http://example.com/success"
result = await download_file(url)
assert result == url
@pytest.mark.asyncio
async def test_download_file_failure():... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\nimport logging\nfrom typing import List\n\n# Set up logging\nlogging.basicConfig(level=logging.INFO)\n\nclass DownloadError(Exception):\n... | trial_gpt4o_2 | {
"original_instruction": "### Asynchronous File Downloader with Retry Logic\n\nYou are tasked with implementing an asynchronous file downloader that downloads multiple files concurrently with the ability to retry downloading in case of failure. This function should make use of asyncio's task management, synchronizat... | 0.616675 | Docs: Python310_38717 | C | [
"download_file",
"download_files"
] | 2 | [
[
"download_files",
"download_file"
]
] | 1 | [] | false | [
"DownloadError"
] | true | pytest | true | [] | true | 4fa037367d77909c36b7f2d3ee38c4343b012894 | 70087a8b85f52dba00b817d742cb643493b4a2a7 | |||
v1.0 | complete | Docs | Docs: Python310_38834_C | import signal
def handle_sigalrm(signum, frame):
"""
Signal handler for SIGALRM.
Prints a message and exits the program.
>>> handle_sigalrm(signal.SIGALRM, None)
Received SIGALRM. Exiting the program!
"""
pass
def setup_signal_handler():
"""
Sets up the signal handler for SIGALRM.
... | import signal
import sys
def handle_sigalrm(signum, frame):
"""
Signal handler for SIGALRM.
Prints a message and exits the program.
"""
print("Received SIGALRM. Exiting the program!")
sys.exit(0)
def setup_signal_handler():
"""
Sets up the signal handler for SIGALRM.
"""
signal... | import signal
import os
import subprocess
import pytest
# Since this functionality involves handling OS signals and involves timing,
# it's best tested through subprocess to observe the output.
def test_handle_sigalrm():
# Create a simple script as a string
script = """
import signal
import sys
def handle_s... | [
{
"docstring": "Signal handler for SIGALRM.\nPrints a message and exits the program.",
"function_declaration": "def handle_sigalrm(signum, frame):",
"function_name": "handle_sigalrm",
"parameter_list": "(signum, frame)"
},
{
"docstring": "Sets up the signal handler for SIGALRM.",
"functi... | [
0,
1,
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 signal\nimport sys\n\ndef handle_sigalrm(signum, frame):\n \"\"\"\n Signal handler for SIGALRM.\n Prints a message and terminates the program.\n \"\"... | trial_gpt4o_7 | {
"original_instruction": "### Question: Implementing Custom Signal Handlers and Timer\n\nYou are required to write a Python program that performs the following tasks:\n\n1. **Set up a signal handler** for the `SIGALRM` signal. This handler should print \"Received SIGALRM. Exiting the program!\" and then terminate th... | 0.575759 | Docs: Python310_38834 | C | [
"handle_sigalrm",
"setup_signal_handler",
"schedule_alarm",
"long_running_task",
"main"
] | 5 | [
[
"setup_signal_handler",
"handle_sigalrm"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 4149d9afb5c8572026ca753dc30f9d66522de879 | 624842457109471d5c3c5540e1eb2fb63ab939c4 | |||
v1.0 | complete | Docs | Docs: Python310_38157_C | import hashlib
def generate_personalized_hash(file_path: str, personalization_string: str) -> str:
"""
Generates a personalized BLAKE2b hash for the given file.
:param file_path: Path to the file
:param personalization_string: Personalization string, must be no longer than 16 bytes
:return: He... | import hashlib
def generate_personalized_hash(file_path: str, personalization_string: str) -> str:
"""
Generates a personalized BLAKE2b hash for the given file.
:param file_path: Path to the file
:param personalization_string: Personalization string, must be no longer than 16 bytes
:return: Hexade... | import os
import pytest
from solution import generate_personalized_hash, verify_file_integrity
# Sample file path for testing
test_file_path = 'test_file.txt'
personalization_string = 'file_check'
def setup_module(module):
# Create a test file
with open(test_file_path, 'w') as f:
f.write("Hello, world... | [
{
"docstring": "Generates a personalized BLAKE2b hash for the given file.\n\n:param file_path: Path to the file\n:param personalization_string: Personalization string, must be no longer than 16 bytes\n:return: Hexadecimal string representing the personalized hash value of the file's content",
"function_decl... | [
0,
1,
1,
0,
0,
1,
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 hashlib\n\ndef generate_personalized_hash(file_path: str, personalization_string: str) -> str:\n \"\"\"\n Generates a personalized BLAKE2b hash for the giv... | trial_gpt4o_8 | {
"original_instruction": "Secure File Integrity Check with Personalized BLAKE2 Hashing\n\nYou have been contracted to create a secure file integrity verification system that uses the BLAKE2 hashing algorithm. This system should allow users to generate personalized hash values for their files and verify the integrity... | 0.626915 | Docs: Python310_38157 | C | [
"generate_personalized_hash",
"verify_file_integrity"
] | 2 | [
[
"verify_file_integrity",
"generate_personalized_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8f11ce0821070f2682d1c274f9b2ebb75f708786 | 36f80ae82aa92321db9840303b93419dfc48e6cf | |||
v1.0 | complete | Docs | Docs: Scikit_38027_C | import pandas as pd
from sklearn.decomposition import PCA
from sklearn.random_projection import johnson_lindenstrauss_min_dim, SparseRandomProjection
from sklearn.cluster import FeatureAgglomeration
from sklearn.preprocessing import StandardScaler
def load_and_preprocess_data(file_path):
""" Load the data from a C... | import pandas as pd
from sklearn.decomposition import PCA
from sklearn.random_projection import johnson_lindenstrauss_min_dim, SparseRandomProjection
from sklearn.cluster import FeatureAgglomeration
from sklearn.preprocessing import StandardScaler
def load_and_preprocess_data(file_path):
# Load the data
data =... | import pytest
from solution import (
load_and_preprocess_data,
apply_pca,
apply_random_projection,
apply_feature_agglomeration,
dimensionality_reduction_comparison
)
import pandas as pd
import numpy as np
# Mock data for testing
data_csv = 'data.csv'
data = pd.DataFrame({
'feature1': np.random.... | [
{
"docstring": null,
"function_declaration": "def load_and_preprocess_data(file_path):",
"function_name": "load_and_preprocess_data",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def apply_pca(data_scaled):",
"function_name": "apply_pca",
"para... | [
0,
1,
0,
0,
1,
0,
0,
1,
0
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom sklearn.decomposition import PCA\nfrom sklearn.random_projection import johnson_lindenstrauss_min_dim, SparseRandomProjection\nfrom sklearn.cl... | trial_gpt4o_1 | {
"original_instruction": "You are given a high-dimensional dataset (`data.csv`), and your task is to perform unsupervised dimensionality reduction using different techniques from the scikit-learn library. You will need to apply Principal Component Analysis (PCA), Random Projections, and Feature Agglomeration, and th... | 0.729394 | Docs: Scikit_38027 | C | [
"load_and_preprocess_data",
"apply_pca",
"apply_random_projection",
"apply_feature_agglomeration",
"dimensionality_reduction_comparison"
] | 5 | [
[
"dimensionality_reduction_comparison",
"apply_feature_agglomeration"
],
[
"dimensionality_reduction_comparison",
"apply_pca"
],
[
"dimensionality_reduction_comparison",
"apply_random_projection"
],
[
"dimensionality_reduction_comparison",
"load_and_preprocess_data"
]
... | 4 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 8de214dc06296fcb18c096e498375277c9f50487 | 626c578235c6ce7b18669feacfd1f1fe39593d6e | |||
v1.0 | complete | Docs | Docs: Python310_38848_C | import ctypes
from ctypes import CDLL, CFUNCTYPE, POINTER, c_int, c_void_p
from typing import List
def compare(a, b):
ai = ctypes.cast(a, ctypes.POINTER(c_int)).contents.value
bi = ctypes.cast(b, ctypes.POINTER(c_int)).contents.value
return ai - bi
def sort_integers(arr: List[int]) -> List[int]:
"""
... | import ctypes
from ctypes import CDLL, CFUNCTYPE, POINTER, c_int, c_void_p
from typing import List
def compare(a, b):
ai = ctypes.cast(a, ctypes.POINTER(c_int)).contents.value
bi = ctypes.cast(b, ctypes.POINTER(c_int)).contents.value
return ai - bi
def sort_integers(arr: List[int]) -> List[int]:
if no... | def test_sort_random_numbers():
assert sort_integers([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
def test_sort_already_sorted():
assert sort_integers([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_sort_reverse_order():
assert sort_integers([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def... | [
{
"docstring": null,
"function_declaration": "def compare(a, b):",
"function_name": "compare",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def sort_integers(arr):",
"function_name": "sort_integers",
"parameter_list": "(arr)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport ctypes\nimport platform\n\ndef sort_integers(arr: List[int]) -> List[int]:\n if platform.system() == \"Linux\":\n libc = ctype... | trial_gpt4o_8 | {
"original_instruction": "### ctypes Question\n\nYou are required to implement a Python function using the `ctypes` library to interact with a C standard library function. The function you need to interact with is `qsort` from the C standard library, which sorts an array.\n\nHere’s what you need to do:\n\n1. Impleme... | 0.648586 | Docs: Python310_38848 | C | [
"compare",
"sort_integers"
] | 2 | [
[
"sort_integers",
"compare"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 6de27574a299d1f06b9231995125e77b8dc0afac | 3210b88171ccbab5bd9ce174909fa52b2b3026f2 | |||
v1.0 | complete | Docs | Docs: Scikit_38940_C | import pandas as pd
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import time
... | import pandas as pd
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import time
... | from solution import optimize_prediction_performance
import pandas as pd
def test_optimize_prediction_performance():
# Create a mock dataset
data = {
'feature1': [1, 2, 0, 4, 0],
'feature2': [0, 0, 3, 0, 5],
'feature3': [7, 8, 0, 0, 0],
'target': [0, 1, 0, 1, 0]
}
df = p... | [
{
"docstring": null,
"function_declaration": "def measure_latency_and_throughput(estimator, X, Y, bulk_size=1000):",
"function_name": "measure_latency_and_throughput",
"parameter_list": "(estimator, X, Y, bulk_size=1000)"
},
{
"docstring": null,
"function_declaration": "def optimize_pred... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport numpy as np\nfrom scipy.sparse import csr_matrix\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom skle... | trial_gpt4o_9 | {
"original_instruction": "### Question: Optimizing Prediction Performance with scikit-learn\n\nYou are given a dataset containing features and labels for a binary classification problem. Your task is to:\n1. Implement a scikit-learn pipeline to preprocess the data and train a classifier.\n2. Optimize the prediction ... | 0.690224 | Docs: Scikit_38940 | C | [
"measure_latency_and_throughput",
"optimize_prediction_performance"
] | 2 | [
[
"optimize_prediction_performance",
"measure_latency_and_throughput"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"scipy",
"sklearn"
] | false | 978a0d10d2d5cf5e93b78ba86502740f8def46d5 | dbb76083e472ae29f638935c3af14a0376222dbf | |||
v1.0 | complete | Docs | Docs: Python310_37947_C | import os
import atexit
import readline
def initialize_history(histfile=os.path.expanduser("~/.custom_history"), hist_len=2000):
"""
Initialize command history by loading from the specified file,
and set up saving history upon exit.
Parameters:
histfile (str): Path to the history file.
hist_le... | import os
import atexit
import readline
def initialize_history(histfile=os.path.expanduser("~/.custom_history"), hist_len=2000):
"""
Initialize command history by loading from the specified file,
and set up saving history upon exit.
Parameters:
histfile (str): Path to the history file.
hist_le... | import readline
from solution import initialize_history, custom_completer, setup_readline
def test_initialize_history(tmpdir):
histfile = tmpdir.join(".custom_history")
initialize_history(str(histfile))
readline.add_history('test_command')
assert readline.get_current_history_length() == 1
assert re... | [
{
"docstring": "Initialize command history by loading from the specified file,\nand set up saving history upon exit.\n\nParameters:\nhistfile (str): Path to the history file.\nhist_len (int): Maximum number of history entries to save.",
"function_declaration": "def initialize_history(histfile=os.path.expand... | [
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 os\nimport atexit\nimport readline\n\ndef initialize_history(histfile=os.path.expanduser(\"~/.custom_history\"), hist_len=2000):\n \"\"\"\n Initializes the... | trial_gpt4o_5 | {
"original_instruction": "### Question: Implementing Enhanced Interactive Command History Management\n\nYou have been asked to implement a command history management system using the `readline` module. This system will enhance the default capabilities in two key areas:\n1. **Persistent History Management**: \n\n T... | 0.371362 | Docs: Python310_37947 | C | [
"initialize_history",
"custom_completer",
"setup_readline"
] | 3 | [
[
"setup_readline",
"custom_completer"
],
[
"setup_readline",
"initialize_history"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b83110155e84d91e27b873f6cd7d0fda5a3e6398 | 0d186c269ce077e65e02a256abd7a436a0aedbb0 | |||
v1.0 | complete | Docs | Docs: Python310_38501_C | def argument_clinic(param_types: dict):
"""Decorator that enforces argument types and generates docstring for the decorated function.
>>> @argument_clinic({'n': int, 'name': str, 'flag': bool})
... def example_function(n, name, flag):
... pass
>>> help(example_function)
example_function(n: i... | def argument_clinic(param_types: dict):
def decorator(f):
def wrapped_func(*args, **kwargs):
# Check positional arguments
for i, (arg_name, arg_type) in enumerate(param_types.items()):
if i < len(args):
if not isinstance(args[i], arg_type):
... | def test_example_function_valid():
assert example_function(5, "testName", True) == "n: 5, name: testName, flag: True"
def test_example_function_type_error_positional():
try:
example_function("5", "testName", True)
except TypeError as e:
assert str(e) == "Argument 'n' must be of type int"
... | [
{
"docstring": null,
"function_declaration": "def argument_clinic(param_types):",
"function_name": "argument_clinic",
"parameter_list": "(param_types)"
},
{
"docstring": "Function that demonstrates example usage of argument_clinic",
"function_declaration": "def example_function(n, name, ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def argument_clinic(param_types: dict):\n def decorator(f):\n def wrapped_func(*args, **kwargs):\n # Check argument types\n for i, (arg_... | trial_gpt4o_1 | {
"original_instruction": "**Objective**: In this task, you need to demonstrate your understanding of parsing argument lists, dynamically generating documentation, and handling input constraints in Python functions by implementing a pseudo Argument Clinic-like mechanism in Python.\n\n### Problem Description:\nYou are... | 0.604048 | Docs: Python310_38501 | C | [
"argument_clinic",
"example_function",
"another_example"
] | 3 | [
[
"another_example",
"argument_clinic"
],
[
"example_function",
"argument_clinic"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 8fe876e19b65e50fa384cd3bb67ac081aab7768e | bd067341044a4b93f5e4db313e96812bde198b97 | |||
v1.0 | complete | Docs | Docs: Pytorch_38767_C | import torch
import torch.nn as nn
import torch.ao.quantization as quantization
from typing import List
def fuse_model(model):
layers_to_fuse = []
for name, module in model.named_children():
if isinstance(module, nn.Sequential):
fuse_model(module)
if isinstance(module, nn.Conv2d) or... | import torch
import torch.nn as nn
import torch.ao.quantization as quantization
def fuse_model(model):
layers_to_fuse = []
for name, module in model.named_children():
if isinstance(module, nn.Sequential):
fuse_model(module)
if isinstance(module, nn.Conv2d) or isinstance(module, nn.L... | import pytest
import torch
import torch.nn as nn
from solution import prepare_for_quantization
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.conv = nn.Conv2d(1, 20, 5, 1)
self.bn = nn.BatchNorm2d(20)
self.fc = nn.Linear(320, 10)
def ... | [
{
"docstring": null,
"function_declaration": "def fuse_model(model):",
"function_name": "fuse_model",
"parameter_list": "(model)"
},
{
"docstring": null,
"function_declaration": "def prepare_for_quantization(model, dtype_layers, dtype=torch.qint8):",
"function_name": "prepare_for_qua... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch import nn\nfrom torch.ao.quantization import fuse_modules, quantize_dynamic\nfrom typing import List\n\ndef prepare_for_quantization(model: tor... | trial_gpt4o_7 | {
"original_instruction": "## Quantization Accuracy Improvement in PyTorch\n\n### Objective\nYour task is to implement a PyTorch function that prepares a given model for quantization by fusing Conv-BN layers and adjusting the dtype of specific layers to improve quantization accuracy.\n\n### Description\nYou will impl... | 0.478555 | Docs: Pytorch_38767 | C | [
"fuse_model",
"prepare_for_quantization"
] | 2 | [
[
"prepare_for_quantization",
"fuse_model"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | f631366cd79ec651ec8aed6c7e087103ddddc431 | 1b4e2a1c28db1b75fde89ad9910b93a1477cfa76 | |||
v1.0 | complete | Docs | Docs: Scikit_37654_C | import os
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
def stream_documents(file_path: str, chunk_size: int):
"""
Generator function that yields chunks of text documents from a file.
Args:
- file_path: str : Path to the file containing th... | import os
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
def stream_documents(file_path: str, chunk_size: int):
"""
Generator function that yields chunks of text documents from a file.
Args:
- file... | import tempfile
import os
import pytest
from solution import stream_documents, incremental_learning_pipeline
def create_temp_file(data):
temp_file = tempfile.NamedTemporaryFile(delete=False, mode='w', encoding='utf-8')
temp_file.writelines(data)
temp_file.close()
return temp_file.name
def test_stream_... | [
{
"docstring": "Generator function that yields chunks of text documents from a file.\n\nArgs:\n- file_path: str : Path to the file containing the text documents.\n- chunk_size: int : Number of documents to yield in each chunk.\n\nYields:\n- List[str]: A list of text documents.",
"function_declaration": "def... | [
1,
0,
0,
0,
0,
1,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\n\ndef stream_... | trial_gpt4o_7 | {
"original_instruction": "### Incremental Learning Pipeline with Out-of-Core Data\n\n**Objective:** Build an incremental learning pipeline using scikit-learn to classify text data that is too large to fit into memory all at once.\n\n**Description:**\nYou are given a large dataset of text documents categorized into d... | 0.554018 | Docs: Scikit_37654 | C | [
"stream_documents",
"incremental_learning_pipeline"
] | 2 | [
[
"incremental_learning_pipeline",
"stream_documents"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sklearn"
] | false | 6afdacf3dadf68476ce74ed7b8bd3c38815716f7 | 8267d539874df24c0bd5688f04d2e8cab70426e6 | |||
v1.0 | complete | Docs | Docs: Python310_39043_C | import turtle
def create_custom_animation():
""" Create a custom animation using the turtle module.
- Create a TurtleScreen with a white background.
- Initialize three turtles with different shapes and colors.
- Turtle 1 (Shape: "turtle", Color: "red"): Moves in a circular path with a radius of 100 pix... | import turtle
import threading
def move_in_circle(t, radius=100, steps=120):
t.pendown()
for _ in range(steps):
t.circle(radius, extent=360/steps)
if _ == steps // 2:
t.penup()
t.pencolor("darkred")
t.pendown()
def move_in_square(t, side=150):
t.pendown(... | import pytest
import turtle
from solution import create_custom_animation
def test_create_custom_animation():
# Actual unit testing for graphical applications like turtle is complex.
# Since turtle requires GUI, automatic testing isn't feasible.
# This test is a dummy and would normally require an environm... | [
{
"docstring": null,
"function_declaration": "def move_in_circle(t, radius=100, steps=120):",
"function_name": "move_in_circle",
"parameter_list": "(t, radius=100, steps=120)"
},
{
"docstring": null,
"function_declaration": "def move_in_square(t, side=150):",
"function_name": "move_i... | [
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 turtle\nimport threading\n\ndef move_in_circle(turtle_obj, radius, pen_colors):\n turtle_obj.penup()\n turtle_obj.goto(radius, 0)\n turtle_obj.pendown()... | trial_gpt4o_2 | {
"original_instruction": "**Question: Create a Custom Animation Using the Turtle Module**\n\n**Objective:**\nYou are required to demonstrate your understanding of the Python turtle graphics module by creating an advanced animation. The animation will feature multiple turtles that perform synchronized and unsynchroni... | 0.6922 | Docs: Python310_39043 | C | [
"move_in_circle",
"move_in_square",
"move_in_zigzag",
"synchronize_movement",
"stop_turtles",
"create_custom_animation"
] | 6 | [
[
"create_custom_animation",
"stop_turtles"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 00290d131e4b295471a05eeab25f8f04ae8f4ce2 | 7ea6925dfb7bb2201b43325a3e401c76056021b6 | |||
v1.0 | complete | Docs | Docs: Scikit_38957_C | from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Example preloaded data
dataset = [
{"review": "I loved ... | from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Example preloaded data
dataset = [
{"review": "I loved ... | from solution import load_data, build_pipeline, train_and_evaluate
def test_load_data():
X_train, X_test, y_train, y_test = load_data()
assert len(X_train) > 0
assert len(X_test) > 0
assert len(y_train) > 0
assert len(y_test) > 0
def test_build_pipeline():
pipeline = build_pipeline()
asser... | [
{
"docstring": null,
"function_declaration": "def load_data():",
"function_name": "load_data",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def build_pipeline():",
"function_name": "build_pipeline",
"parameter_list": "()"
},
{
"docstring": null,... | [
0,
0,
1,
1,
1,
1,
1,
1,
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 sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.pipeline ... | trial_gpt4o_8 | {
"original_instruction": "### Feature Extraction and Classification Using Scikit-Learn\n\nYou are provided with a dataset of textual movie reviews and their associated ratings (positive or negative). Your task is to build a machine learning pipeline that preprocesses the text data, extracts relevant features using s... | 0.636925 | Docs: Scikit_38957 | C | [
"load_data",
"build_pipeline",
"train_and_evaluate"
] | 3 | [
[
"train_and_evaluate",
"build_pipeline"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sklearn"
] | false | 74ffc6182ba9de5609fe968189d3cbf801665998 | 0591967505e442f38e6b376fe77a7ec7252e68bc | |||
v1.0 | complete | Docs | Docs: Python310_39171_C | import asyncio
async def fetch_data(id, delay):
"""
Simulates fetching data by sleeping for a specified delay.
"""
await asyncio.sleep(delay)
return f"data_{id}"
async def process_data(data):
"""
Simulates processing of fetched data by converting it to uppercase.
"""
await asyncio.... | import asyncio
async def fetch_data(id, delay):
"""
Simulates fetching data by sleeping for a specified delay.
"""
await asyncio.sleep(delay)
return f"data_{id}"
async def process_data(data):
"""
Simulates processing of fetched data by converting it to uppercase.
"""
await asyncio.... | from solution import fetch_data, process_data, cancellable_task, fetch_and_process_data, main
import asyncio
def test_fetch_data():
result = asyncio.run(fetch_data(1, 1))
assert result == "data_1"
def test_process_data():
result = asyncio.run(process_data("data_1"))
assert result == "DATA_1"
def test... | [] | [
1,
1,
1,
1,
0,
0,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def fetch_data(id, delay):\n await asyncio.sleep(delay)\n return f\"data_{id}\"\n\nasync def process_data(data):\n await asyncio.sleep(... | trial_gpt4o_3 | {
"original_instruction": "**Objective:**\nDesign an asyncio-based program that demonstrates the following features:\n- Declaring coroutines and tasks.\n- Running tasks concurrently.\n- Handling task cancellations and timeouts.\n- Using thread integration for IO-bound operations.\n\n**Question:**\nYou are required to... | 0.616113 | Docs: Python310_39171 | C | [
"fetch_data",
"process_data",
"cancellable_task",
"fetch_and_process_data",
"main"
] | 5 | [
[
"fetch_and_process_data",
"cancellable_task"
],
[
"fetch_and_process_data",
"fetch_data"
],
[
"fetch_and_process_data",
"process_data"
]
] | 3 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | dad06ad4d63328c8138d9c8f7e12e2484b65a315 | eb64b3fc08ea257ecfdb62ce07647a6b909629f0 | |||
v1.0 | complete | Docs | Docs: Python310_38910_C | import pdb
import cProfile
import timeit
import tracemalloc
# Original inefficient Fibonacci function
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
# 1. Using pdb to debug
def debug_fib():
"""
Locate and analyze the performance issue in the `fib` function using pdb.
Example:
... | import pdb
import cProfile
import timeit
import tracemalloc
# Original inefficient Fibonacci function
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
# 1. Using pdb to debug
def debug_fib():
pdb.set_trace()
fib(10) # Example call to initialize debugging (use proper pdb commands to ... | from solution import fib, optimized_fib
def test_original_fib_base_cases():
assert fib(0) == 0
assert fib(1) == 1
def test_original_fib_small_n_values():
assert fib(2) == 1
assert fib(3) == 2
assert fib(4) == 3
assert fib(5) == 5
def test_optimized_fib_base_cases():
assert optimized_fib(0... | [
{
"docstring": null,
"function_declaration": "def fib(n):",
"function_name": "fib",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def debug_fib():",
"function_name": "debug_fib",
"parameter_list": "()"
},
{
"docstring": null,
"function_decla... | [
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 pdb\nimport cProfile\nimport timeit\nimport tracemalloc\n\n# Original inefficient Fibonacci function\ndef fib(n):\n if n <= 1:\n return n\n return f... | trial_gpt4o_1 | {
"original_instruction": "**Coding Assessment Question:**\n\n### Debugging and Profiling in Python\n\n#### Background\nAs a Python developer, you need to ensure that your code runs efficiently without errors and uses resources optimally. To achieve this, Python provides various libraries for debugging, profiling, mo... | 0.635928 | Docs: Python310_38910 | C | [
"fib",
"debug_fib",
"profile_fib",
"optimized_fib",
"fib_time",
"trace_memory"
] | 6 | [
[
"debug_fib",
"fib"
],
[
"profile_fib",
"fib"
],
[
"trace_memory",
"optimized_fib"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | fb601828a0383a455dada509082cab8b973cf928 | 35e3ad23ed8cff70e0b13d6f980d6696055f64a9 | |||
v1.0 | complete | Docs | Docs: Pytorch_38911_C | import torch
from torch.futures import Future, collect_all
def matrix_multiplication(matrix1, matrix2, device):
"""
Performs matrix multiplication on the specified device.
Args:
matrix1 (torch.Tensor): First matrix.
matrix2 (torch.Tensor): Second matrix.
device (torch.device): Device to ru... | import torch
from torch.futures import Future, collect_all
def matrix_multiplication(matrix1, matrix2, device):
"""
Performs matrix multiplication on the specified device.
Args:
matrix1 (torch.Tensor): First matrix.
matrix2 (torch.Tensor): Second matrix.
device (torch.device): Device to ru... | import torch
from solution import matrix_multiplication, parallel_matrix_multiplication
def test_matrix_multiplication_cpu():
matrix1 = torch.randn(3, 3)
matrix2 = torch.randn(3, 3)
device = torch.device('cpu')
result = matrix_multiplication(matrix1, matrix2, device)
expected_result = torch.matmul(... | [
{
"docstring": "Performs matrix multiplication on the specified device.\n\nArgs:\nmatrix1 (torch.Tensor): First matrix.\nmatrix2 (torch.Tensor): Second matrix.\ndevice (torch.device): Device to run the computation on.\n\nReturns:\ntorch.Tensor: Resultant matrix after multiplication.",
"function_declaration"... | [
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\nfrom torch.futures import Future, collect_all\n\ndef matrix_multiplication(matrix1, matrix2, device):\n \"\"\"\n Performs matrix multiplication on a... | trial_gpt4o_8 | {
"original_instruction": "### PyTorch Coding Assessment Question: Asynchronous Computation with `torch.futures`\n\n#### Objective\nIn this assessment, you will demonstrate your understanding of asynchronous execution in PyTorch using `torch.futures`. You are required to write code that creates `Future` objects, perf... | 0.505308 | Docs: Pytorch_38911 | C | [
"matrix_multiplication",
"parallel_matrix_multiplication"
] | 2 | [
[
"parallel_matrix_multiplication",
"matrix_multiplication"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 43ea5bb98549d0b36d3b2656a67127cca4452985 | 197580e938cfb34c3123f4c581312834ee914be6 | |||
v1.0 | complete | Docs | Docs: Python310_39048_C | import signal
class TimeoutException(Exception):
pass
def handler(signum, frame):
raise TimeoutException("Function execution exceeded timeout")
def timed_execution(timeout, task):
"""Execute a task with a time limit.
This function runs a given task with a specified timeout. If the task
does... | import signal
class TimeoutException(Exception):
pass
def handler(signum, frame):
raise TimeoutException("Function execution exceeded timeout")
def timed_execution(timeout, task):
# Set the signal handler and the alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout)
try:
... | import pytest
import time
from solution import timed_execution, TimeoutException
def sample_task_short():
time.sleep(1)
return "Task Completed - Short"
def sample_task_long():
time.sleep(5)
return "Task Completed - Long"
def sample_task_instant():
return "Task Completed - Instant"
def test_timed... | [] | [
0,
1,
1,
0,
0,
0,
0,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\n\nclass TimeoutException(Exception):\n pass\n\ndef handler(signum, frame):\n raise TimeoutException(\"Function execution exceeded timeout\")\n\ndef... | trial_gpt4o_9 | {
"original_instruction": "In this problem, you are tasked with handling multiple signals in Python to safely manage a time-bound operation. You must use signal handling to ensure that a specific task does not run indefinitely and can be interrupted gracefully. \n\n### Specifications\n\n**Function**: `timed_execution... | 0.60788 | Docs: Python310_39048 | C | [
"handler",
"timed_execution"
] | 2 | [
[
"timed_execution",
"handler"
]
] | 1 | [] | false | [
"TimeoutException"
] | true | pytest | true | [] | true | 971c62ba408e84fe26337a992b20e58d782783e6 | b833616d553ebbe2ae5afaf314c8a9897557a3de | |||
v1.0 | complete | Docs | Docs: Python310_39254_C | import getopt
import sys
def usage():
""" Prints the usage information of the script """
print("Usage: script.py -u <username> -p <password> [-s] [-h]")
print(" or: script.py --username <username> --password <password> [--secure] [--help]")
def parse_args(argv):
""" Parse and validate the command li... | import getopt
import sys
def usage():
print("Usage: script.py -u <username> -p <password> [-s] [-h]")
print(" or: script.py --username <username> --password <password> [--secure] [--help]")
def parse_args(argv):
username = None
password = None
secure = False
try:
opts, args = getopt... | import sys
import pytest
from solution import parse_args, usage
def test_help_message(monkeypatch, capsys):
test_args = ['script.py', '-h']
monkeypatch.setattr(sys, 'argv', test_args)
with pytest.raises(SystemExit):
parse_args(sys.argv[1:])
captured = capsys.readouterr()
assert "Usage:" in... | [
{
"docstring": null,
"function_declaration": "def usage():",
"function_name": "usage",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def parse_args(argv):",
"function_name": "parse_args",
"parameter_list": "(argv)"
}
] | [
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 getopt\nimport sys\n\ndef usage():\n \"\"\"\n Print the usage information for the script.\n \"\"\"\n print(\"Usage: script.py -u <username> -p <passw... | trial_gpt4o_1 | {
"original_instruction": "#### Objective:\nCreate a Python script using the `getopt` module that will parse and validate the following command line arguments and options:\n\n- Short options: `-u` (username), `-p` (password), `-s` (secure flag), `-h` (help)\n- Long options: `--username`, `--password`, `--secure`, `--... | 0.49457 | Docs: Python310_39254 | C | [
"usage",
"parse_args"
] | 2 | [
[
"parse_args",
"usage"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2e6f66cc45785067fd2a01d043fb281f67567dc3 | 61429544f106f9b72cac57a523688212e25e91cb | |||
v1.0 | complete | Docs | Docs: Python310_38950_C | def is_list(obj):
"""
Returns True if the given object is a list, False otherwise.
>>> is_list([1, 2, 3])
True
>>> is_list("hello")
False
"""
def create_list(length):
"""
Returns a new list of the specified length, filled with None.
>>> create_list(3)
[None, None, None]
... | def is_list(obj):
"""
Returns True if the given object is a list, False otherwise.
"""
return isinstance(obj, list)
def create_list(length):
"""
Returns a new list of the specified length, filled with None.
"""
return [None] * length
def get_length(lst):
"""
Returns the length ... | def test_is_list():
assert is_list([1, 2, 3]) == True
assert is_list("hello") == False
assert is_list((1, 2, 3)) == False
assert is_list(None) == False
def test_create_list():
assert create_list(3) == [None, None, None]
assert create_list(0) == []
def test_get_length():
assert get_length([... | [
{
"docstring": "Returns True if the given object is a list, False otherwise.",
"function_declaration": "def is_list(obj):",
"function_name": "is_list",
"parameter_list": "(obj)"
},
{
"docstring": "Returns a new list of the specified length, filled with None.",
"function_declaration": "de... | [
0,
0,
1,
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": "def is_list(obj):\n \"\"\"\n Checks if the object is a list.\n \"\"\"\n return isinstance(obj, list)\n\ndef create_list(length):\n \"\"\"\n Creates a ... | trial_gpt4o_4 | {
"original_instruction": "### Python List Operations Module\n\nYour task is to implement a Python module that provides functionalities similar to those described in the provided documentation for Python list objects using C-API. However, you must implement these functionalities in Python without using the list's bui... | 0.602001 | Docs: Python310_38950 | C | [
"is_list",
"create_list",
"get_length",
"get_item",
"set_item",
"insert_item",
"append_item",
"sort_list",
"reverse_list",
"to_tuple"
] | 10 | [
[
"get_item",
"get_length"
],
[
"insert_item",
"get_length"
],
[
"reverse_list",
"get_length"
],
[
"set_item",
"get_length"
],
[
"sort_list",
"get_length"
]
] | 5 | [] | false | [] | false | pytest | false | [] | true | c37e4b1b9d1b6ccd765ab989255cf6b7d0a17026 | 9b7c35f8d48b54809bfb664e4d87099fcca8e014 | |||
v1.0 | complete | Docs | Docs: Scikit_39349_C | import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
from sklearn.metrics import make_scorer
from sklearn.model_selection import cross_val_score
def custom_mape(y_true, y_pred):
"""
Custom Mean Absolute Percentage Error (MAPE) function.
... | import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
from sklearn.metrics import make_scorer
from sklearn.model_selection import cross_val_score
def custom_mape(y_true, y_pred):
"""
Custom Mean Absolute Percentage Error (MAPE) function.
... | import numpy as np
from solution import custom_mape, evaluate_model_with_mape
def test_custom_mape():
y_true = np.array([10, 20, 30, 40, 50])
y_pred = np.array([12, 18, 29, 41, 55])
expected_mape = np.mean(np.abs((y_true - y_pred) / y_true)) * 100
assert custom_mape(y_true, y_pred) == expected_mape
de... | [
{
"docstring": "Custom Mean Absolute Percentage Error (MAPE) function.\n\nParameters:\ny_true (array-like): True target values.\ny_pred (array-like): Predicted target values.\n\nReturns:\nfloat: MAPE value.",
"function_declaration": "def custom_mape(y_true, y_pred):",
"function_name": "custom_mape",
... | [
0,
0,
0,
0,
1,
1,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sklearn.datasets import fetch_california_housing\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import make_scorer\nfrom sklearn.model_se... | trial_gpt4o_8 | {
"original_instruction": "### Question:\n\n**Objective:** Implement a custom scoring function and use it to evaluate the performance of a machine learning model using scikit-learn.\n\n**Problem Statement:**\n\nYou are provided with a dataset and asked to perform a regression task. The goal is to predict the output v... | 0.673153 | Docs: Scikit_39349 | C | [
"custom_mape",
"evaluate_model_with_mape"
] | 2 | [
[
"evaluate_model_with_mape",
"custom_mape"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | c3348ece1bba795e6ac6d33b598f5503d5383e8b | d2f0c837447e4d82a100475462a1659328786b71 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.