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: Scikit_15516_C | import numpy as np
from sklearn.model_selection import cross_validate
from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score
def custom_weighted_scoring(y_true, y_pred):
"""
Custom scoring function that weighs false negatives more heavily than false positives.
Parameters:
... | import numpy as np
from sklearn.model_selection import cross_validate
from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score
def custom_weighted_scoring(y_true, y_pred):
"""
Custom scoring function that weighs false negatives more heavily than false positives.
Parameters:
... | import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_classification
from solution import evaluate_models
def test_evaluate_models():
X, y = make_classification(n_samples=100, n_features=20, random_state=42)
model1 = DecisionTreeClassifier(random_state=42)
... | [
{
"docstring": "Custom scoring function that weighs false negatives more heavily than false positives.\n\nParameters:\n- y_true (numpy array): True labels\n- y_pred (numpy array): Predicted labels\n\nReturns:\n- score: Weighted accuracy score",
"function_declaration": "def custom_weighted_scoring(y_true, y_... | [
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 numpy as np\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score\n\ndef cu... | trial_gpt4o_1 | {
"original_instruction": "### Question: Model Evaluation with Custom Scoring Metrics\n\nYou have just trained several machine learning models on a classification dataset. To ensure the reliability of your models, you need to evaluate their performance using multiple scoring metrics and compare them. Additionally, fo... | 0.641698 | Docs: Scikit_15516 | C | [
"custom_weighted_scoring",
"evaluate_models"
] | 2 | [
[
"evaluate_models",
"custom_weighted_scoring"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 5d0f50c7353fbee491d6ab222f94a48a242f09c8 | c70595ca1832b43fea85adede3ac89cb43f94a17 | |||
v1.0 | complete | Docs | Docs: Python310_15173_C | import asyncio
from typing import List
async def perform_async_operations(input_files: List[str], output_file: str) -> None:
"""
Perform asynchronous I/O operations and handle specific asyncio exceptions gracefully.
Args:
input_files (List[str]): A list of file paths from which data needs to be re... | import asyncio
from typing import List
async def read_file(path: str) -> str:
try:
reader = await asyncio.open_file(path, mode='r')
data = await reader.read()
await reader.close()
return data
except asyncio.TimeoutError:
print(f'Timeout error reading {path}')
except ... | import pytest
import asyncio
from tempfile import NamedTemporaryFile
from unittest.mock import patch
from solution import perform_async_operations
@pytest.mark.asyncio
async def test_perform_async_operations():
with NamedTemporaryFile(delete=False) as temp_input1, \
NamedTemporaryFile(delete=False) as tem... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List\n\nasync def perform_async_operations(input_files: List[str], output_file: str) -> None:\n try:\n async with aiofiles.... | trial_gpt4o_1 | {
"original_instruction": "**Objective:**\n\nTo assess your understanding of the `asyncio` exceptions in Python 3.10, you will write a function that performs asynchronous I/O operations and handles specific `asyncio` exceptions gracefully.\n\n**Problem Statement:**\n\nImplement an asynchronous function `perform_async... | 0.524675 | Docs: Python310_15173 | C | [
"read_file",
"write_file",
"perform_async_operations"
] | 3 | [
[
"perform_async_operations",
"read_file"
],
[
"perform_async_operations",
"write_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4b99be4e045a577bb74c62a087b148abcceef7c6 | cad1acfcedfe1ee00624f22899e1c4d6da74d3ff | |||
v1.0 | complete | Docs | Docs: Python310_15199_C | import base64
def encode_data(data: bytes, encoding: str) -> bytes:
""" Encode the given binary data using the specified base encoding.
Args:
data (bytes): The binary data to be encoded.
encoding (str): The encoding type to be used. Possible values are "base16", "base32", "base64", or "base85".
... | import base64
def encode_data(data: bytes, encoding: str) -> bytes:
if encoding == "base16":
return base64.b16encode(data)
elif encoding == "base32":
return base64.b32encode(data)
elif encoding == "base64":
return base64.b64encode(data)
elif encoding == "base85":
return ... | import pytest
from solution import encode_data, decode_data, compare_encodings
def test_encode_decode_base16():
original_data = b"test_data"
encoding = "base16"
encoded_data = encode_data(original_data, encoding)
decoded_data = decode_data(encoded_data, encoding)
assert original_data == decoded_dat... | [
{
"docstring": null,
"function_declaration": "def encode_data(data, encoding):",
"function_name": "encode_data",
"parameter_list": "(data, encoding)"
},
{
"docstring": null,
"function_declaration": "def decode_data(encoded_data, encoding):",
"function_name": "decode_data",
"param... | [
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 base64\n\ndef encode_data(data: bytes, encoding: str) -> bytes:\n \"\"\"\n Encodes the given data with the specified encoding scheme.\n \n :param dat... | trial_gpt4o_5 | {
"original_instruction": "### Question: Data Encoding and Decoding with Base64 Module\n\nYou are tasked to create a Python program that can encode and decode given binary data using different base encoding schemes (Base16, Base32, Base64, and Base85). The program should handle exceptions gracefully and print meaning... | 0.743329 | Docs: Python310_15199 | C | [
"encode_data",
"decode_data",
"compare_encodings"
] | 3 | [
[
"compare_encodings",
"decode_data"
],
[
"compare_encodings",
"encode_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 14474f5190c035891fffc4823ddb4c5703bd01f2 | 0a972733e02b9a6d82468f8c1e22cb819976fb85 | |||
v1.0 | complete | Docs | Docs: Python310_15784_C | import asyncio
import platform
async def cross_platform_event_loop():
""" An asyncio-based function to handle platform-specific event loop configurations and perform tasks accordingly.
On Windows:
- Uses ProactorEventLoop
- Executes a subprocess and captures its output
On macOS:
- Use... | import asyncio
import platform
import subprocess
async def windows_subprocess_example():
process = await asyncio.create_subprocess_shell(
'ping google.com',
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if... | import asyncio
import platform
import pytest
from solution import cross_platform_event_loop
@pytest.mark.skipif(platform.system() != 'Windows', reason="Test on Windows only")
def test_cross_platform_event_loop_windows():
asyncio.run(cross_platform_event_loop())
# Since this function involves actual subprocess ... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport platform\nimport subprocess\n\nasync def windows_subprocess_example():\n process = await asyncio.create_subprocess_shell(\n 'ping googl... | trial_gpt4o_0 | {
"original_instruction": "### Asyncio Cross-Platform Event Loop Implementation\n\n**Background:**\n\nYou are tasked with designing an asyncio-based application that works consistently across multiple platforms, including Windows and macOS. Your solution should take into account the platform-specific limitations as d... | 0.368508 | Docs: Python310_15784 | C | [
"windows_subprocess_example",
"macos_server_client_example",
"cross_platform_event_loop"
] | 3 | [
[
"cross_platform_event_loop",
"macos_server_client_example"
],
[
"cross_platform_event_loop",
"windows_subprocess_example"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 22d0df384f4f90f8d48e44a49ab5eda46146a046 | dc8e6bb9d3680e99fd37d36a41bf68646d472dfd | |||
v1.0 | complete | Docs | Docs: Python310_14720_C | from typing import List
def convert_date_times(date_time_strings: List[str], date_format: str) -> List[str]:
""" Converts a list of date-time strings into a standardized format.
>>> convert_date_times(["2023-10-01 13:45:30", "01-10-2023 14:50:15", "10/01/2023 01:55 PM"], "%Y-%m-%d %H:%M:%S")
['2023-10-01 1... | from typing import List
import time
def convert_date_times(date_time_strings: List[str], date_format: str) -> List[str]:
"""
Converts a list of date-time strings into a standardized format.
:param date_time_strings: List of strings representing date-times in various formats.
:param date_format: The de... | import pytest
from solution import convert_date_times, measure_conversion_time
def test_convert_date_times_standard_format():
date_time_strings = ["2023-10-01 13:45:30", "01-10-2023 14:50:15", "10/01/2023 01:55 PM"]
expected_output = ["2023-10-01 13:45:30", "2023-10-01 14:50:15", "2023-10-01 13:55:00"]
out... | [
{
"docstring": "Converts a list of date-time strings into a standardized format.\n\n:param date_time_strings: List of strings representing date-times in various formats.\n:param date_format: The desired output format for the date-times.\n:return: A list of strings where each string represents a date-time conver... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport time\n\ndef convert_date_times(date_time_strings: List[str], date_format: str) -> List[str]:\n \"\"\"\n Converts a list of date-ti... | trial_gpt4o_2 | {
"original_instruction": "**Problem Statement:**\n\nThe Python `time` module offers various functions that assist in manipulating and converting times. Your task is to write a utility that takes a list of strings representing date-times in different formats and returns a list of date-times converted into a standardi... | 0.685961 | Docs: Python310_14720 | C | [
"convert_date_times",
"measure_conversion_time"
] | 2 | [
[
"measure_conversion_time",
"convert_date_times"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 865efe3c418041e1de7108076997a1535b926d95 | e101aecb6e97b5d2134eaa785d2fcdd0a19c5aa5 | |||
v1.0 | complete | Docs | Docs: Python310_15390_C | import asyncio
async def handle_client(reader, writer):
"""Handle connection with client, read a message and send a response.
Args:
reader: StreamReader object to read data from the client.
writer: StreamWriter object to write data to the client.
"""
data = await reader.read(100)
m... | import asyncio
# Server Code
async def handle_client(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
log_message = f"Received {message!r} from {addr!r}"
print(log_message)
response = f"Received {message!r}"
writer.write(respo... | import pytest
import asyncio
from solution import handle_client, start_server, send_message
@pytest.mark.asyncio
async def test_server_client_interaction(capfd):
# Start server
server_task = asyncio.create_task(start_server())
# Allow server some time to start up
await asyncio.sleep(1)
# ... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import asyncio\n\n# Server Code\nasync def handle_client(reader, writer):\n data = await reader.read(100)\n message = data.decode()\n ... | trial_gpt4o_3 | {
"original_instruction": "### Asynchronous Network Communication with Python's `asyncio` Streams\n\n#### Objective\nWrite a Python program using the `asyncio` streams module to implement a custom server-client architecture. You need to demonstrate skills in network connection management, asynchronous data transmissi... | 0.652204 | Docs: Python310_15390 | C | [
"handle_client",
"start_server",
"send_message",
"main"
] | 4 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5e18903713155458f1c4c2cc3619657c01f2e7b6 | 845cabbd46ee1c6e662e65b650f29bc9a15256f4 | |||
v1.0 | complete | Docs | Docs: Python310_15033_C | import asyncio
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
async def io_bound_task(id):
"""Simulate an I/O-bound task."""
await asyncio.sleep(2)
logger.debug(f"Worker {id} completed I/O-bound task.")
def cpu_bound_task(id):
"""Simulate a CPU-bound task... | import asyncio
import logging
from concurrent.futures import ThreadPoolExecutor
import time
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
async def io_bound_task(id):
await asyncio.sleep(2) # Simulating an I/O-bound task, e.g., reading from a file
logger.debug(f"Worker {id} co... | import asyncio
from solution import main
def test_async_program_execution():
# This test will just run the main function and ensure it completes without errors.
try:
asyncio.run(main())
except Exception as e:
pytest.fail(f"Worker execution raised an unexpected exception: {e}")
# Note: It i... | [
{
"docstring": null,
"function_declaration": "def cpu_bound_task(id):",
"function_name": "cpu_bound_task",
"parameter_list": "(id)"
}
] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport logging\nfrom concurrent.futures import ThreadPoolExecutor\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.get... | trial_gpt4o_1 | {
"original_instruction": "### Asynchronous Programming with asyncio\n\n#### Problem Statement\n\nYou are tasked with implementing an asynchronous program that simulates tasks performed by a group of workers. Each worker performs several asynchronous operations, some of which may involve blocking I/O and CPU-bound ta... | 0.514115 | Docs: Python310_15033 | C | [
"io_bound_task",
"cpu_bound_task",
"worker",
"main"
] | 4 | [
[
"worker",
"cpu_bound_task"
],
[
"worker",
"io_bound_task"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0d0915a6a6bd32ba429b1f47f06b5aa17c85a1c3 | 0eaa49efdb29757726667b75d4ba6ed38af428da | |||
v1.0 | complete | Docs | Docs: Python310_13788_C | import wave
import struct
def read_wav_file(file_path):
"""Reads a WAV file and returns relevant audio data as a dictionary.
Args:
file_path (str): Path to the WAV file to be read.
Returns:
dict: A dictionary containing audio data including number of channels, sample width,
fr... | import wave
import struct
def read_wav_file(file_path):
with wave.open(file_path, 'rb') as wav:
wav_data = {
"nchannels": wav.getnchannels(),
"sampwidth": wav.getsampwidth(),
"framerate": wav.getframerate(),
"nframes": wav.getnframes(),
"comptype"... | import pytest
import tempfile
import struct
from solution import read_wav_file, write_wav_file, modify_wav_file
def create_test_wav_file(file_path):
with wave.open(file_path, 'wb') as wav:
wav.setnchannels(1)
wav.setsampwidth(2)
wav.setframerate(44100)
wav.setnframes(4)
wav.... | [
{
"docstring": null,
"function_declaration": "def read_wav_file(file_path):",
"function_name": "read_wav_file",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def write_wav_file(file_path, wav_data):",
"function_name": "write_wav_file",
"paramete... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import wave\nimport struct\n\ndef read_wav_file(file_path):\n with wave.open(file_path, 'rb') as wav:\n wav_data = {\n \"nchannels\": wav.getnchann... | trial_gpt4o_0 | {
"original_instruction": "### WAV File Processing and Modification\n\nIn this assessment, you will demonstrate your understanding of the \"wave\" module by writing functions that read a WAV file, process its audio data, and create a new modified WAV file.\n\n#### Requirements\n\n1. Implement a function `read_wav_fil... | 0.544114 | Docs: Python310_13788 | C | [
"read_wav_file",
"write_wav_file",
"modify_wav_file"
] | 3 | [
[
"modify_wav_file",
"read_wav_file"
],
[
"modify_wav_file",
"write_wav_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 88e027af227b6d48c6b03b500b665aa3c8190572 | 7b9f77ab1d5fb105769c611ee856889d6d8ffd2f | |||
v1.0 | complete | Docs | Docs: Python310_15399_C | import asyncio
async def handle_client(reader, writer):
"""
Handles communication with the client. Reads a message from the client,
echoes it back, and then closes the connection.
"""
# Your implementation here
pass
async def start_server():
"""
Starts the TCP echo server on localhost:... | import asyncio
async def handle_client(reader, writer):
"""
Handles communication with the client. Reads a message from the client,
echoes it back, and then closes the connection.
"""
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f... | import asyncio
import pytest
from solution import handle_client, start_server, tcp_echo_client
@pytest.mark.asyncio
async def test_handle_client():
reader, writer = await asyncio.open_connection('localhost', 8888)
message = "test_message"
# Simulate client sending message
writer.write(message.encode()... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"Connection from {addr}\")\n\n while True:\n ... | trial_gpt4o_2 | {
"original_instruction": "**Objective:**\nImplement a TCP echo server and client using the asyncio streams functionality provided in Python 3.10. This exercise will test your understanding of asynchronous programming, handling network connections, and using the StreamReader and StreamWriter classes.\n\n**Task 1: TCP... | 0.66929 | Docs: Python310_15399 | C | [
"handle_client",
"start_server",
"tcp_echo_client"
] | 3 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e72bae4c620f89350881c64987b6a5aa9f9fc311 | 77f93bf2738c041f56876f277031125a1ea1a990 | |||
v1.0 | complete | Docs | Docs: Python310_14203_C | def parse_python_code(code: str) -> dict:
"""
Parses a string representing a Python assignment or function definition
and returns a structured representation of the components.
>>> parse_python_code("x = 5 + 3") == {
... "type": "assignment",
... "target": "x",
... "value": {
... | import ast
def parse_python_code(code: str) -> dict:
"""
Parses a string representing a Python assignment or function definition
and returns a structured representation of the components.
"""
# Parse the code into an AST
tree = ast.parse(code)
# Handling assignment
if isinstance(tr... | import pytest
from solution import parse_python_code
def test_parse_assignment():
code = "x = 5 + 3"
expected_output = {
"type": "assignment",
"target": "x",
"value": {
"type": "expression",
"elements": ["5", "Add", "3"]
}
}
assert parse_python_co... | [
{
"docstring": "Parses a string representing a Python assignment or function definition\nand returns a structured representation of the components.",
"function_declaration": "def parse_python_code(code):",
"function_name": "parse_python_code",
"parameter_list": "(code)"
},
{
"docstring": nul... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef parse_python_code(code: str) -> dict:\n # Check if the code is an assignment statement\n assignment_pattern = r'^(\\w+)\\s*=\\s*(.+)$'\n match... | trial_gpt4o_2 | {
"original_instruction": "## Python Grammar-Based Parsing Task\n\n### Objective:\nYour task is to implement a Python function to parse a subset of Python expressions and statements using the provided grammar rules. Specifically, you will be implementing a function that evaluates Python assignment statements and func... | 0.594815 | Docs: Python310_14203 | C | [
"parse_python_code",
"parse_expression",
"parse_statement"
] | 3 | [
[
"parse_python_code",
"parse_expression"
],
[
"parse_python_code",
"parse_statement"
],
[
"parse_statement",
"parse_expression"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | effb44d3d2ed8432c55cc407a684e07e35f7116c | fe2271062709cbde89bbdfc8fd1e4fef99bd8b77 | |||
v1.0 | complete | Docs | Docs: Python310_15404_C | import heapq
def add_task(task_list, task, priority, entry_finder):
"""
Adds a new task with a given priority to the task list.
"""
pass
def remove_task(task_list, task, entry_finder, removed_marker):
"""
Removes a specific task from the task list.
Marks the entry as removed.
"""
p... | import heapq
def add_task(task_list, task, priority, entry_finder):
"""
Adds a new task with a given priority to the task list.
"""
if task in entry_finder:
remove_task(task_list, task, entry_finder, '<removed-task>')
entry = [priority, task]
entry_finder[task] = entry
heapq.heappus... | import pytest
from solution import add_task, remove_task, pop_task, get_n_highest_priority_tasks
def test_add_task():
task_list = []
entry_finder = {}
removed_marker = '<removed-task>'
add_task(task_list, 'task1', 2, entry_finder)
assert 'task1' in entry_finder and entry_finder['task1'][0] == ... | [
{
"docstring": "Adds a new task with a given priority to the task list.",
"function_declaration": "def add_task(task_list, task, priority, entry_finder):",
"function_name": "add_task",
"parameter_list": "(task_list, task, priority, entry_finder)"
},
{
"docstring": "Removes a specific task fr... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef add_task(task_list, task, priority, entry_finder):\n \"\"\"\n Adds a new task with the given priority to the task list.\n If the task alrea... | trial_gpt4o_2 | {
"original_instruction": "### Problem:\n\nYou are tasked with implementing a task scheduler that works based on priorities. The scheduler should be able to handle tasks with various priorities, allowing you to efficiently add tasks, remove tasks, and fetch the highest priority task.\n\nYou need to implement the foll... | 0.580467 | Docs: Python310_15404 | C | [
"add_task",
"remove_task",
"pop_task",
"get_n_highest_priority_tasks"
] | 4 | [
[
"add_task",
"remove_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6a50ae36a385c1c7231822ed51b9196a2cb3c4cd | 13c03dfc3ae2527f31169f63e75adf0e48946345 | |||
v1.0 | complete | Docs | Docs: Python310_15466_C | import inspect
def introspect_function_calls() -> dict:
"""
This function returns a dictionary containing detailed information about the currently executing function.
The dictionary contains the following keys:
- "function_name": The name of the currently executing function.
- "function_description... | import inspect
def introspect_function_calls() -> dict:
"""
This function returns a dictionary containing detailed information about the currently executing function.
"""
# Get the current frame
current_frame = inspect.currentframe()
if current_frame is None:
return {}
# G... | def test_introspect_function_calls_example_function():
info = example_function()
assert info["function_name"] == "example_function"
assert info["globals"] is not None
assert info["locals"] is not None
assert "a" in info["locals"]
assert "b" in info["locals"]
assert info["current_line"] > 0
... | [
{
"docstring": "This function returns a dictionary containing detailed information about the currently executing function.",
"function_declaration": "def introspect_function_calls():",
"function_name": "introspect_function_calls",
"parameter_list": "()"
},
{
"docstring": null,
"function_... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import inspect\n\ndef introspect_function_calls() -> dict:\n \"\"\"\n Return detailed information about the currently executing function.\n \"\"\"\n current... | trial_gpt4o_1 | {
"original_instruction": "**Question: Introspecting Function Calls**\n\nGiven the functions described in the `python310` package, your task is to implement a function `introspect_function_calls` that returns detailed information about the currently executing function. Specifically, you will make use of the following... | 0.69211 | Docs: Python310_15466 | C | [
"introspect_function_calls",
"example_function"
] | 2 | [
[
"example_function",
"introspect_function_calls"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | ec7785d439cd1f8a053e4e96469e905b0c19395b | d0663121c4a4d50e9ecb843936bf53e282da930d | |||
v1.0 | complete | Docs | Docs: Python310_15919_C | import asyncio
async def execute_after_delay(fut, delay, value):
""" Execute a Future object after a specified delay with a given value.
"""
# Implement this function
pass
async def main():
""" Main function to initiate and await the Future object.
"""
# Implement this function
pass
d... | import asyncio
async def execute_after_delay(fut, delay, value):
await asyncio.sleep(delay)
fut.set_result(value)
async def main():
loop = asyncio.get_event_loop()
fut = loop.create_future()
# Execute the delay function asynchronously
asyncio.create_task(execute_after_delay(fut, 2, "... w... | import asyncio
import pytest
from solution import execute_after_delay, main, ensure_future_example, main_with_exception_handling
@pytest.mark.asyncio
async def test_execute_after_delay():
fut = asyncio.Future()
await execute_after_delay(fut, 1, "Test Value")
assert fut.result() == "Test Value"
@pytest.mar... | [
{
"docstring": "Ensures the provided coroutine or awaitable is scheduled as a Task.\nRaises a ValueError if the provided argument is not a valid coroutine.",
"function_declaration": "def ensure_future_example(coro):",
"function_name": "ensure_future_example",
"parameter_list": "(coro)"
}
] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def execute_after_delay(fut, delay, value):\n \"\"\"\n Sleeps for `delay` seconds and sets the `value` as the result of the Future `fut`.\... | trial_gpt4o_1 | {
"original_instruction": "### Question: Advanced Asynchronous Programming with asyncio Future\n\nYou are tasked with developing a small Python program to simulate a series of asynchronous operations using the `asyncio` library's `Future` objects. This question assesses your understanding of creating, manipulating, a... | 0.589052 | Docs: Python310_15919 | C | [
"execute_after_delay",
"main",
"ensure_future_example",
"main_with_exception_handling"
] | 4 | [
[
"main_with_exception_handling",
"ensure_future_example"
],
[
"main_with_exception_handling",
"execute_after_delay"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 29f7f866f038f6b871b68fcd22eb6d5498448b2e | f8e5cc24f77cc1a147f49ac6e896e9122a2e227e | |||
v1.0 | complete | Docs | Docs: Python310_13206_C | import csv
from typing import List, Dict
def read_employee_data(filename: str) -> List[Dict[str, str]]:
"""
Reads employee data from a CSV file and returns a list of dictionaries.
Parameters:
- filename: str: The name of the CSV file to read from.
Returns:
- List[Dict[str, str]]: A list of di... | import csv
def read_employee_data(filename: str) -> list:
"""
Reads employee data from a CSV file and returns a list of dictionaries.
Parameters:
- filename: str: The name of the CSV file to read from.
Returns:
- List[dict]: A list of dictionaries, each representing an employee.
"""
w... | import os
import csv
import pytest
from solution import read_employee_data, increment_salary, average_salary_by_department
def create_csv(filename, content):
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(content)
def test_read_employee_data():
create_... | [
{
"docstring": "Reads employee data from a CSV file and returns a list of dictionaries.\n\nParameters:\n- filename: str: The name of the CSV file to read from.\n\nReturns:\n- List[dict]: A list of dictionaries, each representing an employee.",
"function_declaration": "def read_employee_data(filename):",
... | [
0,
0,
0,
1,
0,
1,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\n\ndef read_employee_data(filename):\n \"\"\"\n Reads employee data from a CSV file and returns a list of dictionaries.\n \n Parameters:\n - f... | trial_gpt4o_9 | {
"original_instruction": "### CSV File Manipulation and Analysis\n\n#### Problem Statement:\n\nYou have been provided a CSV file containing information about employees in a company. Each row in the CSV file includes the following fields:\n- `id`: Employee ID\n- `name`: Employee name\n- `department`: Department of th... | 0.688928 | Docs: Python310_13206 | C | [
"read_employee_data",
"increment_salary",
"average_salary_by_department"
] | 3 | [
[
"average_salary_by_department",
"read_employee_data"
],
[
"increment_salary",
"read_employee_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8465387e3bc0f6399577c52f5f5eff03ac5833b1 | c4a2129d48abafd034e224604cccf4c39648d730 | |||
v1.0 | complete | Docs | Docs: Python310_14737_C | ### Task: Complete the Echo Server and Client Implementation
You are required to implement a Python program that creates a simple echo server and client using the socket module. The server should be able to handle multiple clients using the `selectors` module to multiplex the I/O.
#### Server Requirements
- It shoul... | # server.py
import selectors
import socket
sel = selectors.DefaultSelector()
def accept(sock, mask):
conn, addr = sock.accept()
print('accepted', conn, 'from', addr)
conn.setblocking(False)
sel.register(conn, selectors.EVENT_READ, read)
def read(conn, mask):
data = conn.recv(1000)
if data:
... | # test_echo_server.py
import socket
import subprocess
import time
import threading
def start_server():
subprocess.run(['python', 'server.py'])
def test_echo_server():
# Start the server in a separate thread
server_thread = threading.Thread(target=start_server, daemon=True)
server_thread.start()
#... | [
{
"docstring": null,
"function_declaration": "def accept(sock, mask):",
"function_name": "accept",
"parameter_list": "(sock, mask)"
},
{
"docstring": null,
"function_declaration": "def read(conn, mask):",
"function_name": "read",
"parameter_list": "(conn, mask)"
},
{
"doc... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# server.py\nimport selectors\nimport socket\n\nsel = selectors.DefaultSelector()\n\ndef accept(sock, mask):\n conn, addr = sock.accept()\n print('accepted', conn... | trial_gpt4o_0 | {
"original_instruction": "#### Problem Statement\n\nYou are required to implement a Python program that creates a simple echo server and client using the socket module. The server should be able to handle multiple clients using the `selectors` module to multiplex the I/O.\n\n1. **Server Requirements**:\n - It shou... | 0.716487 | Docs: Python310_14737 | C | [
"accept",
"read",
"main",
"main"
] | 4 | [
[
"accept",
"read"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 975409e32c561d745c5d397e51315a834d051b69 | 8403e14ef41e91df3b53b450da72595b4820674c | |||
v1.0 | complete | Docs | Docs: Python310_14932_C | from types import FunctionType, CodeType
def is_function(obj) -> bool:
"""
Check if the given object is a function object.
:param obj: Object to check.
:type obj: Any
:return: True if object is a function, False otherwise.
:rtype: bool
"""
def create_function(code, globals_) -> FunctionTy... | from types import FunctionType, CodeType
def is_function(obj) -> bool:
"""
Check if the given object is a function object.
:param obj: Object to check.
:type obj: Any
:return: True if object is a function, False otherwise.
:rtype: bool
"""
return isinstance(obj, FunctionType)
def crea... | import pytest
from types import CodeType
from solution import is_function, create_function, get_function_details, set_function_globals
def test_is_function():
def sample_func():
pass
assert is_function(sample_func) == True
assert is_function(42) == False
assert is_function("string") == Fal... | [
{
"docstring": "Check if the given object is a function object.\n\n:param obj: Object to check.\n:type obj: Any\n:return: True if object is a function, False otherwise.\n:rtype: bool",
"function_declaration": "def is_function(obj):",
"function_name": "is_function",
"parameter_list": "(obj)"
},
{... | [
0,
0,
0,
1,
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": "def is_function(obj) -> bool:\n \"\"\"\n Check if the given object is a function object.\n\n :param obj: Object to check.\n :type obj: Any\n :return: Tru... | trial_gpt4o_5 | {
"original_instruction": "You are tasked with creating a Python module that mimics some of the functionalities provided by the `PyFunction` C API, specifically for creating and inspecting function objects. Your implementation will involve:\n\n1. Verifying if an object is a function.\n2. Creating a new function objec... | 0.716948 | Docs: Python310_14932 | C | [
"is_function",
"create_function",
"get_function_details",
"set_function_globals"
] | 4 | [
[
"get_function_details",
"is_function"
],
[
"set_function_globals",
"is_function"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d7e9a559eeab13669fa39ebcd948c481975f8da4 | 15355dd497bd2f41903d258ce216988bf046a0f0 | |||
v1.0 | complete | Docs | Docs: Python310_14723_C | import os
from datetime import datetime
import threading
import struct
def generate_filename(template: str, record_id: int, date: str, orig_name: str) -> str:
"""
Generates a filename based on a given template.
template: str - The template string containing placeholders for record_id, date, and orig_n... | import os
from datetime import datetime
import threading
import struct
def generate_filename(template: str, record_id: int, date: str, orig_name: str) -> str:
"""
Generates a filename based on a given template.
template: str - The template string containing placeholders for record_id, date, and orig_n... | import os
import tempfile
import struct
import threading
import pytest
from solution import generate_filename, process_dataset, batch_process
def test_generate_filename():
template = "processed_%date%_%record_id%_%orig_name%"
record_id = 123
date = "25Oct23"
orig_name = "dataset1.bin"
expected_file... | [
{
"docstring": "Generates a filename based on a given template.\n\ntemplate: str - The template string containing placeholders for record_id, date, and orig_name.\nrecord_id: int - The ID of the record.\ndate: str - The date string to be included in the filename.\norig_name: str - The original file name.\n\nRet... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nfrom datetime import datetime\nimport threading\nimport struct\n\ndef generate_filename(template: str, record_id: int, date: str, orig_name: str) -> str:\n ... | trial_gpt4o_0 | {
"original_instruction": "**Question: Optimize a Batch Processing System with String Templating, Binary Data Handling, and Multi-threading**\n\nYou are tasked with designing and implementing a batch processing system that will handle large datasets. This system must:\n1. Use templating to generate consistent file na... | 0.60723 | Docs: Python310_14723 | C | [
"generate_filename",
"process_dataset",
"batch_process"
] | 3 | [
[
"process_dataset",
"generate_filename"
]
] | 1 | [
"process_dataset"
] | false | [] | false | pytest | true | [] | true | c7f84c44c751275fb839c0e07c5a7121929f5836 | 7e50f15bd65a30afdcdc3beb021aa7995730b23f | |||
v1.0 | complete | Docs | Docs: Python310_15735_C | def custom_debugger(logfile: str):
""" Set up a custom debugging and logging environment.
This function sets a global tracing function that logs function calls and returns to the specified log file.
Args:
logfile (str): The path to the log file where debugging information will be written.
Example... | import sys
import traceback
def tracefunc(frame, event, arg):
if event not in ('call', 'return', 'exception'):
return tracefunc
func_name = frame.f_code.co_name
if event == 'call':
args = frame.f_locals
log_message = f"{event} - {func_name} - {args}\n"
elif event == 'return... | import sys
import os
# Importing the solution
from solution import custom_debugger
def example_function(a, b):
return a + b
def function_with_exception():
raise ValueError("An error occurred")
def test_custom_debugger(tmpdir):
log_file = tmpdir.join("log.txt")
# Start the custom debugger
cu... | [
{
"docstring": null,
"function_declaration": "def tracefunc(frame, event, arg):",
"function_name": "tracefunc",
"parameter_list": "(frame, event, arg)"
},
{
"docstring": null,
"function_declaration": "def custom_debugger(logfile):",
"function_name": "custom_debugger",
"parameter_... | [
0,
0,
0,
0,
1,
0,
0,
0,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nimport inspect\n\ndef custom_debugger(logfile: str):\n def tracefunc(frame, event, arg):\n if event == 'call':\n function_name = frame.... | trial_gpt4o_9 | {
"original_instruction": "**Objective:**\nCreate a Python script that interacts with the runtime environment using the `sys` module to provide custom runtime debugging and logging.\n\n**Task:**\nYou are required to write a function `custom_debugger(logfile)` that sets up a custom debugging and logging environment. T... | 0.593873 | Docs: Python310_15735 | C | [
"tracefunc",
"custom_debugger"
] | 2 | [
[
"custom_debugger",
"tracefunc"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2c09ac05e61a68b6f2e3bc9db5c641c05e3d5ef6 | aa72f2e44f8b99383147ae91a1dcff52e196fdf1 | |||
v1.0 | complete | Docs | Docs: Python310_16062_C | import aiohttp
import asyncio
import logging
async def fetch_page(session, url):
""" Fetch the content of a web page using the aiohttp library.
If fetching the page takes longer than 5 seconds, a timeout should occur and be logged.
"""
# Your implementation here
async def process_content(url, content... | import aiohttp
import asyncio
import logging
logging.basicConfig(level=logging.DEBUG)
async def fetch_page(session, url):
"""
Fetches a web page within a timeout.
Logs a timeout error if it takes longer than 5 seconds.
"""
try:
async with session.get(url, timeout=5) as response:
... | import pytest
import asyncio
from unittest.mock import patch, AsyncMock
from solution import fetch_page, process_content, main
@pytest.mark.asyncio
async def test_fetch_page_success():
mock_session = AsyncMock()
mock_response = AsyncMock()
mock_response.text = AsyncMock(return_value="Success")
mock_res... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import aiohttp\nimport asyncio\nimport logging\nfrom aiohttp import ClientTimeout\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG)\n\nasync def fetch_pa... | trial_gpt4o_2 | {
"original_instruction": "### Asynchronous Web Scraper with Timeouts and Logging\n\nYou are to develop an asynchronous web scraper using the asyncio package in Python. The web scraper should be capable of fetching multiple web pages concurrently, process their content for a specific keyword, and log the results. Thi... | 0.572166 | Docs: Python310_16062 | C | [
"fetch_page",
"process_content",
"main",
"fetch_and_process"
] | 4 | [
[
"fetch_and_process",
"fetch_page"
],
[
"fetch_and_process",
"process_content"
]
] | 2 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 5f6be8e0768c4ad1916c3f56121387715d27e22f | a0fd2d107e629d491d62771b4d5103ac7d323236 | |||
v1.0 | complete | Docs | Docs: Python310_15649_C | import spwd
import time
def fetch_user_details(username: str) -> dict:
"""
Fetch the user details from the shadow password database.
Parameters:
username (str): The username to fetch details for.
Returns:
dict: Dictionary of user details.
Raises:
Permi... | import spwd
import time
def fetch_user_details(username):
"""
Fetch the user details from the shadow password database.
Parameters:
username (str): The username to fetch details for.
Returns:
dict: Dictionary of user details.
Raises:
PermissionError: I... | import pytest
import spwd
from solution import fetch_user_details, password_expiry_status, list_all_usernames
@pytest.fixture
def mock_spwd(monkeypatch):
class MockShadowUser:
def __init__(self, sp_namp, sp_pwdp, sp_lstchg, sp_min, sp_max, sp_warn, sp_inact, sp_expire, sp_flag):
self.sp_namp = ... | [
{
"docstring": "Fetch the user details from the shadow password database.\n\nParameters:\n username (str): The username to fetch details for.\n \nReturns:\n dict: Dictionary of user details.\n \nRaises:\n PermissionError: If necessary privileges are not available.\n KeyError: If the user is no... | [
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 spwd\nimport time\n\ndef fetch_user_details(username):\n \"\"\"\n Fetch the user details from the shadow password database.\n \n Parameters:\n ... | trial_gpt4o_0 | {
"original_instruction": "### Shadow Password Management with `spwd` Module\n\nIn this task, you are required to write a Python script that interacts with the Unix shadow password database using the `spwd` module. Your script should perform the following operations:\n\n1. **Fetch User Details**:\n Write a function... | 0.536708 | Docs: Python310_15649 | C | [
"fetch_user_details",
"password_expiry_status",
"list_all_usernames"
] | 3 | [
[
"password_expiry_status",
"fetch_user_details"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a2d2a4ffccb7239bd5eece7efd9eb05d0c49894b | 0d56be8429f181fe3f54beb3c18a58e70216dcf9 | |||
v1.0 | complete | Docs | Docs: Python310_14999_C | def convert_string_to_double(s: str) -> float:
"""
Converts the given string `s` to a floating-point number using PyOS_string_to_double.
Parameters:
s (str): The string to convert.
Returns:
float: The converted floating point number.
Raises:
ValueError: If the string is no... | def convert_string_to_double(s: str) -> float:
"""
Converts the given string `s` to a floating-point number.
Parameters:
s (str): The string to convert.
Returns:
float: The converted floating point number.
Raises:
ValueError: If the string is not a valid floating-point num... | import pytest
from solution import convert_string_to_double, convert_double_to_string, case_insensitive_compare, format_and_compare
def test_convert_string_to_double():
assert convert_string_to_double("123.456") == 123.456
assert convert_string_to_double("0.567") == 0.567
assert convert_string_to_double("-... | [
{
"docstring": "Converts the given string `s` to a floating-point number.\n\nParameters:\ns (str): The string to convert.\n\nReturns:\nfloat: The converted floating point number.\n\nRaises:\nValueError: If the string is not a valid floating-point number.",
"function_declaration": "def convert_string_to_doub... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def convert_string_to_double(s: str) -> float:\n \"\"\"\n Converts the given string `s` to a floating-point number.\n \n Parameters:\n s (str): The strin... | trial_gpt4o_2 | {
"original_instruction": "### Formatted String Handling and Case-Insensitive Comparison\n\nYou are required to implement functions that will read formatted data from a given string, convert it to numbers, perform specific operations, and then output the result as a formatted string. Additionally, you will perform ca... | 0.574891 | Docs: Python310_14999 | C | [
"convert_string_to_double",
"convert_double_to_string",
"case_insensitive_compare",
"format_and_compare"
] | 4 | [
[
"format_and_compare",
"case_insensitive_compare"
],
[
"format_and_compare",
"convert_double_to_string"
],
[
"format_and_compare",
"convert_string_to_double"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 50ccb411a0f024ea1da5203413904218f58b6d97 | 554abc64db1c59f9ad4d84082e4a74522a4d75eb | |||
v1.0 | complete | Docs | Docs: Pytorch_15115_C | from typing import List
import torch.multiprocessing as mp
def compute_worker(data_segment: List[int]) -> List[int]:
"""
Function for worker process to compute.
Args:
data_segment: List of integers.
Returns:
List of squared integers.
"""
return [x ** 2 for x in data_segment]
def distr... | import torch.multiprocessing as mp
def compute_worker(data_segment):
return [x ** 2 for x in data_segment]
def distributed_computation(data, num_workers):
def worker_process(data_partition, return_list, index):
result = compute_worker(data_partition)
return_list[index] = result
# Splittin... | from solution import distributed_computation
import pytest
def test_distributed_computation_basic():
data = [1, 2, 3, 4, 5, 6]
num_workers = 2
expected_output = [1, 4, 9, 16, 25, 36]
assert distributed_computation(data, num_workers) == expected_output
def test_distributed_computation_single_worker():
... | [
{
"docstring": null,
"function_declaration": "def compute_worker(data_segment):",
"function_name": "compute_worker",
"parameter_list": "(data_segment)"
},
{
"docstring": null,
"function_declaration": "def distributed_computation(data, num_workers):",
"function_name": "distributed_com... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.distributed.elastic.multiprocessing import start_processes\nimport math\n\ndef compute_worker(data_segment, return_list, index):\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "## Problem Statement\n\nYou are required to implement a multiprocessing system using PyTorch's `torch.distributed.elastic.multiprocessing` package. Your task is to simulate a distributed training setup where multiple worker processes perform computations on separate portions of input data, ... | 0.587857 | Docs: Pytorch_15115 | C | [
"compute_worker",
"distributed_computation"
] | 2 | [
[
"distributed_computation",
"compute_worker"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 12ecf4d11db9eb3e98ad98940f46d481c0d77cc5 | 3f64713089a8045f47a64a21b608448f1f092cca | |||
v1.0 | complete | Docs | Docs: Python310_16172_C | import signal
import sys
import time
def sigint_handler(signum, frame):
print("SIGINT received, graceful shutdown.")
sys.exit(0)
def sigalrm_handler(signum, frame):
print("Alarm signal received.")
def setup_signal_handlers():
"""Setup custom signal handlers for SIGINT and SIGALRM."""
signal.signa... | import signal
import time
import sys
def sigint_handler(signum, frame):
print("SIGINT received, graceful shutdown.")
sys.exit(0)
def sigalrm_handler(signum, frame):
print("Alarm signal received.")
def setup_signal_handlers():
signal.signal(signal.SIGINT, sigint_handler)
signal.signal(signal.SIGAL... | import os
import signal
import subprocess
import time
def run_script_and_test_signals():
# Start the script as a subprocess
proc = subprocess.Popen(['python', 'solution.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
# Allow some time for the process to start and print "Running..." ... | [
{
"docstring": null,
"function_declaration": "def sigint_handler(signum, frame):",
"function_name": "sigint_handler",
"parameter_list": "(signum, frame)"
},
{
"docstring": null,
"function_declaration": "def sigalrm_handler(signum, frame):",
"function_name": "sigalrm_handler",
"pa... | [
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 signal\nimport time\nimport sys\n\ndef sigint_handler(signum, frame):\n print(\"SIGINT received, graceful shutdown.\")\n sys.exit(0)\n\ndef sigalrm_handler... | trial_gpt4o_0 | {
"original_instruction": "#### Objective\nYou are required to write a Python script that demonstrates your understanding of signal handling using the Python `signal` module. You will implement a custom signal handler that responds to specific signals and performs designated actions. \n\n#### Task\n1. **Signal Handle... | 0.526054 | Docs: Python310_16172 | C | [
"sigint_handler",
"sigalrm_handler",
"setup_signal_handlers",
"main"
] | 4 | [
[
"setup_signal_handlers",
"sigalrm_handler"
],
[
"setup_signal_handlers",
"sigint_handler"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 101838e8c8a7265855e80d5cd50035d0e29359e6 | c766b04827fd7f4871bada7c7789da41709c9414 | |||
v1.0 | complete | Docs | Docs: Python310_15702_C | class FileProcessingError(Exception):
"""Base exception class for file processing errors."""
pass
class FileNotFound(FileProcessingError):
"""Exception raised when the specified file does not exist."""
def __init__(self, file_path):
self.file_path = file_path
super().__init__(f"File {se... | class FileProcessingError(Exception):
"""Base exception class for file processing errors."""
pass
class FileNotFound(FileProcessingError):
"""Exception raised when the specified file does not exist."""
def __init__(self, file_path):
self.file_path = file_path
super().__init__(f"File {se... | import pytest
from solution import FileNotFound, FileCorrupted, PermissionDenied, read_file, process_file
def test_read_nonexistent_file():
with pytest.raises(FileNotFound) as exc_info:
read_file("nonexistent.txt")
assert str(exc_info.value) == "File nonexistent.txt not found."
def test_read_corrupted... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class FileProcessingError(Exception):\n \"\"\"Base class for file processing errors.\"\"\"\n pass\n\nclass FileNotFound(FileProcessingError):\n \"\"\"Raised wh... | trial_gpt4o_1 | {
"original_instruction": "### Coding Assignment:\n\n#### Custom Exception Handling and Propagation\n\n**Objective:**\nCreate a custom exception class hierarchy and write functions that demonstrate raising and handling these exceptions properly.\n\n**Problem Statement:**\nYou are tasked with implementing a small modu... | 0.542173 | Docs: Python310_15702 | C | [
"read_file",
"process_file"
] | 2 | [
[
"process_file",
"read_file"
]
] | 1 | [] | false | [
"FileProcessingError",
"FileNotFound",
"FileCorrupted",
"PermissionDenied"
] | true | pytest | true | [] | true | 1ff625e3651b97d9f65c6851ab7c1782b58055b0 | 5df2f0a9210a0e49f5e901231ff778124502fb3b | |||
v1.0 | complete | Docs | Docs: Pytorch_15505_C | import torch
from torch.func import vmap, grad
def transformed_f(x: torch.Tensor) -> torch.Tensor:
"""
Transforms the given function f to be compatible with torch.func.vmap.
Parameters:
x (torch.Tensor): A tensor of arbitrary shape.
Returns:
torch.Tensor: A transformed tensor after applying t... | import torch
from torch.func import vmap
def f(x: torch.Tensor) -> torch.Tensor:
# Compute sine of x, then the square of the sine, and return the sum of the squared sine values
sine_x = torch.sin(x)
squared_sine_x = sine_x ** 2
return torch.sum(squared_sine_x)
def transformed_f(x: torch.Tensor) -> tor... | import torch
from solution import transformed_f, batched_f
def test_transformed_f_single_input():
x = torch.tensor([0.1, 0.2, 0.3])
result = transformed_f(x)
expected_result = torch.sum(torch.sin(x) ** 2)
assert torch.isclose(result, expected_result), f"Expected {expected_result}, but got {result}"
de... | [
{
"docstring": null,
"function_declaration": "def f(x):",
"function_name": "f",
"parameter_list": "(x)"
},
{
"docstring": "Transforms the given function f to be compatible with torch.func.vmap.\n\nParameters:\nx (torch.Tensor): A tensor of arbitrary shape.\n\nReturns:\ntorch.Tensor: A transf... | [
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 torch\nfrom torch.func import vmap\n\ndef f(x: torch.Tensor) -> torch.Tensor:\n # Compute sine of x, then the square of the sine, and return the sum of the sq... | trial_gpt4o_0 | {
"original_instruction": "**Coding Assessment Question: Understanding and Implementing Function Transformations Using `torch.func`**\n\n### Objective\nImplement a function using PyTorch that computes a specific mathematical operation on batched tensor inputs and ensure it adheres to the constraints and limitations o... | 0.594757 | Docs: Pytorch_15505 | C | [
"f",
"transformed_f",
"batched_f"
] | 3 | [
[
"batched_f",
"transformed_f"
],
[
"transformed_f",
"f"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | f62a54f91fdcf55af62ec422d8e4661d981519d7 | 9d269c12e8ab3a4d941d1a872c1c9529b6339adc | |||
v1.0 | complete | Docs | Docs: Pytorch_15058_C | import os
import torch
def configure_pytorch_mps():
"""
Configures the PyTorch MPS environment variables.
This function sets the following environment variables:
- PYTORCH_MPS_FAST_MATH: Enables fast math for kernels.
- PYTORCH_MPS_HIGH_WATERMARK_RATIO: Limits the maximum allowed allocati... | import os
import torch
def configure_pytorch_mps():
"""
Configures the PyTorch MPS environment variables.
"""
os.environ['PYTORCH_MPS_FAST_MATH'] = '1'
os.environ['PYTORCH_MPS_HIGH_WATERMARK_RATIO'] = '0.95'
os.environ['PYTORCH_MPS_LOW_WATERMARK_RATIO'] = '0.85'
os.environ['PYTORCH_DEBUG_MP... | import os
from unittest.mock import patch
def test_configure_pytorch_mps():
from solution import configure_pytorch_mps
with patch.dict(os.environ, {}, clear=True):
configure_pytorch_mps()
assert os.environ['PYTORCH_MPS_FAST_MATH'] == '1'
assert os.environ['PYTORCH_MPS_HIGH... | [
{
"docstring": "Configures the PyTorch MPS environment variables.",
"function_declaration": "def configure_pytorch_mps():",
"function_name": "configure_pytorch_mps",
"parameter_list": "()"
},
{
"docstring": "Creates and trains a dummy linear regression model to demonstrate the applied MPS co... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport torch\n\ndef configure_pytorch_mps():\n \"\"\"\n Configures the PyTorch MPS environment variables.\n \"\"\"\n os.environ['PYTORCH_MPS_FAST... | trial_gpt4o_4 | {
"original_instruction": "<|Analysis Begin|>\n\nThe provided documentation outlines several environment variables specific to PyTorch's use of Apple's Metal Performance Shaders (MPS). These variables control various aspects such as logging, profiling, and memory allocation behaviors. Key aspects include setting high... | 0.406878 | Docs: Pytorch_15058 | C | [
"configure_pytorch_mps",
"train_dummy_model"
] | 2 | [
[
"train_dummy_model",
"configure_pytorch_mps"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | ddfd5e881b34d5a8b948671945ee3990d10ed90b | 3f8dc3b34ec869713ee950f8e382f1aaba95d5fe | |||
v1.0 | complete | Docs | Docs: Python310_16268_C | import threading
import math
def calculate_factorial(n):
"""
Calculate and return the factorial of n.
"""
return math.factorial(n)
def thread_function(n):
result = calculate_factorial(n)
print(f"Thread for n={n}: {result}")
def main():
"""
Initialize the main function to spawn thread... | # solution.py
import threading
import math
def calculate_factorial(n):
"""
Calculate and return the factorial of n.
"""
return math.factorial(n)
def thread_function(n):
result = calculate_factorial(n)
print(f"Thread for n={n}: {result}")
def main():
numbers = [5, 6, 7, 8, 9]
threads ... | # test_solution.py
from solution import calculate_factorial, thread_function
import threading
def test_calculate_factorial():
assert calculate_factorial(5) == 120
assert calculate_factorial(6) == 720
assert calculate_factorial(7) == 5040
# Mock print for testing thread_function
def test_thread_function(m... | [
{
"docstring": "Calculate and return the factorial of n.",
"function_declaration": "def calculate_factorial(n):",
"function_name": "calculate_factorial",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def thread_function(n):",
"function_name": "thread_functi... | [
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": "# solution/multi_threaded.c\n\n#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include <pthread.h>\n#include <math.h>\n\n#define THREAD_COUNT 3\n\nvoid* thread_func(voi... | trial_gpt4o_7 | {
"original_instruction": "**Title: Implement a Multi-threaded C Extension Module with Python Embedding**\n\n**Objective**:\nIn this question, you will implement a simple multi-threaded C extension module that utilizes Python 3.10’s embedding features. This module should demonstrate the proper use of the Global Inter... | 0.719863 | Docs: Python310_16268 | C | [
"calculate_factorial",
"thread_function",
"main"
] | 3 | [
[
"thread_function",
"calculate_factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ecd90673bcc971e788da51e670c7b3a75a03ed13 | 2ddbcdee551a1759f6638c92cebc0007a41e139a | |||
v1.0 | complete | Docs | Docs: Python310_16247_C | from typing import List
import itertools
import functools
def prime_generator_partial_sum(n: int) -> List[int]:
"""Generate the specified count of prime numbers and return the running sum of these prime numbers.
:param n: The number of primes to generate and sum.
:type n: int
:return: A list conta... | from typing import List
import itertools
import functools
def is_prime(n: int) -> bool:
"""Check if a number is a prime number."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n ... | from solution import prime_generator_partial_sum
def test_prime_generator_partial_sum_5():
assert prime_generator_partial_sum(5) == [2, 5, 10, 17, 28]
def test_prime_generator_partial_sum_1():
assert prime_generator_partial_sum(1) == [2]
def test_prime_generator_partial_sum_10():
assert prime_generator_p... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate an infinite sequence of prime numbers.",
"function_declaration": "def generate_primes():",
"function_nam... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport itertools\nfrom functools import partial\n\ndef is_prime(num):\n \"\"\" Helper function to check if a number is prime. \"\"\"\n if... | trial_gpt4o_2 | {
"original_instruction": "### Python Coding Assessment Question\n\n#### Objective\nDemonstrate understanding of Python's functional programming modules (`itertools` and `functools`) by implementing a solution that utilizes iterators and partial function application.\n\n#### Problem Statement\n\nImplement a function ... | 0.710382 | Docs: Python310_16247 | C | [
"is_prime",
"generate_primes",
"prime_generator_partial_sum"
] | 3 | [
[
"generate_primes",
"is_prime"
],
[
"prime_generator_partial_sum",
"generate_primes"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 590f196e3e378d30f64fbcb3822984cca24e916b | a79b7bc2ed678f305a43a8e21f9b0bfbcff4d1e8 | |||
v1.0 | complete | Docs | Docs: Python310_15334_C | import aiohttp
import asyncio
from bs4 import BeautifulSoup
async def fetch_url(session, url):
""" Fetch the HTML content from a URL asynchronously. """
pass # Your implementation goes here.
def parse_html(html):
""" Parse the HTML content to extract the title. """
pass # Your implementation goes he... | import aiohttp
import asyncio
from bs4 import BeautifulSoup
async def fetch_url(session, url):
try:
async with session.get(url, timeout=10) as response:
return await response.text()
except asyncio.TimeoutError:
print(f"Timeout while fetching {url}")
except Exception as e:
... | import pytest
import asyncio
from solution import fetch_url, parse_html, scrape_titles
# Helper function to run async functions for testing
def run_async(func, *args):
return asyncio.run(func(*args))
# Note: These tests require live internet connections and access to the URLs.
async def mock_fetch_url(session, u... | [
{
"docstring": null,
"function_declaration": "def parse_html(html):",
"function_name": "parse_html",
"parameter_list": "(html)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import aiohttp\nimport asyncio\nfrom bs4 import BeautifulSoup\n\nasync def fetch_url(session, url):\n try:\n async with session.get(url, timeout=10) as respon... | trial_gpt4o_1 | {
"original_instruction": "### Asynchronous Web Scraper with asyncio\n\n#### Problem Statement:\n\nYou are tasked with creating an asynchronous web scraper using the `asyncio` package. Your scraper should perform the following tasks:\n\n1. Fetch the HTML content from multiple URLs concurrently.\n2. Parse the HTML to ... | 0.742752 | Docs: Python310_15334 | C | [
"fetch_url",
"parse_html",
"scrape_titles"
] | 3 | [
[
"scrape_titles",
"fetch_url"
],
[
"scrape_titles",
"parse_html"
]
] | 2 | [] | false | [] | false | pytest | true | [
"aiohttp",
"bs4"
] | false | 271618aab3717d530e1f026d7e167774755740ba | e62e91ab2a593ad027698be64d607ba9fb86fae2 | |||
v1.0 | complete | Docs | Docs: Python310_16205_C | def process_primes(input_list: list) -> dict:
""" Process an input list to find prime numbers, sort them, and create a dictionary
mapping each prime number to its position in the sorted list with the sum of primes as a final entry.
>>> process_primes([10, 15, 3, 7, 11, 17, 2]) == {17: 1, 11: 2, 7: 3, 3: 4, ... | def is_prime(n):
"""
Check if the number `n` is a prime number.
"""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def process_primes(input_list: list) -> dict:
"""
Process the input list to find prime numb... | from solution import process_primes
def test_process_primes_basic():
input_list = [10, 15, 3, 7, 11, 17, 2]
expected_output = {17: 1, 11: 2, 7: 3, 3: 4, 2: 5, 'sum': 40}
assert process_primes(input_list) == expected_output
def test_process_primes_with_no_primes():
input_list = [4, 6, 8, 9, 10, 12]
... | [
{
"docstring": "Check if the number `n` is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Process the input list to find prime numbers, sort them, and create a dictionary\nmapping each prime number to its ... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(number):\n \"\"\"\n Helper function to check if a number is a prime number.\n \"\"\"\n if number < 2:\n return False\n for i in range... | trial_gpt4o_2 | {
"original_instruction": "#### Objective\nTo assess the student's understanding and ability to work with lists and dictionaries, using various list methods and comprehensions.\n\n#### Problem Statement\nYou are given an input list of integers. Your task is to create a function that processes this list through severa... | 0.668113 | Docs: Python310_16205 | C | [
"is_prime",
"process_primes"
] | 2 | [
[
"process_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9556247fa30bc7509ec2a6f13a24badb7b93ca63 | 0c919fda5767f61acc972e6b67439c2e27a5bc80 | |||
v1.0 | complete | Docs | Docs: Scikit_14718_C | import numpy as np
from sklearn.metrics.pairwise import linear_kernel, polynomial_kernel, rbf_kernel
def compute_kernel(X, kernel='linear', **kwargs):
"""
Computes the pairwise kernel matrix for the given dataset.
Parameters:
X (numpy array): Dataset of shape (n_samples, n_features).
kernel (s... | import numpy as np
from sklearn.metrics.pairwise import linear_kernel, polynomial_kernel, rbf_kernel
def compute_kernel(X, kernel='linear', **kwargs):
"""
Computes the pairwise kernel matrix for the given dataset.
Parameters:
X (numpy array): Dataset of shape (n_samples, n_features).
kernel (s... | import numpy as np
from solution import compute_kernel, compute_similarity, knn_classify
def test_compute_kernel_linear():
X = np.array([[1, 2], [3, 4], [5, 6]])
K = compute_kernel(X, kernel='linear')
expected_K = np.dot(X, X.T)
assert np.allclose(K, expected_K)
def test_compute_kernel_polynomial():
... | [
{
"docstring": "Computes the pairwise kernel matrix for the given dataset.\n\nParameters:\nX (numpy array): Dataset of shape (n_samples, n_features).\nkernel (str): The type of kernel to use ('linear', 'polynomial', 'rbf').\n**kwargs: Additional keyword arguments for the specific kernel parameters.\n\nReturns:\... | [
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 numpy as np\nfrom sklearn.metrics.pairwise import linear_kernel, polynomial_kernel, rbf_kernel\nfrom scipy.stats import mode\n\ndef compute_kernel(X, kernel, **k... | trial_gpt4o_4 | {
"original_instruction": "### Advanced Coding Assessment Question on scikit-learn\n\n#### Context\nYou are a data scientist working on a project that involves clustering and classification of image data represented as feature vectors. Your task is to compute the similarity between different images using various kern... | 0.567172 | Docs: Scikit_14718 | C | [
"compute_kernel",
"compute_similarity",
"knn_classify"
] | 3 | [
[
"knn_classify",
"compute_similarity"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | ca1a0618e0a395f2a87f07c9c63f2880690565eb | fd0d716974b6f8dbf9c67b5e0ef276f5a9f35f30 | |||
v1.0 | complete | Docs | Docs: Python310_15834_C | import asyncio
import contextvars
import uuid
# Context variable for storing session ID
session_id_var = contextvars.ContextVar('session_id')
def generate_session_id() -> str:
"""Generate a unique session ID."""
pass # Implementation here
async def handle_client(reader, writer):
"""Handle client connect... | import asyncio
import contextvars
import uuid
# Context variable for storing session ID
session_id_var = contextvars.ContextVar('session_id')
def generate_session_id() -> str:
"""Generate a unique session ID."""
return str(uuid.uuid4())
async def handle_client(reader, writer):
ctx = contextvars.copy_cont... | import asyncio
import pytest
from solution import generate_session_id, handle_client, main
import socket
import threading
def test_generate_session_id():
session_id_1 = generate_session_id()
session_id_2 = generate_session_id()
assert session_id_1 != session_id_2
assert len(session_id_1) > 0
a... | [
{
"docstring": "Generate a unique session ID.",
"function_declaration": "def generate_session_id():",
"function_name": "generate_session_id",
"parameter_list": "()"
}
] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport contextvars\nimport uuid\n\n# Context variable for storing session ID\nsession_id_var = contextvars.ContextVar('session_id')\n\ndef generate_sess... | trial_gpt4o_1 | {
"original_instruction": "**Context Management in an Asynchronous Framework**\n\nAs a developer, you are tasked with creating a small web server using `asyncio` that handles multiple clients asynchronously and keeps track of the session data using `contextvars`.\n\n**Requirements:**\n\n1. **Session Management**: Eac... | 0.560049 | Docs: Python310_15834 | C | [
"generate_session_id",
"handle_client",
"main"
] | 3 | [
[
"handle_client",
"generate_session_id"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9f6a98fd53fd3cca46d22f756f2fe5f3c77efec9 | 6e0ea14bee3c9117edb34a0def04444c696cbccd | |||
v1.0 | complete | Docs | Docs: Pytorch_16434_C | import torch
def complex_to_real_function(z: torch.Tensor) -> torch.Tensor:
"""
Computes a real-valued function of a complex input tensor.
The function computes the magnitude squared of the complex input,
which is a real number.
Parameters:
z (torch.Tensor): A complex-valued tensor of shape (N... | import torch
def complex_to_real_function(z: torch.Tensor) -> torch.Tensor:
"""
Computes a real-valued function of a complex input tensor.
The function computes the magnitude squared of the complex input,
which is a real number.
Parameters:
z (torch.Tensor): A complex-valued tensor of shape (N... | from solution import complex_to_real_function, verify_gradients
import torch
def test_complex_to_real_function():
# Test with a known complex tensor
z = torch.complex(torch.tensor([3.0, 4.0]), torch.tensor([1.0, 2.0]))
output = complex_to_real_function(z)
expected_output = torch.tensor([10.0, 20.0]) #... | [
{
"docstring": "Computes a real-valued function of a complex input tensor.\nThe function computes the magnitude squared of the complex input,\nwhich is a real number.\n\nParameters:\nz (torch.Tensor): A complex-valued tensor of shape (N,)\n\nReturns:\ntorch.Tensor: A real-valued tensor of shape (N,)",
"func... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef complex_to_real_function(z: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Computes a real value function of a complex input tensor.\n The funct... | trial_gpt4o_1 | {
"original_instruction": "#### Objective\nImplement a custom PyTorch function that operates on complex inputs and produces real-valued outputs. Then, use `torch.autograd.gradcheck` to verify the correctness of the gradients computed for this function.\n\n#### Problem Statement\nYou are required to implement a comple... | 0.451918 | Docs: Pytorch_16434 | C | [
"complex_to_real_function",
"verify_gradients"
] | 2 | [
[
"verify_gradients",
"complex_to_real_function"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 2ffb902b02ae3a517a0c75f786e0fdfdf0e0366f | 3623b4c53aadcd3d4533261659682f99aab44b1e | |||
v1.0 | complete | Docs | Docs: Python310_16056_C | import concurrent.futures
import requests
from typing import List, Dict, Union
def fetch_url_content(url: str, timeout: int) -> Union[str, Exception]:
"""
Fetches content from a URL with a specified timeout.
"""
try:
response = requests.get(url, timeout=timeout)
response.raise_for_statu... | import concurrent.futures
import requests
from typing import List, Dict, Union
def fetch_url_content(url: str, timeout: int) -> Union[str, Exception]:
"""
Fetches content from a URL with a specified timeout.
"""
try:
response = requests.get(url, timeout=timeout)
response.raise_for_statu... | from solution import check_keyword_in_urls
def mock_requests_get(url, timeout):
class MockResponse:
def __init__(self, text='', status_code=200):
self.text = text
self.status_code = status_code
def raise_for_status(self):
if self.status_code != 200:
... | [
{
"docstring": "Fetches content from a URL with a specified timeout.",
"function_declaration": "def fetch_url_content(url, timeout):",
"function_name": "fetch_url_content",
"parameter_list": "(url, timeout)"
},
{
"docstring": "Searches for the keyword in the given content.",
"function_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 concurrent.futures\nimport requests\nfrom typing import List, Dict, Union\n\ndef fetch_url_content(url: str, timeout: int) -> Union[str, Exception]:\n \"\"\"\... | trial_gpt4o_0 | {
"original_instruction": "You have been given a list of URLs and you are required to check if the content of these URLs contains a specific keyword. You will need to use both `ThreadPoolExecutor` and `ProcessPoolExecutor` to achieve this. You should also handle potential exceptions and timeouts gracefully.\n\n### In... | 0.573263 | Docs: Python310_16056 | C | [
"fetch_url_content",
"search_keyword",
"check_keyword_in_urls"
] | 3 | [
[
"check_keyword_in_urls",
"fetch_url_content"
],
[
"check_keyword_in_urls",
"search_keyword"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 28e2def01066b86e73d26073206be3360abc4bdb | 2630cb156e1524fdeac3d95465e848396f168cbe | |||
v1.0 | complete | Docs | Docs: Python310_15570_C | import curses
def save_to_file(buffer, filename="output.txt"):
with open(filename, "w") as f:
for line in buffer:
f.write(line + "\n")
def run_editor():
"""
Implements a simple text editor using the curses library. The editor will have the following features:
1. A main window that ... | import curses
def save_to_file(buffer, filename="output.txt"):
with open(filename, "w") as f:
for line in buffer:
f.write(line + "\n")
def run_editor():
def main(stdscr):
# Init curses
curses.curs_set(1) # Make the cursor visible
curses.noecho()
curses.cbre... | import pytest
import os
def test_save_to_file():
buffer = ["Hello", "World"]
filename = "test_output.txt"
save_to_file(buffer, filename)
with open(filename, "r") as f:
lines = f.readlines()
assert lines == ["Hello\n", "World\n"]
os.remove(filename)
def test_insert_m... | [
{
"docstring": null,
"function_declaration": "def save_to_file(buffer, filename='output.txt'):",
"function_name": "save_to_file",
"parameter_list": "(buffer, filename='output.txt')"
},
{
"docstring": null,
"function_declaration": "def run_editor():",
"function_name": "run_editor",
... | [
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 curses\n\ndef run_editor():\n def main(stdscr):\n curses.curs_set(1)\n \n # Set color pairs for status bar indication\n curses.sta... | trial_gpt4o_3 | {
"original_instruction": "### Advanced Python Programming Problem Using the `curses` Library\n\n**Objective:** Demonstrate your ability to create a complex text-based user interface using the `curses` library in Python.\n\n### Problem Description:\n\nYou are tasked with creating a simple text editor using the `curse... | 0.478809 | Docs: Python310_15570 | C | [
"save_to_file",
"run_editor"
] | 2 | [
[
"run_editor",
"save_to_file"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | aac209651fb06478d0855148ac768448438a9cd0 | 23bf45e4f3c5529ad4282ba6e8b2e92bf5094434 | |||
v1.0 | complete | Docs | Docs: Scikit_16070_C | import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score, make_scorer
def load_and_prepare_data(csv_path):
"""
Load dataset and preprocess by splitting into train and t... | import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score, make_scorer
def load_and_prepare_data(csv_path):
"""
Load dataset and preprocess by splitting into train and t... | from solution import load_and_prepare_data, train_regression_model, mean_bias_deviation, root_relative_squared_error, evaluate_model
import numpy as np
import pandas as pd
from sklearn.metrics import r2_score, mean_absolute_error
def test_load_and_prepare_data():
df = pd.DataFrame({
'feature1': np.random.r... | [
{
"docstring": "Load dataset and preprocess by splitting into train and test sets.\n\nParameters:\ncsv_path (str): Path to the CSV file containing the dataset.\n\nReturns:\ntuple: Splitted data (X_train, X_test, y_train, y_test).",
"function_declaration": "def load_and_prepare_data(csv_path):",
"functio... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics i... | trial_gpt4o_2 | {
"original_instruction": "**Advanced Coding Assessment Question**\n\n### Objective:\nAssess the understanding of implementing custom scoring metrics using scikit-learn and applying them to a supervised learning problem.\n\n### Scenario:\nYou are given a dataset and asked to train a regression model. After training t... | 0.802114 | Docs: Scikit_16070 | C | [
"load_and_prepare_data",
"train_regression_model",
"mean_bias_deviation",
"root_relative_squared_error",
"evaluate_model"
] | 5 | [
[
"evaluate_model",
"mean_bias_deviation"
],
[
"evaluate_model",
"root_relative_squared_error"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | ecf07d07218584f2b44f172160f21bd1a11cb08a | 1702b6ea41ffdbb0a6aaaf33570ef02d8c34e74d | |||
v1.0 | complete | Docs | Docs: Python310_16286_C | import os
import pydoc
def generate_and_serve_doc(module_name: str, output_dir: str, port: int = 0) -> str:
"""
Generate a summary of the documentation for the given module and save it as an HTML file.
Serve the HTML file via an HTTP server.
Args:
- module_name (str): The name of the module to doc... | import os
import pydoc
import http.server
import socketserver
import threading
from typing import Optional
def generate_html_summary(doc: str, module_name: str) -> str:
"""
Generate the HTML content for the summary of the module documentation.
Args:
- doc (str): The full documentation string of the mo... | from solution import generate_and_serve_doc
import os
def test_generate_and_serve_doc_existing_module(tmp_path):
module_name = "sys"
output_dir = tmp_path
url = generate_and_serve_doc(module_name, str(output_dir))
assert url.startswith("http://localhost:")
assert os.path.exists(os.path.join(ou... | [
{
"docstring": "Generate the HTML content for the summary of the module documentation.\n\nArgs:\n- doc (str): The full documentation string of the module.\n- module_name (str): The name of the module.\n\nReturns:\n- str: Formatted HTML content.",
"function_declaration": "def generate_html_summary(doc, modul... | [
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 pydoc\nimport http.server\nimport socketserver\nimport threading\n\ndef generate_and_serve_doc(module_name: str, output_dir: str, port: int = 0) -> st... | trial_gpt4o_5 | {
"original_instruction": "### Question:\n\n#### Documentation Summarizer and HTML Exporter\n\nYou are tasked with implementing a Python function that uses the \"pydoc\" module to generate a summary of the documentation for a given module and saves it as an HTML file. The function must also be able to serve this HTML... | 0.517386 | Docs: Python310_16286 | C | [
"generate_html_summary",
"generate_and_serve_doc"
] | 2 | [
[
"generate_and_serve_doc",
"generate_html_summary"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 39d2ff7d70907dcdaf6e3e8665a520077447d343 | 0813f5f18615824fa1eab9aecb6c2dccf1842305 | |||
v1.0 | complete | Docs | Docs: Pytorch_16565_C | import torch.cuda.tunable
def enable_tunable_ops():
"""
Enables the tunable operations.
"""
pass
def configure_tuning_params(duration: int, iterations: int):
"""
Configures the tuning parameters.
Args:
duration (int): The maximum tuning duration in milliseconds.
iterations (int): ... | import torch.cuda.tunable
def enable_tunable_ops():
"""
Enables the tunable operations.
"""
torch.cuda.tunable.enable()
def configure_tuning_params(duration: int, iterations: int):
"""
Configures the tuning parameters.
Args:
duration (int): The maximum tuning duration in milliseconds.... | import os
import torch.cuda.tunable
from solution import enable_tunable_ops, configure_tuning_params, write_tuning_results_to_file, perform_tuning
# Mocks to simulate the actual behavior since we can't perform real GPU tuning in this environment
def mock_enable():
pass
def mock_set_tuning_duration(duration):
... | [
{
"docstring": "Enables the tunable operations.",
"function_declaration": "def enable_tunable_ops():",
"function_name": "enable_tunable_ops",
"parameter_list": "()"
},
{
"docstring": "Configures the tuning parameters.\n\nArgs:\nduration (int): The maximum tuning duration in milliseconds.\nit... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch.cuda.tunable\n\ndef enable_tunable_ops():\n \"\"\"\n Enables the tunable operations.\n \"\"\"\n torch.cuda.tunable.enable()\n\ndef configure_tu... | trial_gpt4o_1 | {
"original_instruction": "**Question: Working with `torch.cuda.tunable` Module**\n\nIn this assignment, you are required to interact with the `torch.cuda.tunable` module to demonstrate your understanding of enabling features, configuring parameters, and managing file operations in PyTorch.\n\n### Task:\n\n1. **Enabl... | 0.313595 | Docs: Pytorch_16565 | C | [
"enable_tunable_ops",
"configure_tuning_params",
"write_tuning_results_to_file",
"perform_tuning"
] | 4 | [
[
"perform_tuning",
"configure_tuning_params"
],
[
"perform_tuning",
"enable_tunable_ops"
],
[
"perform_tuning",
"write_tuning_results_to_file"
]
] | 3 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 150222f4aa6810dc079aa9364ba6255265ad15e7 | f0de727c3a37dc5b7b03c3a6c4ae6c34c69557a4 | |||
v1.0 | complete | Docs | Docs: Python310_16481_C | import asyncio
import contextvars
import random
# Define the context variable
request_info = contextvars.ContextVar('request_info', default='No info')
def log_request_info(info: str) -> contextvars.Token:
"""
Sets the request information to the context variable.
:param info: The information to log.
:... | import asyncio
import contextvars
import random
# Define the context variable
request_info = contextvars.ContextVar('request_info', default='No info')
def log_request_info(info: str) -> contextvars.Token:
"""
Sets the request information to the context variable.
"""
return request_info.set(info)
def ... | import pytest
from contextvars import ContextVar
import asyncio
import random
# Mock random.uniform to make tests deterministic
@pytest.fixture(autouse=True)
def deterministic_random(monkeypatch):
def mock_random():
return 0.1 # fixed delay for test purposes
monkeypatch.setattr(random, 'uniform', mock... | [
{
"docstring": "Sets the request information to the context variable.",
"function_declaration": "def log_request_info(info):",
"function_name": "log_request_info",
"parameter_list": "(info)"
},
{
"docstring": "Retrieves the currently set value of request_info.",
"function_declaration": "... | [
0,
0,
0,
0,
1,
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 asyncio\nimport contextvars\nimport random\n\n# Define the context variable\nrequest_info = contextvars.ContextVar('request_info', default='No info')\n\ndef log_... | trial_gpt4o_7 | {
"original_instruction": "### Context: Context Management with `contextvars` and Asynchronous Programming\n\n**Question:**\n\nYou are tasked with developing a concurrent HTTP request handler that stores request-specific data using context variables. This involves simulating an environment where separate asynchronous... | 0.585084 | Docs: Python310_16481 | C | [
"log_request_info",
"retrieve_request_info",
"handle_request",
"main"
] | 4 | [
[
"handle_request",
"log_request_info"
],
[
"handle_request",
"retrieve_request_info"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 02ad9cb7f0fd7c4921a2cde15db06654b1d227ae | b85e961a17cdf03fbc4e409cc313f91de850d2fe | |||
v1.0 | complete | Docs | Docs: Python310_16312_C | def run_computation_in_threads(num_threads: int, data: list) -> list:
"""
Spawns 'num_threads' each processing a portion of 'data'.
Returns the combined result from all threads.
:param num_threads: Number of threads to create.
:param data: List of data for computation.
:return: List of results ... | from concurrent.futures import ThreadPoolExecutor
import ctypes
import threading
# Load the shared object (C-extension) compiled as `my_extension.so`
# Here we simulate the C-extension using ctypes
# Let's assume we have a C function `heavy_computation` that takes an int and returns an int
# For the sake of this simul... | import pytest
from solution import run_computation_in_threads
def test_single_thread():
data = [1, 2, 3, 4]
expected_results = [1, 4, 9, 16]
assert run_computation_in_threads(1, data) == expected_results
def test_multiple_threads():
data = [1, 2, 3, 4, 5, 6, 7, 8]
expected_results = [1, 4, 9, 16, ... | [
{
"docstring": null,
"function_declaration": "def heavy_computation(x):",
"function_name": "heavy_computation",
"parameter_list": "(x)"
},
{
"docstring": "Spawns 'num_threads' each processing a portion of 'data'.\nReturns the combined result from all threads.\n\n:param num_threads: Number of... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# This is a simulated example of what the C extension and Python integration would look like.\n\nfrom threading import Thread\nimport ctypes\nfrom ctypes import cdll, p... | trial_gpt4o_2 | {
"original_instruction": "### Python Thread Management with C-Extensions\n\nYou have been assigned to extend the functionality of a Python application by integrating a C-extension module. This extension will perform some heavy computations and interact with Python objects. Your task is to write a Python C-extension ... | 0.615109 | Docs: Python310_16312 | C | [
"heavy_computation",
"run_computation_in_threads"
] | 2 | [
[
"run_computation_in_threads",
"heavy_computation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5ffb0f4032594a53a21c11ecf1be3c499d80c712 | a5dcca4ff589444334496a825a3e6e23274782d8 | |||
v1.0 | complete | Docs | Docs: Python310_16164_C | import codecs
def custom_encode(input_text: str, encoding: str, errors: str) -> bytes:
"""
Encode the input text using the specified encoding and custom error handling.
Parameters:
- input_text (str): The text to be encoded.
- encoding (str): The encoding format to use.
- errors (str): The err... | import codecs
def custom_encode(input_text: str, encoding: str, errors: str) -> bytes:
"""
Encode the input text using the specified encoding and custom error handling.
Parameters:
- input_text (str): The text to be encoded.
- encoding (str): The encoding format to use.
- errors (str): The err... | from solution import (custom_encode, custom_decode, register_custom_error_handler, incremental_process)
def test_custom_encode_ascii():
register_custom_error_handler()
result = custom_encode("Hello, World!", "ascii", "strict")
assert result == b"Hello, World!"
def test_custom_encode_custom_error_handler()... | [
{
"docstring": "Encode the input text using the specified encoding and custom error handling.\n\nParameters:\n- input_text (str): The text to be encoded.\n- encoding (str): The encoding format to use.\n- errors (str): The error handling scheme.\n\nReturns:\n- bytes: The encoded byte sequence.",
"function_de... | [
0,
0,
0,
1,
0,
1,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import codecs\n\ndef custom_encode(input_text: str, encoding: str, errors: str) -> bytes:\n \"\"\"\n Encode the input text using the specified encoding and custom... | trial_gpt4o_5 | {
"original_instruction": "**Objective:**\nTo assess your understanding of the Python `codecs` package and its functionalities related to custom encoding, decoding, error handling, and incremental processing.\n\n**Problem:**\n\nYou are provided with a task to implement a text processing utility that dynamically handl... | 0.680182 | Docs: Python310_16164 | C | [
"custom_encode",
"custom_decode",
"hex_replace",
"register_custom_error_handler",
"incremental_process"
] | 5 | [
[
"register_custom_error_handler",
"hex_replace"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e4b611b7078bfe3ab8f84b283e0d26ac86c69327 | 70e473a57da5020ddee9b301e86c682fa166574e | |||
v1.0 | complete | Docs | Docs: Python310_15423_C | import email
from email.parser import BytesFeedParser
def parse_emails_from_log(log_file: str) -> list[str]:
""" Parse a log file containing multiple raw email messages separated by the delimiter "=====", and return a list of parsed email subjects.
>>> log_file_path = "path/to/log_file.txt"
>>> with o... | import email
from email.parser import BytesFeedParser
def parse_emails_from_log(log_file: str) -> list[str]:
subjects = []
delimiter = b"=====\n"
with open(log_file, 'rb') as f:
message_data = []
for line in f:
if line == delimiter:
if message_data:
... | import pytest
from solution import parse_emails_from_log
def test_parse_emails_from_log(tmp_path):
# Create a temporary log file
log_content = (
"From: user1@example.com\n"
"Subject: Meeting Today\n"
"To: user2@example.com\n"
"\n"
"Please join the meeting at 10 AM.\n"
... | [
{
"docstring": null,
"function_declaration": "def parse_emails_from_log(log_file):",
"function_name": "parse_emails_from_log",
"parameter_list": "(log_file)"
},
{
"docstring": null,
"function_declaration": "def parse_email_subject(raw_message):",
"function_name": "parse_email_subject... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import email\nfrom email.parser import BytesFeedParser\n\ndef parse_emails_from_log(log_file: str) -> list[str]:\n subjects = []\n delimiter = b\"=====\"\n wit... | trial_gpt4o_1 | {
"original_instruction": "## Coding Assessment Question\n\n### Problem Statement\nYou are given a log file containing multiple raw email messages, concatenated one after another. Each message is separated by a special delimiter string `\"=====\"`. You need to implement a function `parse_emails_from_log(log_file)`, w... | 0.61563 | Docs: Python310_15423 | C | [
"parse_emails_from_log",
"parse_email_subject"
] | 2 | [
[
"parse_emails_from_log",
"parse_email_subject"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3ae8668bbe23fe2e8898f4af23ecb837d10baa33 | 6504070e58bccd265452164ec2363c9598f82eac | |||
v1.0 | complete | Docs | Docs: Python310_16229_C | import asyncio
from typing import List, Tuple
async def run_commands(commands: List[str]) -> List[Tuple[str, str]]:
""" Execute a list of shell commands concurrently and return their outputs.
Args:
commands (List[str]): List of shell commands to run.
Returns:
List[Tuple[str, str]]: List o... | import asyncio
from typing import List, Tuple
async def run_command(command: str) -> Tuple[str, str]:
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
return (... | import pytest
import asyncio
from solution import run_commands
@pytest.mark.asyncio
async def test_single_command():
commands = ["echo 'Hello, world!'"]
output = await run_commands(commands)
assert output == [("Hello, world!\n", "")]
@pytest.mark.asyncio
async def test_multiple_commands():
commands = ... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def run_command(command: str) -> Tuple[str, str]:\n process = await asyncio.create_subprocess_shell(\n ... | trial_gpt4o_1 | {
"original_instruction": "**Problem Statement:**\n\nYou are tasked with building a concurrent command execution utility utilizing Python's asyncio and subprocess functionalities. The goal is to create a function that takes a list of shell commands, executes them as subprocesses in parallel, and returns their respect... | 0.652169 | Docs: Python310_16229 | C | [
"run_command",
"run_commands"
] | 2 | [
[
"run_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9bb603a24dfb85b069ae902b664923b4b269e1bc | 06c0398b31c912ecc6fa039651f965f38e1085c7 | |||
v1.0 | complete | Docs | Docs: Python310_16596_C | import asyncio
async def run_tcp_server(port: int):
"""
Start and run an asynchronous TCP server.
Args:
- port (int): Port number on which the server should listen.
"""
async def tcp_client(port: int, message: str):
"""
Start and run an asynchronous TCP client.
Args:
- port (int): ... | import asyncio
async def handle_client(reader, writer):
addr = writer.get_extra_info('peername')
print(f"New client connected: {addr}")
welcome_message = "Welcome to the async TCP server!"
writer.write(welcome_message.encode())
await writer.drain()
while True:
data = await reader.read... | import asyncio
import pytest
from solution import run_tcp_server, tcp_client
@pytest.fixture
def event_loop():
loop = asyncio.get_event_loop()
yield loop
loop.close()
@pytest.mark.asyncio
async def test_run_tcp_server(event_loop):
port = 8888
server_task = asyncio.ensure_future(run_tcp_server(port... | [
{
"docstring": null,
"function_declaration": "def main():",
"function_name": "main",
"parameter_list": "()"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n \"\"\"\n Handle individual client connection. Sends a welcome message and echoes received messages.\n... | trial_gpt4o_1 | {
"original_instruction": "**Objective:**\nWrite a Python function that demonstrates the creation and management of an asynchronous TCP server and client using `asyncio`. Your implementation should incorporate creating tasks, handling callbacks, and performing network I/O operations.\n\n#### Task:\n\n1. Implement an ... | 0.655338 | Docs: Python310_16596 | C | [
"handle_client",
"run_tcp_server",
"tcp_client",
"main"
] | 4 | [
[
"run_tcp_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 92d5881c27c837c6c75c8cbd3a87caf1ec442509 | f655a3b0ad0a805b6ec15ddf4f5b7848d8d3c340 | |||
v1.0 | complete | Docs | Docs: Python310_16710_C | import os
class AmbiguousIndentationError(Exception):
""" Custom exception capturing the line number and filename. """
def __init__(self, filename, lineno, line):
super().__init__(f"Ambiguous indentation in {filename} at line {lineno}: {line}")
self.filename = filename
self.lineno = lin... | import os
class AmbiguousIndentationError(Exception):
def __init__(self, filename, lineno, line):
self.filename = filename
self.lineno = lineno
self.line = line
super().__init__(f"Ambiguous indentation in {filename} at line {lineno}: {line}")
def check_file_for_indentation_issues(f... | import os
import pytest
from solution import check_indentation
test_dir = "test_dir"
sub_dir = os.path.join(test_dir, "sub_dir")
os.makedirs(test_dir, exist_ok=True)
os.makedirs(sub_dir, exist_ok=True)
# Create test files
with open(os.path.join(test_dir, "script1.py"), "w", encoding="utf-8") as f:
f.write("if Tru... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\nclass AmbiguousIndentationError(Exception):\n def __init__(self, file_name, line_number, line_content):\n self.file_name = file_name\n sel... | trial_gpt4o_1 | {
"original_instruction": "**Problem Statement:**\n\nYou are required to implement a simplified version of the \"tabnanny\" module to gain a better understanding of recursive file handling and exception management in Python. Your task is to write a program that:\n1. Recursively searches through a given directory for ... | 0.559147 | Docs: Python310_16710 | C | [
"check_file_for_indentation_issues",
"check_indentation"
] | 2 | [
[
"check_indentation",
"check_file_for_indentation_issues"
]
] | 1 | [] | false | [
"AmbiguousIndentationError"
] | true | pytest | true | [] | true | ee09b16ed564413c91caf8c50e520843157222de | 5a134d90b1a7eb4678daa8296755401ec0679c1a | |||
v1.0 | complete | Docs | Docs: Python310_16300_C | import asyncio
from typing import List
async def fetch_data_from_source(source_id: int) -> str:
"""
Simulated function to fetch data from a remote source.
Args:
source_id (int): The ID of the source.
Returns:
str: The data fetched from the source as a string.
"""
await... | import asyncio
from typing import List
async def fetch_data_from_source(source_id: int) -> str:
"""
Simulated function to fetch data from a remote source.
"""
await asyncio.sleep(source_id) # Simulate delay based on source_id
return f"data_from_source_{source_id}"
async def gather_data(sources: L... | import pytest
import asyncio
from solution import fetch_data_from_source, gather_data
@pytest.mark.asyncio
async def test_fetch_data_from_source():
assert await fetch_data_from_source(1) == "data_from_source_1"
assert await fetch_data_from_source(2) == "data_from_source_2"
@pytest.mark.asyncio
async def test_... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List\n\nasync def fetch_data_from_source(source_id: int) -> str:\n \"\"\"\n Simulates fetching data from a remote source.\n ... | trial_gpt4o_2 | {
"original_instruction": "**Title:** Advanced Asynchronous Task Management with asyncio\n\n**Objective:**\nDemonstrate your understanding of Python's asyncio package by implementing a function that concurrently processes data from multiple sources with timeouts and task cancellations.\n\n**Description:**\nYou are ta... | 0.51502 | Docs: Python310_16300 | C | [
"fetch_data_from_source",
"gather_data"
] | 2 | [
[
"gather_data",
"fetch_data_from_source"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d66fff19be5bf26c54f28b50cc1758fe0fc4a058 | fc7d6f2306233feaccad5be84f45d541555ccd4e | |||
v1.0 | complete | Docs | Docs: Python310_16924_C | import os
import shutil
import random
import string
import timeit
import zipfile
def perform_file_operations_and_measure_performance():
""" Perform specific file management operations and measure the performance
of these operations using the given modules in the standard library.
- Create a directory named... | import os
import shutil
import random
import string
import timeit
import zipfile
def create_random_string(length=10):
"""
Generates a random alphanumeric string of given length.
"""
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
def perform_file_operations_and_measure_p... | from solution import perform_file_operations_and_measure_performance
def test_perform_file_operations_and_measure_performance():
# Note: This test checks the execution of the main function and ensures it runs without error.
# Difficult to check print outputs and timings without specific testing frameworks for ... | [
{
"docstring": "Generates a random alphanumeric string of given length.",
"function_declaration": "def create_random_string(length=10):",
"function_name": "create_random_string",
"parameter_list": "(length=10)"
},
{
"docstring": null,
"function_declaration": "def perform_file_operations_... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport shutil\nimport random\nimport string\nimport timeit\nimport zipfile\n\ndef create_random_string(length=10):\n \"\"\"\n Generates a random alphan... | trial_gpt4o_0 | {
"original_instruction": "## Coding Assessment Question\n\n### Objective\n\nYou are required to design a Python program that performs specific file management operations and measures the performance of these operations using the given modules in the standard library.\n\n### Problem\n\nYou need to write a Python scri... | 0.671368 | Docs: Python310_16924 | C | [
"create_random_string",
"perform_file_operations_and_measure_performance"
] | 2 | [
[
"perform_file_operations_and_measure_performance",
"create_random_string"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 77201eecc7b436517a6899e9a4072a4ef6cf8904 | afb86b925cab67c92256f9b136ffcd9a5902171b | |||
v1.0 | complete | Docs | Docs: Python310_16488_C | from typing import List, Dict
def remove_duplicates(words: List[str]) -> List[str]:
"""
Removes duplicate words from the list, preserving the original order.
>>> remove_duplicates(['apple', 'banana', 'apple', 'orange', 'banana', 'grape'])
['apple', 'banana', 'orange', 'grape']
>>> remove_duplicates... | from typing import List, Dict
def remove_duplicates(words: List[str]) -> List[str]:
"""
Removes duplicate words from the list, preserving the original order.
"""
seen = set()
result = []
for word in words:
if word not in seen:
seen.add(word)
result.append(word)
... | from solution import remove_duplicates, word_frequencies, sort_words_by_frequency, transpose_matrix
def test_remove_duplicates():
assert remove_duplicates(['apple', 'banana', 'apple', 'orange', 'banana', 'grape']) == ['apple', 'banana', 'orange', 'grape']
assert remove_duplicates([]) == []
assert remove_du... | [
{
"docstring": "Removes duplicate words from the list, preserving the original order.",
"function_declaration": "def remove_duplicates(words):",
"function_name": "remove_duplicates",
"parameter_list": "(words)"
},
{
"docstring": "Counts the frequency of each word in the list and returns a di... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict\n\ndef remove_duplicates(words: List[str]) -> List[str]:\n \"\"\"\n Removes duplicate words from the list, preserving the original o... | trial_gpt4o_2 | {
"original_instruction": "**Objective:**\nImplement functions to manipulate and transform collections using operations and techniques highlighted in the documentation.\n\n**Question:**\n\nYou are provided with a list of words. Your task is to perform several operations on this list and return the required results. I... | 0.740829 | Docs: Python310_16488 | C | [
"remove_duplicates",
"word_frequencies",
"sort_words_by_frequency",
"transpose_matrix"
] | 4 | [
[
"sort_words_by_frequency",
"word_frequencies"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 330e0ddae1b9319a08e58c9528759e62a1ed009c | 013002e9689b46eaa84e405e0ef01be08149df6e | |||
v1.0 | complete | Docs | Docs: Python310_16560_C | import __future__
def format_version(version):
"""Formats the version tuple into a string with the format MAJOR.MINOR.MICRO-LEVEL."""
if version is None:
return "None"
major, minor, micro, level, _ = version
level_char = level[0].upper() if level else 'F'
return f"{major}.{minor}.{micro}-{l... | import __future__
def format_version(version):
if version is None:
return "None"
major, minor, micro, level, _ = version
level_char = level[0].upper() if level else 'F'
return f"{major}.{minor}.{micro}-{level_char}"
def future_features_info() -> str:
features = [attr for attr in dir(__futu... | from solution import future_features_info
def test_future_features_info_format():
output = future_features_info()
# Check if the output starts with "Feature: " and contains expected attributes
assert "Feature: " in output
assert "Optional: " in output
assert "Mandatory: " in output
assert "Comp... | [
{
"docstring": null,
"function_declaration": "def format_version(version):",
"function_name": "format_version",
"parameter_list": "(version)"
},
{
"docstring": null,
"function_declaration": "def future_features_info():",
"function_name": "future_features_info",
"parameter_list": ... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import __future__\n\ndef format_version(version):\n if version is None:\n return \"None\"\n major, minor, micro, level, _ = version\n level_char = level... | trial_gpt4o_0 | {
"original_instruction": "**Coding Assessment Question:**\n\nYou are required to implement a function `future_features_info()` that extracts and formats information about features from the `__future__` module.\n\n### Function Signature\n```python\ndef future_features_info() -> str:\n```\n\n### Objective\nThe functio... | 0.427523 | Docs: Python310_16560 | C | [
"format_version",
"future_features_info"
] | 2 | [
[
"future_features_info",
"format_version"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1c7df3e36c8e73d30bff7c91eec6af48c2e80042 | ab231cde744500550af4b1806ed2d60a2e5dabb2 | |||
v1.0 | complete | Docs | Docs: Python310_17008_C | def divisible_generator(numbers: list, divisor: int):
"""
A generator function that yields numbers from the input list that are divisible by the given divisor.
Arguments:
numbers : list : a list of integers
divisor : int : the divisor to check divisibility
Yields:
int : numbers fr... | def divisible_generator(numbers: list, divisor: int):
"""
A generator function that yields numbers from the input list that are divisible by the given divisor.
Arguments:
numbers : list : a list of integers
divisor : int : the divisor to check divisibility
Yields:
int : numbers fr... | from solution import divisible_generator, sum_of_divisibles
def test_divisible_generator():
numbers = [10, 20, 33, 46, 50]
divisor = 10
gen = divisible_generator(numbers, divisor)
assert list(gen) == [10, 20, 50]
numbers = [1, 2, 3, 4, 5, 6]
divisor = 2
gen = divisible_generator(number... | [
{
"docstring": "A generator function that yields numbers from the input list that are divisible by the given divisor.\n\nArguments:\nnumbers : list : a list of integers\ndivisor : int : the divisor to check divisibility\n\nYields:\nint : numbers from the input list that are divisible by the divisor",
"func... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def divisible_generator(numbers: list, divisor: int):\n \"\"\"\n A generator function that yields numbers from the input list that are divisible by the given divi... | trial_gpt4o_2 | {
"original_instruction": "### Advanced Coding Assessment Question\n\n**Objective**: Implement a Python function that uses generators to process a sequence of data efficiently.\n\n**Problem Statement**:\nYou are tasked with creating a custom generator function and a utility function that works with this generator. Th... | 0.720868 | Docs: Python310_17008 | C | [
"divisible_generator",
"sum_of_divisibles"
] | 2 | [
[
"sum_of_divisibles",
"divisible_generator"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ca2901647577d68e3147b1defe8fa2eff50b4bee | 7d9c16d3ca430a3810a403f72a006fcdfafbcad1 | |||
v1.0 | complete | Docs | Docs: Python310_16651_C | import asyncio
# Server-side code
async def handle_client(reader, writer):
"""
Handle a client connection, read the message, process and send back the response.
"""
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} f... | import asyncio
# Server-side code
async def handle_client(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} from {addr!r}")
response = message[::-1]
print(f"Send {response!r} to {addr!r}")
writer.wr... | import asyncio
import pytest
from threading import Thread
from solution import run_server, run_client
def start_server_in_thread():
server_thread = Thread(target=run_server, daemon=True)
server_thread.start()
return server_thread
# Run the server once for all tests
server_thread = start_server_in_thread()... | [
{
"docstring": null,
"function_declaration": "def run_server():",
"function_name": "run_server",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def run_client(message):",
"function_name": "run_client",
"parameter_list": "(message)"
}
] | [
0,
0,
0,
0,
1,
1,
1,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\n# Server-side code\nasync def handle_client(reader, writer):\n data = await reader.read(100)\n message = data.decode()\n addr = writer.get_ex... | trial_gpt4o_9 | {
"original_instruction": "### Problem: Asynchronous Server-Client Communication using asyncio\n\nYou are required to implement an asynchronous server-client communication system using Python's `asyncio` package. This task will demonstrate your understanding of event loops, asynchronous tasks, and networking with asy... | 0.697096 | Docs: Python310_16651 | C | [
"handle_client",
"main",
"tcp_client",
"run_server",
"run_client"
] | 5 | [
[
"run_client",
"tcp_client"
],
[
"run_server",
"main"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 352d7fbffd6491423a87491148b749ce316b4fb8 | 1c77e013e3ddd032936b5260b46e736675726866 | |||
v1.0 | complete | Docs | Docs: Python310_17121_C | import aiohttp
import asyncio
async def fetch_webpages(urls: list) -> None:
""" Asynchronously fetch and print the content of multiple web pages concurrently.
>>> urls = ['https://www.example.com', 'https://www.python.org']
>>> await fetch_webpages(urls)
Content from https://www.example.com:
<!doct... | import aiohttp
import asyncio
async def fetch_content(session, url):
try:
async with session.get(url) as response:
response.raise_for_status()
content = await response.text()
print(f"Content from {url}:\n{content[:500]}\n")
except Exception as e:
print(f"Fail... | import asyncio
from unittest.mock import patch, AsyncMock
from solution import fetch_webpages
@patch('aiohttp.ClientSession.get')
def test_fetch_webpages_single_url(mock_get):
mock_response = AsyncMock()
mock_response.text = AsyncMock(return_value="<html>Some content</html>")
mock_response.raise_for_status... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import aiohttp\nimport asyncio\n\nasync def fetch_content(session, url):\n try:\n async with session.get(url) as response:\n response.raise_for_sta... | trial_gpt4o_0 | {
"original_instruction": "### Asynchronous Web Scraping with asyncio (instead of asyncore)\n\n**Objective**: \nYou are required to implement an asynchronous web scraping tool using the `asyncio` package. This tool should be able to fetch and print the content of multiple web pages concurrently.\n\n**Problem Statemen... | 0.573018 | Docs: Python310_17121 | C | [
"fetch_content",
"fetch_webpages"
] | 2 | [
[
"fetch_webpages",
"fetch_content"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 91150e92e7aad0ddea3fb0b088d5067a10f7bbd4 | 6c536dbb6530b7218dcfa1b5633c808f78661221 | |||
v1.0 | complete | Docs | Docs: Python310_17136_C | import math
from typing import List, Generator
def is_prime(n: int) -> bool:
"""
Returns True if n is a prime number, False otherwise.
"""
pass
def prime_generator(numbers: List[int]) -> Generator[int, None, None]:
"""
Generator that yields prime numbers from the given list of numbers.
"""... | import math
def is_prime(n: int) -> bool:
"""
Returns True if n is a prime number, False otherwise.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return F... | import pytest
from solution import is_prime, prime_generator, sum_of_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(29) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-7) == False... | [
{
"docstring": "Returns True if n is a prime number, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generator that yields prime numbers from the given list of numbers.",
"function_declaration": "def p... | [
0,
0,
0,
1,
0,
0,
1,
1,
1,
0
] | 4 | medium | 0.4 | {
"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 Check if a number is a prime number.\n \n Parameters:\n - n (int): The number to check for primality.\n \n ... | trial_gpt4o_7 | {
"original_instruction": "**Title: Implementing and Utilizing Generators in Python**\n\n**Objective:**\nDesign a generator in Python that processes a given list of numbers to yield only those which are prime. Additionally, implement a function that utilizes this generator to return the sum of the first N prime numbe... | 0.724178 | Docs: Python310_17136 | C | [
"is_prime",
"prime_generator",
"sum_of_primes"
] | 3 | [
[
"prime_generator",
"is_prime"
],
[
"sum_of_primes",
"prime_generator"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | be80c1bdea59d411fd6ea17836205fdfc0bc1472 | 4f64f4267de6870d071eecdabdb5399e79f87643 | |||
v1.0 | complete | Docs | Docs: Python310_16991_C | import syslog
def initialize_syslog(ident: str, logoption: int, facility: int) -> None:
"""Initialize the syslog with the provided identifier, log option, and facility."""
def log_message(priority: int, message: str) -> None:
"""Send a log message with a given priority."""
def set_priority_mask(maskpri: int)... | import syslog
_syslog_initialized = False
def initialize_syslog(ident: str, logoption: int, facility: int) -> None:
global _syslog_initialized
syslog.openlog(ident, logoption, facility)
_syslog_initialized = True
def log_message(priority: int, message: str) -> None:
global _syslog_initialized
if ... | import syslog
from solution import initialize_syslog, log_message, set_priority_mask, close_syslog
def test_initialize_syslog():
initialize_syslog('testApp', syslog.LOG_PID, syslog.LOG_USER)
# Verify syslog is initialized by logging a message and inspecting the syslog output (manual step required)
def test_lo... | [
{
"docstring": null,
"function_declaration": "def initialize_syslog(ident, logoption, facility):",
"function_name": "initialize_syslog",
"parameter_list": "(ident, logoption, facility)"
},
{
"docstring": null,
"function_declaration": "def log_message(priority, message):",
"function_n... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import syslog\n\nis_syslog_initialized = False\n\ndef initialize_syslog(ident: str, logoption: int, facility: int) -> None:\n global is_syslog_initialized\n\n sys... | trial_gpt4o_1 | {
"original_instruction": "**Question: Implement a Logging System Using the syslog Module**\n\nYou have been tasked with creating a logging system for a Unix-based application. The logging system needs to handle various types of messages with different levels of severity and send them to appropriate syslog facilities... | 0.605679 | Docs: Python310_16991 | C | [
"initialize_syslog",
"log_message",
"set_priority_mask",
"close_syslog"
] | 4 | [
[
"log_message",
"initialize_syslog"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2097dde8413a4107609a86a3f573a67235589226 | f94c43b60848112d72daf32874323d87fa29c39d | |||
v1.0 | complete | Docs | Docs: Seaborn_17015_C | import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
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 * 0.5) * (n - i) * flip)
def custom_plot(n: int, style: str, context: str, custom_rc: dict = None) -> None:
"""
Gen... | import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
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 * 0.5) * (n - i) * flip)
def custom_plot(n: int, style: str, context: str, custom_rc: dict = None) -> None:
"""
Gen... | import pytest
from solution import custom_plot
def test_valid_custom_plot():
# Basic plot should not raise any exceptions
try:
custom_plot(10, "whitegrid", "talk")
assert True
except Exception as e:
assert False, f"Unexpected exception {e}"
# Testing with custom rc para... | [
{
"docstring": null,
"function_declaration": "def sinplot(n=10, flip=1):",
"function_name": "sinplot",
"parameter_list": "(n=10, flip=1)"
},
{
"docstring": "Generates a custom plot with sine waves.\n\nParameters:\nn (int): Number of sine waves to plot.\nstyle (string): One of seaborn's prede... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\ndef sinplot(n=10, flip=1):\n x = np.linspace(0, 14, 100)\n for i in range(1, n+1):\n... | trial_gpt4o_2 | {
"original_instruction": "**Objective**: Demonstrate your understanding of Seaborn's functionality for controlling figure aesthetics and context by creating a customized visualization.\n\n**Task**:\n1. Create a function named `custom_plot` that:\n - Accepts an integer `n` for the number of sine waves to plot.\n ... | 0.703318 | Docs: Seaborn_17015 | C | [
"sinplot",
"custom_plot"
] | 2 | [
[
"custom_plot",
"sinplot"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"seaborn"
] | false | 53ecd8e45b591b261be129ed4585169c709b383b | 6425c464f9d447c77135c53039f539e69d33c37d | |||
v1.0 | complete | Docs | Docs: Python310_17126_C | def float_string_to_safe_double(float_str: str) -> float:
""" Implement a Python function that mimics the behavior of creating a floating point number from a string and safely converting it into a double.
Args:
float_str (str): A string that is intended to represent a floating point number.
Return... | def PyFloat_Check(float_str):
"""
Mimics checking if a given string can be a valid float.
"""
try:
float(float_str)
return True
except ValueError:
return False
def PyFloat_CheckExact(float_str):
"""
Mimics exact checking if the input string is a valid float.
It b... | from solution import float_string_to_safe_double
def test_valid_float_string():
assert float_string_to_safe_double("123.456") == 123.456
def test_invalid_float_string():
assert float_string_to_safe_double("not_a_float") is None
def test_integer_string():
assert float_string_to_safe_double("100") == 100.0... | [
{
"docstring": "Mimics checking if a given string can be a valid float.",
"function_declaration": "def PyFloat_Check(float_str):",
"function_name": "PyFloat_Check",
"parameter_list": "(float_str)"
},
{
"docstring": "Mimics exact checking if the input string is a valid float.\nIt behaves the ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def float_string_to_safe_double(float_str: str) -> float:\n \"\"\"\n Converts a float string into a double safely.\n \n Args:\n float_str: A string repre... | trial_gpt4o_2 | {
"original_instruction": "**Question**: Implement a Python function that mimics the behavior of creating a floating point number from a string and safely converting it into a double, depending on whether the input is valid. \n\nYour task involves:\n1. Checking if the given input is a valid float string.\n2. Creating... | 0.619943 | Docs: Python310_17126 | C | [
"PyFloat_Check",
"PyFloat_CheckExact",
"PyFloat_FromString",
"PyFloat_AsDouble",
"float_string_to_safe_double"
] | 5 | [
[
"PyFloat_CheckExact",
"PyFloat_Check"
],
[
"PyFloat_FromString",
"PyFloat_CheckExact"
],
[
"float_string_to_safe_double",
"PyFloat_AsDouble"
],
[
"float_string_to_safe_double",
"PyFloat_FromString"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | b824a026d0ee5b6ae2bf87b251b7a974e41684be | f19dbad9430fb56ab04c999826137de29a8ed9d6 | |||
v1.0 | complete | Docs | Docs: Python310_16509_C | from typing import List, Dict, Union, Tuple
def process_lists(list1: List[int], list2: List[int]) -> Dict[str, Union[List[int], Tuple[int, int]]]:
"""Take two lists of integers and return a dictionary with various list operations.
Args:
list1 (List[int]): First list of integers.
list2 (List[int]):... | from typing import List, Dict, Union, Tuple
from math import isqrt
def is_prime(n: int) -> bool:
""" Return True if n is a prime number, else False."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
for i in range(5, isqrt(n) + 1, 6)... | from solution import process_lists
def test_process_lists_basic():
result = process_lists([1, 2, 3, 5], [3, 4, 5, 7])
assert result == {
"merged": [1, 2, 3, 4, 5, 7],
"intersection": [3, 5],
"prime_counts": (3, 3),
"common_diffs": [2, 2, 2, 2]
}
def test_process_lists_no_ov... | [
{
"docstring": "Return True if n is a prime number, else False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Count the number of prime numbers in a given list.",
"function_declaration": "def count_primes(lst):",
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict, Union, Tuple\n\ndef is_prime(n: int) -> bool:\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n return False\n if ... | trial_gpt4o_1 | {
"original_instruction": "### Question: Advanced List Manipulation and Operations\n\nYou are tasked to implement a function named `process_lists` that takes in two lists of integers and returns a dictionary with the following keys and values:\n* `\"merged\"`: A list containing all elements from both input lists, mer... | 0.638344 | Docs: Python310_16509 | C | [
"is_prime",
"count_primes",
"process_lists"
] | 3 | [
[
"count_primes",
"is_prime"
],
[
"process_lists",
"count_primes"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cfdd662aae923184e78945e9f744dfd5eb6ded96 | 148d9c84a05b55ac5349f67cc1cb9d89411e942f | |||
v1.0 | complete | Docs | Docs: Python310_16875_C | from typing import List
def download_and_process(urls: List[str], timeout: int = None) -> List[str]:
""" Downloads content from a set of URLs concurrently and processes the data using multiprocessing.
Args:
urls (List[str]): A list of URLs.
timeout (int, optional): Maximum time limit for the operation.... | from multiprocessing import Pool
import requests
from typing import List
def fetch_content(url):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.text.upper()
except (requests.RequestException, requests.HTTPError) as e:
return f"Error fe... | import pytest
from solution import download_and_process
def test_download_and_process():
# Using example URLs for testing
example_urls = [
"https://www.example.com",
"https://www.nonexistenturl.org" # Invalid URL to test error handling
]
results = download_and_process(example_urls)
... | [
{
"docstring": null,
"function_declaration": "def fetch_content(url):",
"function_name": "fetch_content",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def download_and_process(urls, timeout=None):",
"function_name": "download_and_process",
"parameter... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from multiprocessing import Pool\nimport requests\nfrom typing import List\n\n\ndef fetch_content(url):\n try:\n response = requests.get(url, timeout=10)\n ... | trial_gpt4o_0 | {
"original_instruction": "### Advanced Multiprocessing Task: Web Scraping with Concurrent Downloads\n\n**Problem Statement:**\n\nYou are tasked with writing a Python function that downloads content from a set of URLs concurrently and processes the data using the `multiprocessing` package. The goal is to maximize the... | 0.63666 | Docs: Python310_16875 | C | [
"fetch_content",
"download_and_process"
] | 2 | [
[
"download_and_process",
"fetch_content"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 8f4b62587b72ab0cca55fdee308e29cc57a65d63 | de1ea458148810a5023b804b64d198d33d89e029 | |||
v1.0 | complete | Docs | Docs: Python310_17123_C | import fnmatch
from typing import List
def manage_files(file_list: List[str], commands: List[str]) -> List[str]:
"""
This function takes a list of file paths and a list of command strings.
It processes the commands to return a list of files that should be included based on the rules defined by the commands... | import fnmatch
import os
def match_files(pattern, files):
return [file for file in files if fnmatch.fnmatch(file, pattern)]
def recursive_match_files(directory, pattern, files):
matched_files = []
for file in files:
if file.startswith(directory):
relative_path = file[len(directory):].l... | from solution import manage_files
def test_example_scenario():
files = [
'src/module1.py', 'src/module2.py', 'src/sub/extra.py',
'data/settings.json', 'data/config.yaml',
'scripts/install.py', 'README.md'
]
commands = [
'include *.py',
'exclude data/*',
'r... | [
{
"docstring": null,
"function_declaration": "def match_files(pattern, files):",
"function_name": "match_files",
"parameter_list": "(pattern, files)"
},
{
"docstring": null,
"function_declaration": "def recursive_match_files(directory, pattern, files):",
"function_name": "recursive_m... | [
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 fnmatch\nimport os\n\ndef manage_files(file_list, commands):\n def match(pattern, filename):\n return fnmatch.fnmatch(filename, pattern)\n \n def... | trial_gpt4o_6 | {
"original_instruction": "**Objective:**\n\nImplement a function to manage file inclusion and exclusion based on the provided Unix-style glob patterns.\n\n**Function Signature:**\n```python\ndef manage_files(file_list, commands):\n \"\"\"\n This function takes a list of file paths and a list of command strings... | 0.652778 | Docs: Python310_17123 | C | [
"match_files",
"recursive_match_files",
"manage_files"
] | 3 | [
[
"manage_files",
"match_files"
],
[
"manage_files",
"recursive_match_files"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 19ca036116f4b2eb29b67912cba5e1742fcb86cb | 140d18a03d5f8cfc554880b31f4aaf6be3386eb6 | |||
v1.0 | complete | Docs | Docs: Python310_16736_C | import asyncio
from typing import List, Tuple
async def manage_tasks(queue_type: str, tasks: List[Tuple[int, str, int]]) -> List[str]:
""" Implement an asyncio-based task manager that handles tasks using different types of queues.
Args:
queue_type (str): Type of the queue. Can be "FIFO", "PRIORITY", or... | import asyncio
from typing import List, Tuple, Union
async def worker(queue: asyncio.Queue, completed_tasks: List[str]):
while not queue.empty():
priority, task_name, duration = await queue.get()
await asyncio.sleep(duration)
completed_tasks.append(task_name)
queue.task_done()
asyn... | import pytest
import asyncio
from solution import manage_tasks
@pytest.mark.asyncio
async def test_fifo_queue():
tasks = [(1, "task1", 1), (2, "task2", 1), (3, "task3", 1)]
assert await manage_tasks("FIFO", tasks) == ["task1", "task2", "task3"]
@pytest.mark.asyncio
async def test_priority_queue():
tasks =... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple, Union\n\nasync def worker(queue: asyncio.Queue, completed_tasks: List[str]):\n while not queue.empty():\n prio... | trial_gpt4o_0 | {
"original_instruction": "### Python asyncio Queue Task\n\n#### Objective:\nImplement an asyncio-based task manager that can schedule and execute tasks using different types of queues provided by the `asyncio` module: `Queue`, `PriorityQueue`, and `LifoQueue`.\n\n#### Task Description:\nCreate a Python function `man... | 0.623087 | Docs: Python310_16736 | C | [
"worker",
"manage_tasks"
] | 2 | [
[
"manage_tasks",
"worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8074b8c3557fbce2232cee29c2f60838cf4bd905 | 4da24280ac6b8f1f3a2e2ca168de2537b714d107 | |||
v1.0 | complete | Docs | Docs: Python310_16868_C | import requests
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from typing import List, Dict
def fetch_url(url: str) -> str:
"""
Fetches the content of a given URL.
"""
pass
def fetch_data_concurrently(urls: List[str]) -> Dict[str, float]:
"""
Fetches data f... | import requests
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from typing import List, Dict
def fetch_url(url: str) -> str:
"""
Fetches the content of a given URL.
"""
try:
response = requests.get(url)
response.raise_for_status()
return respo... | from solution import fetch_data_concurrently
def test_fetch_data_concurrently():
# Mock URLs for testing
urls = [
"http://example.com/data1",
"http://example.com/data2",
"http://example.com/data3",
"http://example.com/data4"
]
result = fetch_data_concurrently(urls)
... | [
{
"docstring": "Fetches the content of a given URL.",
"function_declaration": "def fetch_url(url):",
"function_name": "fetch_url",
"parameter_list": "(url)"
},
{
"docstring": "Fetches data from a list of URLs concurrently using ThreadPoolExecutor and ProcessPoolExecutor,\nand returns the tim... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\nimport requests\nimport time\nfrom typing import List, Dict\n\ndef fetch_url(url: str) -> str:\n \"\"\"\n Fetch the content of the give... | trial_gpt4o_1 | {
"original_instruction": "You are given a list of URLs, and your task is to fetch data from these URLs concurrently using the `concurrent.futures` module. The objective is to implement a function that uses both `ThreadPoolExecutor` and `ProcessPoolExecutor` to perform the fetch operation and compare their performanc... | 0.527688 | Docs: Python310_16868 | C | [
"fetch_url",
"fetch_data_concurrently"
] | 2 | [
[
"fetch_data_concurrently",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 94255b068dc8d482ee193837a5c90841231505c1 | 4228052cfc30813e305ae7531480a51b7a9217d9 | |||
v1.0 | complete | Docs | Docs: Python310_17148_C | import asyncio
import contextvars
# Context Variable for holding request ID
request_id_var = contextvars.ContextVar('request_id', default=None)
async def shorten_url(request_id, url):
"""
Asynchronously imitates shortening a URL and logs the request ID and URL.
Args:
request_id (int): The unique requ... | import asyncio
import contextvars
from urllib.parse import urlparse, urljoin
# Context Variable for holding request ID
request_id_var = contextvars.ContextVar('request_id', default=None)
async def shorten_url(request_id, url):
"""
Asynchronously imitates shortening a URL and logs the request ID and URL.
"... | import os
import pytest
import asyncio
from solution import handle_request, request_id_var
@pytest.fixture(autouse=True)
def clean_log_file():
# Ensure the log file is clean before each test
if os.path.exists("requests.log"):
os.remove("requests.log")
yield
# Clean up the log file after each te... | [
{
"docstring": "Logs the request ID and the URL to the 'requests.log' file.",
"function_declaration": "def log_request(request_id, url):",
"function_name": "log_request",
"parameter_list": "(request_id, url)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport contextvars\nimport re\n\n# Context Variable for holding request ID\nrequest_id_var = contextvars.ContextVar('request_id', default=None)\n\nasync... | trial_gpt4o_2 | {
"original_instruction": "#### Objective:\nDesign and implement a Python program utilizing the `contextvars` module to handle context-specific state within an asynchronous framework.\n\n#### Problem Statement:\nYou are tasked with developing a URL shortener service with a basic logging feature. Each request to short... | 0.507333 | Docs: Python310_17148 | C | [
"shorten_url",
"log_request",
"handle_request"
] | 3 | [
[
"handle_request",
"shorten_url"
],
[
"shorten_url",
"log_request"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 53d1eeb7444d302f9dfd28e21bfd0bd431a21d0c | a0bd60e8aa84ab4f093082672676547e1ddae670 | |||
v1.0 | complete | Docs | Docs: Python310_17402_C | import ssl
import socket
from threading import Thread
def setup_server_context():
"""
Sets up the SSL context for the server using TLS and requires client authentication.
"""
pass # Implement the function to setup server SSL context
def handle_client(connection):
"""
Handles communication wit... | import ssl
import socket
from threading import Thread
def setup_server_context():
"""
Sets up the SSL context for the server using TLS and requires client authentication.
"""
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(certfile="server_cert.pem", keyfile="server_key.pe... | import subprocess
from threading import Thread
import time
import socket
import ssl
# Generate a simple self-signed certificate using OpenSSL
def generate_certificates():
subprocess.run([
"openssl", "req", "-new", "-newkey", "rsa:2048", "-days", "1",
"-nodes", "-x509", "-subj", "/C=US/ST=Test/L=Tes... | [
{
"docstring": "Sets up the SSL context for the server using TLS and requires client authentication.",
"function_declaration": "def setup_server_context():",
"function_name": "setup_server_context",
"parameter_list": "()"
},
{
"docstring": "Handles communication with the client.",
"funct... | [
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 ssl\nimport socket\nfrom threading import Thread\n\ndef setup_server_context():\n \"\"\"\n Setup the SSLContext for the server with secure defaults.\n L... | trial_gpt4o_1 | {
"original_instruction": "**Task: Secure Message Transmission Using SSLContext**\n\nIn this task, you are required to implement a Python program that demonstrates secure client-server communication using Python's `ssl` module. Follow the guidelines below to meet the requirements:\n\n### Requirements\n\n1. **SSL Cont... | 0.78143 | Docs: Python310_17402 | C | [
"setup_server_context",
"handle_client",
"start_server",
"setup_client_context",
"start_client"
] | 5 | [
[
"start_client",
"setup_client_context"
],
[
"start_server",
"setup_server_context"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | af99328b9eb8cf1c06cc5bc7a2a34cc7a0dded50 | 03f43ee66ba15c7532e63e4517046af09db69b82 | |||
v1.0 | complete | Docs | Docs: Python310_17481_C | import sys
def log_audit_event(event, args):
"""
Log the audit event to a file.
Parameters:
- event (str): The name of the event.
- args (tuple): The arguments associated with the event.
>>> log_audit_event("test_event", (1, 2, 3))
"""
pass
def setup_audit_hook():
"""
Setu... | import sys
def log_audit_event(event, args):
"""
Log the audit event to a file.
Parameters:
- event (str): The name of the event.
- args (tuple): The arguments associated with the event.
"""
try:
with open("audit_log.txt", "a") as log_file:
log_file.write(f"{event}:... | import os
import sys
import subprocess
from pathlib import Path
def test_log_file_exists():
# Clean up before the test
audit_log = Path("audit_log.txt")
if audit_log.exists():
audit_log.unlink()
# Run the script
subprocess.run([sys.executable, "solution.py"], input="Test Input\n", text... | [
{
"docstring": "Log the audit event to a file.\n\nParameters:\n- event (str): The name of the event.\n- args (tuple): The arguments associated with the event.",
"function_declaration": "def log_audit_event(event, args):",
"function_name": "log_audit_event",
"parameter_list": "(event, args)"
},
{... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\n\ndef log_audit_event(event, args):\n \"\"\"\n Logs the event name and its arguments to a file named 'audit_log.txt'.\n Each event is on a new line... | trial_gpt4o_2 | {
"original_instruction": "**Question: Implement an Audit Event Logger in Python**\n\nPython 3.8 introduced the ability to audit and log events through `sys.audit` calls. This allows developers to monitor certain sensitive actions more closely. For this task, you need to implement an auditing hook that logs specific ... | 0.481696 | Docs: Python310_17481 | C | [
"log_audit_event",
"setup_audit_hook"
] | 2 | [
[
"setup_audit_hook",
"log_audit_event"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | d16f2f22fedcb1af6e16eb4e521d9fca6fa00b67 | 9ffc05158d888393b4b334406de7ae04ff7a2608 | |||
v1.0 | complete | Docs | Docs: Python310_16279_C | import os
import argparse
from datetime import datetime
def list_files(directory, ext=None):
"""List all files in the directory with an optional extension filter."""
pass
def search_file(directory, filename):
"""Search for a specific file by name in the directory."""
pass
def file_details(directory, ... | import os
import argparse
from datetime import datetime
def list_files(directory, ext=None):
try:
files = os.listdir(directory)
if ext:
files = [file for file in files if file.endswith(ext)]
return files
except FileNotFoundError:
print(f"Error: The directory {directo... | import os
import tempfile
import pytest
from datetime import datetime
from solution import list_files, search_file, file_details
# Testing the list_files function
def test_list_files():
with tempfile.TemporaryDirectory() as tmpdir:
dirname = tmpdir
assert list_files(dirname) == []
tmpfile1 ... | [
{
"docstring": null,
"function_declaration": "def list_files(directory, ext=None):",
"function_name": "list_files",
"parameter_list": "(directory, ext=None)"
},
{
"docstring": null,
"function_declaration": "def search_file(directory, filename):",
"function_name": "search_file",
"... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport argparse\nfrom datetime import datetime\n\ndef list_files(directory, ext=None):\n try:\n files = os.listdir(directory)\n if ext:\n ... | trial_gpt4o_0 | {
"original_instruction": "### Advanced Command-Line Interface Application\n\n**Objective:** \nCreate a Python script using the `argparse` module that simulates a file processing utility with advanced command-line argument parsing.\n\n**Problem Statement:**\nYou are tasked with writing a Python script named `file_pro... | 0.674248 | Docs: Python310_16279 | C | [
"list_files",
"search_file",
"file_details",
"main"
] | 4 | [
[
"search_file",
"list_files"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 266be7b1136dbb8af0d26fd01c5260e3fb91b696 | a343329b048f16272cdcb6f3230818aa2c95acf1 | |||
v1.0 | complete | Docs | Docs: Python310_16776_C | import sys
from typing import List, Dict
def handle_command_line_arguments(arguments: List[str]) -> Dict[str, List[str]]:
"""Handles command-line arguments, separating the script name from the other arguments.
>>> handle_command_line_arguments(['script.py', 'arg1', 'arg2'])
{'script_name': 'script.py',... | import sys
import os
def handle_command_line_arguments(arguments):
"""
Handles command-line arguments, separating the script name from the other arguments.
Parameters:
arguments (list of str): List of command-line arguments.
Returns:
dict: A dictionary with 'script_name' a... | import pytest
from solution import handle_command_line_arguments, custom_excepthook, setup_custom_excepthook, audit_hook, add_audit_hook
import sys
import os
def test_handle_command_line_arguments():
args = ['script.py', 'arg1', 'arg2']
expected_output = {'script_name': 'script.py', 'arguments': ['arg1', 'arg2... | [
{
"docstring": "Handles command-line arguments, separating the script name from the other arguments.\n\nParameters:\n arguments (list of str): List of command-line arguments.\n \nReturns:\n dict: A dictionary with 'script_name' and 'arguments'.",
"function_declaration": "def handle_command_line_arg... | [
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 sys\nimport os\n\ndef handle_command_line_arguments(arguments):\n \"\"\"\n Handles command-line arguments, separating the script name from the other argume... | trial_gpt4o_0 | {
"original_instruction": "**Objective:** \n\nTo assess the student's understanding of Python's `sys` module, specifically dealing with command-line arguments, exception handling, and auditing hooks.\n\n### Problem Statement:\n\nYou are required to create a Python script that uses functionalities from the `sys` modul... | 0.578217 | Docs: Python310_16776 | C | [
"handle_command_line_arguments",
"custom_excepthook",
"setup_custom_excepthook",
"audit_hook",
"add_audit_hook"
] | 5 | [
[
"add_audit_hook",
"audit_hook"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 78c649b637188916c855deb4acdd00ffbf105347 | 352695cc5e691b95a32da239f42f94573ec9b1f6 | |||
v1.0 | complete | Docs | Docs: Scikit_17361_C | def stream_data(file_path, batch_size):
"""
Streams data from a file in mini-batches.
Parameters:
file_path (str): Path to the input text file.
batch_size (int): Number of lines to read per batch.
Yields:
List[str]: A batch of lines from the file.
"""
pass
def extract_features(dat... | import numpy as np
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
def stream_data(file_path, batch_size):
"""
Streams data from a file in mini-batches.
Parameters:
file_path (str): Path to the inpu... | import numpy as np
import os
from solution import stream_data, extract_features, incremental_learning
def test_stream_data(tmpdir):
# Create a temporary file with sample data
file_path = os.path.join(tmpdir, 'sample.txt')
lines = [f"Line {i}\n" for i in range(100)]
with open(file_path, 'w') as f:
... | [
{
"docstring": "Streams data from a file in mini-batches.\n\nParameters:\nfile_path (str): Path to the input text file.\nbatch_size (int): Number of lines to read per batch.\n\nYields:\nList[str]: A batch of lines from the file.",
"function_declaration": "def stream_data(file_path, batch_size):",
"funct... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_... | trial_gpt4o_4 | {
"original_instruction": "**Incremental Learning with Scikit-learn**\n\n**Objective:** \nDesign and implement a pipeline for handling and learning from a large dataset that does not fit into memory using scikit-learn. This will involve:\n1. Streaming data from a file or generated data.\n2. Extracting features using ... | 0.510052 | Docs: Scikit_17361 | C | [
"stream_data",
"extract_features",
"incremental_learning"
] | 3 | [
[
"incremental_learning",
"extract_features"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 1fe17e8ba2cd0620998796ae3c2f095069bd7699 | b359698ea81737c84922f2396c7025dc3e03f037 | |||
v1.0 | complete | Docs | Docs: Python310_16824_C | import argparse
import re
users = []
def create_user(args):
"""Create a new user with specified name, age, and email.
Use the following command to create a user:
>>> python userdb.py create --name "John Doe" --age 30 --email john@example.com
"""
...
def delete_user(args):
"""Delete an existin... | import argparse
import re
users = []
def valid_email(email):
regex = r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'
return re.match(regex, email)
def create_user(args):
global users
name = args.name
age = args.age
email = args.email
if not valid_email(email):
print(f"Error: ... | import pytest
from io import StringIO
import sys
from solution import users, create_user, delete_user, update_age, list_users
@pytest.fixture
def reset_users():
global users
users.clear()
yield
users.clear()
def test_create_user(reset_users):
args = argparse.Namespace(name="John Doe", age=30, emai... | [
{
"docstring": null,
"function_declaration": "def valid_email(email):",
"function_name": "valid_email",
"parameter_list": "(email)"
},
{
"docstring": null,
"function_declaration": "def create_user(args):",
"function_name": "create_user",
"parameter_list": "(args)"
},
{
"d... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import argparse\nimport re\n\nusers = []\n\ndef valid_email(email):\n regex = r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'\n return re.match(regex, email)... | trial_gpt4o_0 | {
"original_instruction": "As a developer, you need to create a command-line utility for processing a database of user data. The utility should support the following functionalities:\n1. **Create a new user** with a name, age, and email.\n2. **Delete an existing user** by email.\n3. **Update the age** of an existing ... | 0.566298 | Docs: Python310_16824 | C | [
"valid_email",
"create_user",
"delete_user",
"update_age",
"list_users",
"main"
] | 6 | [
[
"create_user",
"valid_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2dcbbb49ebf68faeae7a359baae712ab7acc9400 | 89891a380f2efdd97cee3f5311eeecafba5be12b | |||
v1.0 | complete | Docs | Docs: Python310_17466_C | import time
def measure_function_runtime(func):
""" Measures the runtime of a given function.
>>> def quick_func():
... pass
>>> measure_function_runtime(quick_func) < 0.1
True
>>> def slow_func():
... time.sleep(1)
>>> measure_function_runtime(slow_func) >= 1
True
"""
... | import time
def measure_function_runtime(func):
"""
Measures the runtime of a given function.
"""
start_time = time.time()
func()
end_time = time.time()
return end_time - start_time
def convert_to_gmt(struct_time_obj):
"""
Converts a local struct_time object to a GMT time string.
... | import time
from solution import measure_function_runtime, convert_to_gmt
def test_measure_function_runtime():
def quick_func():
pass
def slow_func():
time.sleep(1)
quick_time = measure_function_runtime(quick_func)
slow_time = measure_function_runtime(slow_func)
assert quick_time... | [
{
"docstring": "Measures the runtime of a given function.",
"function_declaration": "def measure_function_runtime(func):",
"function_name": "measure_function_runtime",
"parameter_list": "(func)"
},
{
"docstring": "Converts a local struct_time object to a GMT time string.",
"function_decl... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\n\ndef get_current_local_time():\n \"\"\"\n Returns the current local time in the format \"YYYY-MM-DD HH:MM:SS\".\n \"\"\"\n return time.strftim... | trial_gpt4o_1 | {
"original_instruction": "#### Objective\nImplement a Python script that utilizes the `time` module to perform and measure various time-related tasks efficiently.\n\n#### Description\nYou are required to implement a program that performs the following tasks:\n\n1. **Get Current Time:**\n - Print the current local ... | 0.570792 | Docs: Python310_17466 | C | [
"measure_function_runtime",
"convert_to_gmt",
"compare_performance"
] | 3 | [
[
"compare_performance",
"measure_function_runtime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | da35377eb4b11d8021741d2d2e3409203c0474df | cfe14944de263a6976cd0f4669b55a625fcd3774 | |||
v1.0 | complete | Docs | Docs: Python310_16406_C | import os
from typing import List, Dict, Tuple, Optional
MAILCAP_FILES = [
os.path.expanduser('~/.mailcap'),
'/etc/mailcap',
'/usr/etc/mailcap',
'/usr/local/etc/mailcap'
]
def read_mailcap_file(filepath: str) -> Dict[str, List[Dict[str, str]]]:
"""
Reads and parses a mailcap file, returning a ... | import os
MAILCAP_FILES = [
os.path.expanduser('~/.mailcap'),
'/etc/mailcap',
'/usr/etc/mailcap',
'/usr/local/etc/mailcap'
]
def read_mailcap_file(filepath):
caps = {}
try:
with open(filepath, 'r') as file:
for line in file:
line = line.strip()
... | from solution import getcaps, findmatch, read_mailcap_file
import pytest
def test_getcaps():
caps = getcaps()
assert type(caps) is dict
assert 'video/mpeg' in caps or 'text/plain' in caps # Depending on system mailcap files
def test_findmatch_view():
test_caps = {
'video/mpeg': [{'view': 'xmp... | [
{
"docstring": null,
"function_declaration": "def read_mailcap_file(filepath):",
"function_name": "read_mailcap_file",
"parameter_list": "(filepath)"
},
{
"docstring": null,
"function_declaration": "def getcaps():",
"function_name": "getcaps",
"parameter_list": "()"
},
{
... | [
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 os\n\ndef getcaps():\n \"\"\"\n Reads and parses mailcap files on the system to return a dictionary\n mapping MIME types to lists of mailcap file entrie... | trial_gpt4o_3 | {
"original_instruction": "### Question: Implementing MIME Type Matching in Mailcap\n\nYou are tasked to implement a simplified version of Python's `mailcap` module. Specifically, you need to define two functions to handle MIME type entries and match them to appropriate commands.\n\n#### Step 1: Implement the `getcap... | 0.505046 | Docs: Python310_16406 | C | [
"read_mailcap_file",
"getcaps",
"findmatch"
] | 3 | [
[
"getcaps",
"read_mailcap_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 441352d57d9d6a14b685f978738879a1ea13320f | a08caaa7da91e6c431156f8126a7bff6f4a8bc88 | |||
v1.0 | complete | Docs | Docs: Python310_17765_C | import asyncio
async def handle_client(reader, writer):
"""
Handle a connected client.
Continuously read messages from the client and broadcast them to all connected clients.
Handle client disconnection gracefully.
"""
# Your implementation here...
async def start_chat_server(host='127.0.0.1',... | import asyncio
clients = []
async def handle_client(reader, writer):
addr = writer.get_extra_info('peername')
clients.append(writer)
print(f"{addr} is connected")
try:
while True:
data = await reader.read(100)
message = data.decode()
if not message:
... | import asyncio
import pytest
from sys import platform
from solution import start_chat_server
async def client_dummy(host, port, message):
reader, writer = await asyncio.open_connection(host, port)
writer.write(message.encode())
await writer.drain()
data = await reader.read(100)
received_message = d... | [] | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import asyncio\n\nconnected_clients = []\n\nasync def handle_client(reader, writer):\n client_address = writer.get_extra_info('peername')\n ... | trial_gpt4o_2 | {
"original_instruction": "### Mini Chat Server using `asyncio` Streams\n\n#### Objective:\nDesign and implement a mini chat server using `asyncio` streams. The server should be able to handle multiple clients simultaneously, broadcast messages from any client to all connected clients, and properly manage connection ... | 0.555607 | Docs: Python310_17765 | C | [
"handle_client",
"broadcast",
"start_chat_server"
] | 3 | [
[
"handle_client",
"broadcast"
],
[
"start_chat_server",
"handle_client"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9fdc15183b6c0af47bd89af08550ed3906e0fa52 | 142f1d669c28639be135ec2a17983e8fb29d5af6 | |||
v1.0 | complete | Docs | Docs: Pytorch_16912_C | import os
import torch.distributed as dist
def initialize_distributed_training(nnodes: int, nproc_per_node: int, rdzv_id: str, rdzv_backend: str, rdzv_endpoint: str):
"""
Initializes the distributed training environment with given arguments.
"""
pass
def manage_fault_tolerance(max_restarts: int):
... | import os
import torch.distributed as dist
import logging
logging.basicConfig(level=logging.INFO)
def initialize_distributed_training(nnodes: int, nproc_per_node: int, rdzv_id: str, rdzv_backend: str, rdzv_endpoint: str):
"""
Initializes the distributed training environment with given arguments.
"""
... | import pytest
import os
from unittest.mock import patch, MagicMock
import solution
@pytest.fixture
def patch_os_system():
with patch("os.system") as mock_system:
yield mock_system
@pytest.fixture
def patch_torch_distributed_init():
with patch("torch.distributed.init_process_group") as mock_init:
... | [
{
"docstring": "Initializes the distributed training environment with given arguments.",
"function_declaration": "def initialize_distributed_training(nnodes, nproc_per_node, rdzv_id, rdzv_backend, rdzv_endpoint):",
"function_name": "initialize_distributed_training",
"parameter_list": "(nnodes, nproc... | [
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 os\nimport logging\nimport torch.distributed as dist\nfrom torch.distributed.elastic.multiprocessing.errors import record\n\nlogging.basicConfig(level=logging.IN... | trial_gpt4o_9 | {
"original_instruction": "### Distributed Training and Fault Tolerance with PyTorch\n\nYou have been tasked with writing a Python script that implements a basic distributed training setup using PyTorch. Your goal is to design a flexible and fault-tolerant distributed training mechanism. \n\n#### Requirements:\n1. **... | 0.448266 | Docs: Pytorch_16912 | C | [
"initialize_distributed_training",
"manage_fault_tolerance",
"handle_scaling_events",
"main",
"run_training"
] | 5 | [
[
"manage_fault_tolerance",
"run_training"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 994e0392dcc1c46a02ce5618cae4d673bd2c1b39 | 7ea696ee4125827ada8ce1b15fa8de7dde260913 | |||
v1.0 | complete | Docs | Docs: Pytorch_17493_C | import torch
def create_view(t, new_rows, new_cols):
"""
Create a view of tensor t with shape (new_rows, new_cols).
"""
pass
def is_contiguous(t):
"""
Check if the tensor t is contiguous.
"""
pass
def make_contiguous(t):
"""
Return a contiguous version of tensor t.
"""
... | import torch
def create_view(t, new_rows, new_cols):
"""
Create a view of tensor t with shape (new_rows, new_cols).
"""
return t.view(new_rows, new_cols)
def is_contiguous(t):
"""
Check if the tensor t is contiguous.
"""
return t.is_contiguous()
def make_contiguous(t):
"""
Ret... | from solution import create_view, is_contiguous, make_contiguous, process_tensor
import torch
def test_create_view():
t = torch.tensor([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
expected = torch.tensor([[ 1, 2, 3, 4, 5,... | [
{
"docstring": "Create a view of tensor t with shape (new_rows, new_cols).",
"function_declaration": "def create_view(t, new_rows, new_cols):",
"function_name": "create_view",
"parameter_list": "(t, new_rows, new_cols)"
},
{
"docstring": "Check if the tensor t is contiguous.",
"function_... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef create_view(t, new_rows, new_cols):\n \"\"\"\n Creates a view of tensor `t` with shape `(new_rows, new_cols)`.\n \"\"\"\n return t.view(... | trial_gpt4o_9 | {
"original_instruction": "### Question: Tensor Views and Contiguity in PyTorch\n\nIn this exercise, you will demonstrate your understanding of tensor views and contiguity in PyTorch by implementing a series of operations that optimize memory usage and evaluate tensor properties.\n\n#### Task:\n\n1. Write a function ... | 0.557619 | Docs: Pytorch_17493 | C | [
"create_view",
"is_contiguous",
"make_contiguous",
"process_tensor"
] | 4 | [
[
"process_tensor",
"create_view"
],
[
"process_tensor",
"is_contiguous"
],
[
"process_tensor",
"make_contiguous"
]
] | 3 | [] | false | [] | false | pytest | true | [
"torch"
] | false | c79c273e0052b701e62074239f42d90c1d30debb | c16bcd71ef40ef373d42df08845b56bfb29089df | |||
v1.0 | complete | Docs | Docs: Scikit_17745_C | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
def preprocess_data(file_path):
"""
Loads and preprocesses the data.
- Loads the dataset into a pandas Data... | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
def preprocess_data(file_path):
"""
Loads and preprocesses th... | import pandas as pd
import numpy as np
from sklearn.datasets import make_regression
from io import StringIO
from solution import preprocess_data, train_and_evaluate
def create_mock_csv():
"""
Creates a mock CSV file-like object for testing.
"""
X, y = make_regression(n_samples=100, n_features=8, noise=... | [
{
"docstring": "Loads and preprocesses the data.",
"function_declaration": "def preprocess_data(file_path):",
"function_name": "preprocess_data",
"parameter_list": "(file_path)"
},
{
"docstring": "Trains and evaluates a regression model on the provided dataset.",
"function_declaration": ... | [
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\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LinearRegr... | trial_gpt4o_3 | {
"original_instruction": "Supervised Learning with Scikit-Learn\n\n**Objective**: This question aims to assess your ability to preprocess data, implement a supervised learning algorithm using scikit-learn, and evaluate the model's performance.\n\n**Scenario**: You are provided with a dataset containing information a... | 0.763032 | Docs: Scikit_17745 | C | [
"preprocess_data",
"train_and_evaluate"
] | 2 | [
[
"train_and_evaluate",
"preprocess_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 2a0b3015366171de6387ae4f5e80e10755ab9b0a | c02e6fb3a57a4d9200c0ffde19e1ab451bf2c443 | |||
v1.0 | complete | Docs | Docs: Scikit_17205_C | import numpy as np
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture, BayesianGaussianMixture
def generate_synthetic_data():
""" Generate a synthetic dataset with three distinct clusters,
each following a Gaussian distribution with different means and covariance matrices.
The data... | import numpy as np
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture, BayesianGaussianMixture
# Task 1: Generate Dataset
np.random.seed(42)
def generate_synthetic_data():
# Means of the clusters
mean1 = [0, 0]
mean2 = [5, 5]
mean3 = [10, 0]
# Covariance matrices of the c... | def test_generate_synthetic_data():
data = generate_synthetic_data()
assert data.shape == (300, 2)
def test_gmm_optimal_components():
assert optimal_n_components == 3 # Expecting 3 distinct clusters
def test_gmm_bic_scores():
assert len(bic_scores) == 6
assert np.argmin(bic_scores) == 2 # Index ... | [
{
"docstring": null,
"function_declaration": "def generate_synthetic_data():",
"function_name": "generate_synthetic_data",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def plot_gmm_results(X, labels, gmm):",
"function_name": "plot_gmm_results",
"paramet... | [
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 numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.mixture import GaussianMixture, BayesianGaussianMixture\n\n# Set the random seed for reproducibility\n... | trial_gpt4o_7 | {
"original_instruction": "You are required to demonstrate your understanding of Gaussian Mixture Models (GMM) and Bayesian Gaussian Mixture Models (BGMM) using scikit-learn. Follow the tasks below to design and analyze a dataset using these models.\n\n### Tasks:\n1. **Generate a Synthetic Dataset**:\n - Use `numpy... | 0.629941 | Docs: Scikit_17205 | C | [
"generate_synthetic_data",
"plot_gmm_results",
"draw_ellipse"
] | 3 | [
[
"plot_gmm_results",
"draw_ellipse"
]
] | 1 | [] | false | [] | false | pytest | false | [
"matplotlib",
"numpy",
"sklearn"
] | false | 77fda78cd3f6505eb2e59e1fa2e168dcc3fe5bb7 | e8e968006d9c7362ea9d4b16e0e678f2a15f9cef | |||
v1.0 | complete | Docs | Docs: Python310_17815_C | import random
import timeit
# Sorting Algorithms
def insertion_sort(arr):
"""Sort the array using insertion sort algorithm."""
# Implement the insertion sort
def merge_sort(arr):
"""Sort the array using merge sort algorithm."""
# Implement the merge sort
def quick_sort(arr):
"""Sort the array usi... | import random
import timeit
# Sorting Algorithms
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def merge_sort(arr):
if len(arr) > 1:
mid = l... | from solution import insertion_sort, merge_sort, quick_sort_wrapper
import random
def test_insertion_sort():
arr = generate_specific_random_list()
sorted_arr = sorted(arr)
insertion_sort(arr)
assert arr == sorted_arr
def test_merge_sort():
arr = generate_specific_random_list()
sorted_arr = sor... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"doc... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport timeit\n\n# Sorting Algorithms\ndef insertion_sort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while... | trial_gpt4o_0 | {
"original_instruction": "#### Objective\nYour task is to create a utility that benchmarks different sorting algorithms using the `timeit` module. This will test your understanding of `timeit` and ability to write code that leverages this module to compare performance accurately.\n\n#### Requirements and Constraints... | 0.581326 | Docs: Python310_17815 | C | [
"insertion_sort",
"merge_sort",
"quick_sort",
"quick_sort_wrapper",
"generate_random_list",
"benchmark_sorting_algorithms"
] | 6 | [
[
"quick_sort_wrapper",
"quick_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e85507960fd240b93ea1d471ae3a4cd6e5591c64 | 5e5b7f0031a421482ada7a1d83308fb0d219ae06 | |||
v1.0 | complete | Docs | Docs: Scikit_17698_C | import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import validation_curve, learning_curve
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.utils import shuffle
def plot_validation_curve(X_train, y_train, param_range):
""" Plot the validation curve for a ... | import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import validation_curve, learning_curve
from sklearn.datasets import load_iris
from sklearn.utils import shuffle
import matplotlib.pyplot as plt
def plot_validation_curve(X_train, y_train, param_range):
train_scores, valid_scores = validat... | from solution import plot_validation_curve, plot_learning_curve
from sklearn.datasets import load_iris
from sklearn.utils import shuffle
import numpy as np
def test_plot_validation_curve_execution():
X, y = load_iris(return_X_y=True)
X, y = shuffle(X, y, random_state=0)
param_range = np.logspace(-7, 3... | [
{
"docstring": null,
"function_declaration": "def plot_validation_curve(X_train, y_train, param_range):",
"function_name": "plot_validation_curve",
"parameter_list": "(X_train, y_train, param_range)"
},
{
"docstring": null,
"function_declaration": "def plot_learning_curve(X_train, y_trai... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import validation_curve, learning_curve\nfrom sklearn.datasets import load_iris\nfrom skle... | trial_gpt4o_0 | {
"original_instruction": "#### Objective:\nIn this assignment, you are required to demonstrate your understanding of both validation and learning curves in the scikit-learn package. You will implement functions to plot these curves and analyze the results to diagnose a machine learning model.\n\n#### Problem Stateme... | 0.663123 | Docs: Scikit_17698 | C | [
"plot_validation_curve",
"plot_learning_curve",
"analyze_model"
] | 3 | [
[
"analyze_model",
"plot_learning_curve"
],
[
"analyze_model",
"plot_validation_curve"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"sklearn"
] | false | 1293e191f616b6c865fd5c2a4d5b29bca7816812 | d2ebc0c22b78ecdead541063086fc80ff6c899ec | |||
v1.0 | complete | Docs | Docs: Python310_17707_C | import asyncio
from concurrent.futures import ThreadPoolExecutor
async def fetch_news_source(source_id):
""" Asynchronously fetches news from a given source.
Simulates a delay proportional to the source_id and returns a dummy article.
Args:
source_id (int): The ID of the news source.
Returns:... | import asyncio
from concurrent.futures import ThreadPoolExecutor
import logging
logging.basicConfig(level=logging.DEBUG)
async def fetch_news_source(source_id):
"""
Asynchronously fetches news from a given source.
Simulates a delay proportional to the source_id and returns a dummy article.
"""
try... | import pytest
from solution import fetch_news_source, fetch_all_news, fetch_news_with_cpu_bound_task
@pytest.mark.asyncio
async def test_fetch_news_source():
result = await fetch_news_source(1)
assert result["source_id"] == 1
assert "article" in result
@pytest.mark.asyncio
async def test_fetch_all_news():... | [
{
"docstring": "Dummy CPU-bound task that squares the source_id.",
"function_declaration": "def cpu_bound_task(source_id):",
"function_name": "cpu_bound_task",
"parameter_list": "(source_id)"
},
{
"docstring": null,
"function_declaration": "def fetch_news_with_cpu_bound_task_wrapper(num_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom concurrent.futures import ProcessPoolExecutor\n\nasync def fetch_news_source(source_id):\n \"\"\"\n Simulates fetching a news article from a ... | trial_gpt4o_2 | {
"original_instruction": "### Asynchronous News Fetcher\n\n**Objective**:\nYou are tasked with implementing an asynchronous news fetcher that collects news articles from multiple sources concurrently. Some of the fetching operations are CPU-intensive and must be handled without blocking the event loop.\n\n**Requirem... | 0.562069 | Docs: Python310_17707 | C | [
"fetch_news_source",
"fetch_all_news",
"cpu_bound_task",
"fetch_news_with_cpu_bound_task",
"main",
"fetch_news_with_cpu_bound_task_wrapper"
] | 6 | [
[
"fetch_all_news",
"fetch_news_source"
],
[
"fetch_news_with_cpu_bound_task",
"cpu_bound_task"
],
[
"fetch_news_with_cpu_bound_task_wrapper",
"main"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ab8e243b7c461121981765d599751a1023d39312 | 8861c474802309776814d9757c8c299777d03821 | |||
v1.0 | complete | Docs | Docs: Scikit_17740_C | import numpy as np
import scipy.sparse as sp
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
import time
import sklearn
def sparsity_ratio(X):
""" Calculate the sparsity ratio of a given sparse matrix X.
>>> sparsity_ratio(csr_matrix(np.array([[1, 0, 0], [0, 0, 1], [1,... | import numpy as np
import scipy.sparse as sp
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
import time
import sklearn
def sparsity_ratio(X):
return 1.0 - np.count_nonzero(X.toarray()) / float(X.shape[0] * X.shape[1])
def classify_and_optimize(X_train, y_train, X_test, y... | import numpy as np
from scipy.sparse import csr_matrix
from solution import classify_and_optimize, sparsity_ratio
def test_sparsity_ratio():
dense_matrix = np.array([[1, 0, 0], [0, 0, 1], [1, 0, 0]])
sparse_matrix = csr_matrix(dense_matrix)
ratio = sparsity_ratio(sparse_matrix)
assert ratio == 0.666666... | [
{
"docstring": null,
"function_declaration": "def sparsity_ratio(X):",
"function_name": "sparsity_ratio",
"parameter_list": "(X)"
},
{
"docstring": null,
"function_declaration": "def classify_and_optimize(X_train, y_train, X_test, y_test):",
"function_name": "classify_and_optimize",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport scipy.sparse as sp\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\nimport time\nimport sklearn\n... | trial_gpt4o_0 | {
"original_instruction": "#### Objective:\nImplement a `sklearn.linear_model.SGDClassifier` model to classify a provided dataset while optimizing for prediction latency and memory usage. You will need to utilize sparse matrix representations and configure scikit-learn’s settings to limit validation overhead and work... | 0.667713 | Docs: Scikit_17740 | C | [
"sparsity_ratio",
"classify_and_optimize"
] | 2 | [
[
"classify_and_optimize",
"sparsity_ratio"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy",
"sklearn"
] | false | 669105d9fd646f95f60a7147d232c79338dbed16 | 7a551b1b4ed6a64d4fc33a3c3a25c88c664e960f | |||
v1.0 | complete | Docs | Docs: Python310_17871_C | import random
from typing import List, Dict
def initialize_bag(ball_counts: Dict[str, int]) -> list:
"""
Initialize the bag of balls.
Parameters:
ball_counts (dict): A dictionary where keys are colors (str) and values are counts (int) of balls.
Returns:
list: A list where each element is a ba... | import random
def initialize_bag(ball_counts: dict) -> list:
"""
Initialize the bag of balls.
Parameters:
ball_counts (dict): A dictionary where keys are colors (str) and values are counts (int) of balls.
Returns:
list: A list where each element is a ball (represented by its color as a string... | from solution import initialize_bag, draw_balls, shuffle_bag, generate_statistics
def test_initialize_bag():
assert initialize_bag({'red': 5, 'blue': 3, 'green': 2}) == ['red']*5 + ['blue']*3 + ['green']*2
def test_draw_balls():
bag = ['red', 'red', 'blue', 'green']
drawn = draw_balls(bag, 2)
assert l... | [
{
"docstring": "Initialize the bag of balls.\n\nParameters:\nball_counts (dict): A dictionary where keys are colors (str) and values are counts (int) of balls.\n\nReturns:\nlist: A list where each element is a ball (represented by its color as a string) based on the input counts.",
"function_declaration": "... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom collections import Counter\n\ndef initialize_bag(ball_counts: dict) -> list:\n \"\"\"\n Initialize the bag of balls.\n\n Parameters:\n b... | trial_gpt4o_1 | {
"original_instruction": "#### Objective:\nYou are required to create a Python script using the `random` module to simulate drawing balls from a bag. The bag contains balls of different colors, and you will perform various random operations to demonstrate your understanding of the module's functionalities.\n\n#### T... | 0.599039 | Docs: Python310_17871 | C | [
"initialize_bag",
"draw_balls",
"shuffle_bag",
"generate_statistics"
] | 4 | [
[
"generate_statistics",
"draw_balls"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b4e71aeabdafd5e1066b3c839683a2b4ee6a49b8 | cc8531b146c9ce4b5d34d3348456c6354b6ebd1b | |||
v1.0 | complete | Docs | Docs: Python310_18003_C | from contextlib import contextmanager, ExitStack
@contextmanager
def resource_manager(resource_name):
"""
Context manager that acquires and releases a resource.
Args:
resource_name (str): The name of the resource to acquire.
Yields:
str: The name of the acquired resource.
Example... | from contextlib import contextmanager, ExitStack
@contextmanager
def resource_manager(resource_name):
"""
Context manager that acquires and releases a resource.
Args:
resource_name (str): The name of the resource to acquire.
Yields:
str: The name of the acquired resource.
"""
... | # To properly test the solution, create a test file named test_solution.py with the following code:
from solution import resource_manager, conditional_resource_manager
import pytest
def test_resource_manager():
with resource_manager("test_resource") as resource:
assert resource == "test_resource"
def test... | [
{
"docstring": "Context manager that acquires and releases a resource.\n\nArgs:\nresource_name (str): The name of the resource to acquire.\n\nYields:\nstr: The name of the acquired resource.",
"function_declaration": "def resource_manager(resource_name):",
"function_name": "resource_manager",
"param... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from contextlib import contextmanager, ExitStack\n\n@contextmanager\ndef resource_manager(resource_name):\n \"\"\"\n A context manager that acquires and releases ... | trial_gpt4o_2 | {
"original_instruction": "### Context Management with Python's `contextlib`\n\n#### Objective:\nImplement a custom context manager using `contextlib`'s `contextmanager` decorator that maintains a stack of resources and ensures their proper release. Additionally, implement a mechanism that supports conditional resour... | 0.350594 | Docs: Python310_18003 | C | [
"resource_manager",
"conditional_resource_manager"
] | 2 | [
[
"conditional_resource_manager",
"resource_manager"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c63898247dd55b51eef66ebafbe23b7959b3d293 | c13e8d0318cc2fa70a0832e63437ec0db56c6f44 | |||
v1.0 | complete | Docs | Docs: Scikit_17350_C | import numpy as np
from sklearn.base import BaseEstimator
from typing import Tuple, List, Dict, Any
def load_preprocess_data(file_path: str) -> Tuple[np.ndarray, np.ndarray]:
"""
Load and preprocess the dataset from the given file path.
Args:
- file_path (str): Path to the dataset file.
R... | import numpy as np
import pandas as pd
import time
from typing import Tuple, Dict, Any, List
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_erro... | import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor
# Assuming 'solution' is the module name where above functions are defined
from solution import load_preprocess_data, train_evaluate_model, compare_models, optimize_model_... | [
{
"docstring": "Load and preprocess the dataset from the given file path.\n\nArgs:\n- file_path (str): Path to the dataset file.\n\nReturns:\n- Tuple[np.ndarray, np.ndarray]: Features and target arrays.",
"function_declaration": "def load_preprocess_data(file_path):",
"function_name": "load_preprocess_d... | [
1,
0,
0,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport pandas as pd\nimport time\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.svm import SVR\nfrom sklearn.ensemble import Rando... | trial_gpt4o_6 | {
"original_instruction": "**Question: Optimizing Prediction Latency and Throughput with scikit-learn**\n\n**Problem Statement:**\n\nYou are provided with a dataset and a requirement to build a machine learning pipeline in scikit-learn, focusing on optimizing prediction latency and throughput. Your task is to impleme... | 0.686788 | Docs: Scikit_17350 | C | [
"load_preprocess_data",
"train_evaluate_model",
"compare_models",
"optimize_model_performance"
] | 4 | [
[
"compare_models",
"train_evaluate_model"
],
[
"optimize_model_performance",
"compare_models"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 8d7947bb806da32b9d7f100f1500fcc2f63c9ca5 | ba7ef9025969a64f897d15f3b910bd7898d3f38c | |||
v1.0 | complete | Docs | Docs: Python310_17778_C | import asyncio
import time
async def task_1(seconds: int, name: str) -> str:
""" Coroutine that sleeps for a specified number of seconds and returns a message.
Args:
seconds (int): Number of seconds to sleep.
name (str): Name of the task.
Returns:
str: Completion message i... | import asyncio
import time
async def task_1(seconds: int, name: str) -> str:
await asyncio.sleep(seconds)
return f"Task {name} completed after {seconds} seconds."
async def task_2(name: str) -> str:
for i in range(1000):
if i % 100 == 0:
await asyncio.sleep(0)
return f"Task {name} ... | import pytest
import asyncio
from solution import task_1, task_2, task_3, task_manager
@pytest.mark.asyncio
async def test_task_1():
result = await task_1(1, 'T1-Test')
assert "Task T1-Test completed after 1 seconds." in result
@pytest.mark.asyncio
async def test_task_2():
result = await task_2('T2-Test')... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport time\n\nasync def task_1(seconds: int, name: str) -> str:\n print(f\"{name} starting at {time.strftime('%X')}\")\n await asyncio.sleep(seco... | trial_gpt4o_2 | {
"original_instruction": "**Problem Statement: Asynchronous Task Manager**\n\nYou are tasked with creating an asynchronous task manager using Python's asyncio module. The task manager should be able to handle multiple types of tasks concurrently, ensure certain tasks do not block or cancel others, and handle timeout... | 0.69375 | Docs: Python310_17778 | C | [
"task_1",
"task_2",
"task_3",
"task_manager"
] | 4 | [
[
"task_manager",
"task_1"
],
[
"task_manager",
"task_2"
],
[
"task_manager",
"task_3"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 9a8fc1627b01ed380c9b303a6f387dd7685f131e | 14e5cc09c8660c67816a057169f572f0f9dc15d5 | |||
v1.0 | complete | Docs | Docs: Pytorch_17783_C | import torch
def convert_to_sparse(input_tensor: torch.Tensor, layout: str) -> torch.Tensor:
"""
Converts a given dense tensor to the specified sparse format.
Args:
- input_tensor (torch.Tensor): The dense tensor to convert.
- layout (str): The sparse format ('coo', 'csr', 'csc', 'bsr', 'bsc').
... | import torch
def convert_to_sparse(input_tensor: torch.Tensor, layout: str) -> torch.Tensor:
"""
Converts a given dense tensor to the specified sparse format.
Args:
- input_tensor (torch.Tensor): The dense tensor to convert.
- layout (str): The sparse format ('coo', 'csr', 'csc', 'bsr', 'bsc').
... | import pytest
import torch
from solution import convert_to_sparse, sparse_matrix_multiplication, sparse_tensor_operations
def test_convert_to_sparse_coo():
dense_tensor = torch.tensor([[0, 2], [3, 0]], dtype=torch.float32)
sparse_tensor = convert_to_sparse(dense_tensor, 'coo')
assert sparse_tensor.layout =... | [
{
"docstring": "Converts a given dense tensor to the specified sparse format.\n\nArgs:\n- input_tensor (torch.Tensor): The dense tensor to convert.\n- layout (str): The sparse format ('coo', 'csr', 'csc', 'bsr', 'bsc').\n\nReturns:\n- torch.Tensor: The tensor in the specified sparse format.",
"function_decl... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef convert_to_sparse(input_tensor: torch.Tensor, layout: str) -> torch.Tensor:\n \"\"\"\n Converts a given dense tensor to the specified sparse f... | trial_gpt4o_0 | {
"original_instruction": "### Sparse Tensors in PyTorch: Challenge Task\n\nAs neural networks become large, models with sparse connections and weights often arise, especially in graph neural networks or pruned networks. Efficiently handling these sparse structures can significantly reduce computation time and memory... | 0.622441 | Docs: Pytorch_17783 | C | [
"convert_to_sparse",
"sparse_matrix_multiplication",
"sparse_tensor_operations"
] | 3 | [
[
"sparse_matrix_multiplication",
"convert_to_sparse"
],
[
"sparse_tensor_operations",
"convert_to_sparse"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 67b42893a280bfbf52b63238ff270f06d1410a02 | 22d244d67dcb7fd82599bdf54c32290917b6f75c | |||
v1.0 | complete | Docs | Docs: Seaborn_18056_C | import seaborn as sns
import matplotlib.pyplot as plt
def create_custom_pointplot():
"""
Load the `penguins` dataset using Seaborn and create a point plot that shows the average `bill_length_mm`
for each `island` differentiated by `species`. Enhance the plot by:
- Adding a second layer of grouping ba... | import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Load the dataset
penguins = sns.load_dataset("penguins")
# Function to calculate the 95% confidence interval
def ci_95(data):
return 1.96 * np.std(data) / np.sqrt(len(data))
# Create the point plot with enhancements
def create_custom_poin... | def test_create_custom_pointplot():
# Testing if the function runs without errors
try:
create_custom_pointplot()
assert True # If this point is reached, test is successful
except Exception as e:
assert False, f"create_custom_pointplot raised an exception: {e}"
# As the function pri... | [
{
"docstring": null,
"function_declaration": "def ci_95(data):",
"function_name": "ci_95",
"parameter_list": "(data)"
},
{
"docstring": null,
"function_declaration": "def create_custom_pointplot():",
"function_name": "create_custom_pointplot",
"parameter_list": "()"
}
] | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\n# Load the penguins dataset\npenguins = sns.load_dataset(\"penguins... | trial_gpt4o_4 | {
"original_instruction": "#### Objective\nAssess your understanding of the Seaborn library, specifically the `sns.pointplot` functionality, by creating and customizing point plots with multiple layers of complexity.\n\n#### Dataset\nWe will use the `penguins` dataset available in the Seaborn library. Ensure you have... | 0.704872 | Docs: Seaborn_18056 | C | [
"ci_95",
"create_custom_pointplot"
] | 2 | [
[
"create_custom_pointplot",
"ci_95"
]
] | 1 | [] | false | [] | false | pytest | false | [
"matplotlib",
"numpy",
"seaborn"
] | false | 04f6e903469f48cc48007dd5d534c7a234c07066 | dff5b7a152d94328fdd1a936f58dd1e6e2a22c39 | |||
v1.0 | complete | Docs | Docs: Python310_17901_C | import asyncio
from typing import List, Tuple
async def process_tasks(tasks: List[Tuple[int, str]], num_workers: int) -> List[str]:
""" Implement an asynchronous task processing system using asyncio.PriorityQueue.
>>> await process_tasks([(1, 'Task1'), (3, 'Task3'), (2, 'Task2')], 1)
['Task1', 'Task2'... | import asyncio
from typing import List, Tuple
async def worker(queue: asyncio.PriorityQueue, results: List[str]):
while True:
try:
priority, task = await queue.get()
except asyncio.CancelledError:
break
results.append(task)
await asyncio.sleep(0.1) # Simulat... | import pytest
import asyncio
from solution import process_tasks
@pytest.mark.asyncio
async def test_process_tasks_single_worker():
tasks = [(1, 'Task1'), (3, 'Task3'), (2, 'Task2')]
num_workers = 1
result = await process_tasks(tasks, num_workers)
assert result == ['Task1', 'Task2', 'Task3']
@pytest.ma... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def worker(queue: asyncio.PriorityQueue, results: List[str]):\n while True:\n try:\n priori... | trial_gpt4o_0 | {
"original_instruction": "**Objective:**\n\nImplement a task processing system using asyncio queues where multiple workers process tasks concurrently and handle priorities of tasks.\n\n**Problem Statement:**\n\nYou are required to implement an asynchronous task processing system using `asyncio.PriorityQueue`. Your s... | 0.601737 | Docs: Python310_17901 | C | [
"worker",
"process_tasks"
] | 2 | [
[
"process_tasks",
"worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5c794bf54e30e43c4b2e9ab309ac424389d497c1 | 91d6249e906f9e141dd93ee6aba31ebfe485c0e6 | |||
v1.0 | complete | Docs | Docs: Pytorch_18140_C | import torch
from torch.func import grad, vmap
def model(weights, feature_vec):
"""
Simple linear model with ReLU activation.
>>> weights = torch.tensor([0.5, -1.0])
>>> feature_vec = torch.tensor([2.0, 3.0])
>>> model(weights, feature_vec).item()
0.0
"""
pass # TODO: Implement model
... | import torch
from torch.func import grad, vmap
def model(weights, feature_vec):
"""
Simple linear model with ReLU activation
"""
return torch.nn.functional.relu(feature_vec.matmul(weights))
def compute_loss(weights, example, target):
"""
Computes Mean Squared Error (MSE) loss between model pre... | import torch
from solution import model, compute_loss, compute_batch_gradients
def test_model():
weights = torch.tensor([0.5, -1.0])
feature_vec = torch.tensor([2.0, 3.0])
result = model(weights, feature_vec)
assert result == torch.tensor(0.0) # ReLU should zero out the negative value
def test_comput... | [
{
"docstring": "Simple linear model with ReLU activation",
"function_declaration": "def model(weights, feature_vec):",
"function_name": "model",
"parameter_list": "(weights, feature_vec)"
},
{
"docstring": "Computes Mean Squared Error (MSE) loss between model prediction and target",
"fun... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.func import vmap, grad\n\ndef model(weights, feature_vec):\n \"\"\"\n Linear model with ReLU activation\n \"\"\"\n assert feature_v... | trial_gpt4o_2 | {
"original_instruction": "You are given a machine learning problem where you need to compute the gradient of a loss function with respect to the model parameters for each sample in the batch efficiently.\n\n### Task\n\nImplement a function `compute_batch_gradients` that takes in a dataset and model weights, and retu... | 0.682508 | Docs: Pytorch_18140 | C | [
"model",
"compute_loss",
"compute_batch_gradients"
] | 3 | [
[
"compute_batch_gradients",
"compute_loss"
],
[
"compute_loss",
"model"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 2456b7847f4c3bc03f52bfc4906172df0464118f | 7ce8d90cb83568aac222a3e6ec6bcad33a315139 | |||
v1.0 | complete | Docs | Docs: Python310_18329_C | import asyncio
import socket
import time
clients = []
async def handle_client(client_socket, addr):
"""Handle an individual client connection and broadcast messages to all connected clients.
Args:
client_socket: The socket object representing the client connection.
addr: The address of th... | import asyncio
import socket
import time
clients = []
async def handle_client(client_socket, addr):
while True:
try:
message = await asyncio.get_event_loop().sock_recv(client_socket, 1024)
if not message:
break
message = message.decode('utf-8')
... | import pytest
import asyncio
import socket
@pytest.mark.asyncio
async def test_server_client_connection():
async def run_server():
loop = asyncio.get_event_loop()
await server(loop)
async def run_client():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
await ... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport socket\nimport time\n\nclients = []\n\nasync def handle_client(client_socket, addr):\n while True:\n try:\n message = await ... | trial_gpt4o_0 | {
"original_instruction": "**Networking Chat Application Using Sockets and Asynchronous I/O**\n\n### Objective\nImplement a simple chat server-client system using the `asyncio` and `socket` modules. The server should handle simultaneous connections from multiple clients and facilitate message broadcasting to all conn... | 0.649113 | Docs: Python310_18329 | C | [
"handle_client",
"server"
] | 2 | [
[
"server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | d5f4dc7dcb546ab13090e8993983fd72583a53a6 | 9ee51fe351266d3c9fe024911b467e55d035efd2 | |||
v1.0 | complete | Docs | Docs: Pytorch_17038_C | import os
import tempfile
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel
from torch.distributed import ReduceOp
def custom_allreduce_hook(state, bucket):
""" Perform an allreduc... | import os
import tempfile
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel
from torch.distributed import ReduceOp
def custom_allreduce_hook(state, bucket):
# Perform allreduce ope... | import os
import tempfile
import torch
import torch.nn as nn
import torch.optim as optim
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel
import torch.multiprocessing as mp
# We will reuse the defined functions: custom_allreduce_hook, SimpleModel,
# setup, cleanup, and run_demo in... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport tempfile\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.multiprocessing as mp\nfrom... | trial_gpt4o_1 | {
"original_instruction": "### PyTorch DDP Communication Hooks Assessment\n\n#### Objective\nImplement a custom communication hook for a DistributedDataParallel (DDP) model in PyTorch. This hook should perform an allreduce operation on the bucket's gradients and apply a custom transformation to the reduced gradients.... | 0.581498 | Docs: Pytorch_17038 | C | [
"custom_allreduce_hook",
"setup",
"cleanup",
"run_demo",
"demo_custom_hook"
] | 5 | [
[
"demo_custom_hook",
"cleanup"
],
[
"demo_custom_hook",
"custom_allreduce_hook"
],
[
"demo_custom_hook",
"setup"
]
] | 3 | [] | false | [
"SimpleModel"
] | true | pytest | false | [
"torch"
] | false | 768cedfc174b38bfce6dddc776f3d7a4e0caa770 | 975b7eb7eaf9276ff1c474d21b8be35d9643a8b7 | |||
v1.0 | complete | Docs | Docs: Python310_18265_C | import functools
@functools.lru_cache(maxsize=100)
def fib_lru(n: int) -> int:
"""
Returns the nth Fibonacci number using LRU cache with a max size of 100.
>>> fib_lru(0) == 0
>>> fib_lru(1) == 1
>>> fib_lru(10) == 55
>>> fib_lru(20) == 6765
"""
pass
@functools.cache
def factorial_cach... | import functools
@functools.lru_cache(maxsize=100)
def fib_lru(n: int) -> int:
"""
Returns the nth Fibonacci number using LRU cache with a max size of 100.
"""
if n < 2:
return n
return fib_lru(n - 1) + fib_lru(n - 2)
@functools.cache
def factorial_cache(n: int) -> int:
"""
Returns... | from solution import fib_lru, factorial_cache, evaluate_cache_performance
def test_fib_lru():
assert fib_lru(0) == 0
assert fib_lru(1) == 1
assert fib_lru(10) == 55
assert fib_lru(20) == 6765
assert fib_lru(30) == 832040
def test_factorial_cache():
assert factorial_cache(0) == 1
assert fac... | [
{
"docstring": "Returns the nth Fibonacci number using LRU cache with a max size of 100.",
"function_declaration": "def fib_lru(n):",
"function_name": "fib_lru",
"parameter_list": "(n)"
},
{
"docstring": "Returns the factorial of n using a simple cache.",
"function_declaration": "def fac... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import functools\n\n# Part 1: Implement Fibonacci function with LRU cache\n@functools.lru_cache(maxsize=100)\ndef fib_lru(n):\n \"\"\"\n Returns the nth Fibonacci... | trial_gpt4o_2 | {
"original_instruction": "**Title**: Implementing and Managing Cached Functions with `functools`\n\n**Objective**: \nDemonstrate your understanding of caching mechanisms provided by the `functools` module by implementing a project which uses `@functools.lru_cache` and `@functools.cache` decorators.\n\n**Problem Stat... | 0.597451 | Docs: Python310_18265 | C | [
"fib_lru",
"factorial_cache",
"evaluate_cache_performance"
] | 3 | [
[
"evaluate_cache_performance",
"factorial_cache"
],
[
"evaluate_cache_performance",
"fib_lru"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 619dbb8f2576522505f820188770651cfd8fc389 | b947095d1c115975f38a38bfec4a1171a4f954e2 | |||
v1.0 | complete | Docs | Docs: Scikit_17925_C | import os
import pandas as pd
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
def data_streamer(folder_path, batch_size):
"""
Generator that yields mini-batches from CSV files in the folder.
Parameters:
folder_path (str): Path to the folder ... | import os
import pandas as pd
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
def data_streamer(folder_path, batch_size):
"""
Generator that yields mini-batches from CSV files in the folder.
:param folder_path: Path to the folder containing ... | import os
import pandas as pd
import pytest
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from solution import data_streamer, build_out_of_core_pipeline
# Create temporary directory and CSV files for testing
@pytest.fixture(scope="module")
def prepare_test... | [
{
"docstring": "Generator that yields mini-batches from CSV files in the folder.\n\n:param folder_path: Path to the folder containing CSV files.\n:param batch_size: Number of rows to yield per mini-batch.",
"function_declaration": "def data_streamer(folder_path, batch_size):",
"function_name": "data_str... | [
0,
0,
0,
1,
0,
0,
0,
0,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport pandas as pd\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\n\ndef data_streamer(folde... | trial_gpt4o_9 | {
"original_instruction": "### Coding Assessment: Implementing an Out-of-Core Learning Pipeline\n\n#### Objective\nThe task is to implement an out-of-core learning pipeline using scikit-learn, demonstrating your understanding of streaming instances, feature extraction, and incremental learning.\n\n#### Problem Statem... | 0.640366 | Docs: Scikit_17925 | C | [
"data_streamer",
"build_out_of_core_pipeline"
] | 2 | [
[
"build_out_of_core_pipeline",
"data_streamer"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas",
"sklearn"
] | false | 1fa8e600dc0cb072af6f717c9afd383d447ecf2e | cc280eb9cece4ac44637f0f9ac12e76d3890fbbe | |||
v1.0 | complete | Docs | Docs: Python310_18431_C | import asyncio
import contextvars
# Define the context variable
request_id = contextvars.ContextVar("request_id")
async def handle_request(id):
"""
Simulates handling a client request by setting the request_id
and printing the ID before and after processing.
>>> asyncio.run(handle_request(1))
... | import asyncio
import contextvars
# Define the context variable
request_id = contextvars.ContextVar("request_id")
async def handle_request(id):
"""
Simulates handling a client request by setting the request_id
and printing the ID before and after processing.
"""
# Set the request_id for the contex... | import asyncio
import contextvars
from solution import handle_request, simulate_requests, request_id
async def test_handle_request():
"""
Tests the handle_request function to ensure correct handling
of context variables.
"""
id = 1
token = request_id.set(id)
try:
await handle_r... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport contextvars\n\n# Define the context variable\nrequest_id = contextvars.ContextVar(\"request_id\")\n\nasync def handle_request(id):\n # Set the... | trial_gpt4o_1 | {
"original_instruction": "**Objective**: Write a Python script to demonstrate your understanding of the `contextvars` module and its usage in an asynchronous environment.\n\n**Instructions**:\n1. Create a context variable called `request_id` to store request identifiers for an asynchronous web server.\n2. Implement ... | 0.497083 | Docs: Python310_18431 | C | [
"handle_request",
"simulate_requests"
] | 2 | [
[
"simulate_requests",
"handle_request"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 330b5bc7f269f74f771cd5f0844805e0a41022ae | 5e8940e875efb80fd6eaad857327b20bad815f3b | |||
v1.0 | complete | Docs | Docs: Python310_18149_C | import asyncio
async def async_task(name: str, duration: int):
"""
Asynchronous task that waits for a given duration and handles timeout.
"""
print(f"{name} started")
try:
await asyncio.sleep(duration)
print(f"{name} completed")
except asyncio.CancelledError:
print(f"{na... | import asyncio
async def async_task(name: str, duration: int):
"""
Asynchronous task that waits for a given duration and handles timeout.
"""
print(f"{name} started")
try:
await asyncio.sleep(duration)
print(f"{name} completed")
return name
except asyncio.CancelledError:... | import asyncio
from solution import async_task, task_manager
async def test_async_task():
result = await async_task("test_task", 1)
assert result == "test_task"
def test_task_manager():
tasks = [('Task1', 3), ('Task2', 7), ('Task3', 2)]
results = asyncio.run(task_manager(tasks))
assert results == ... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def async_task(name: str, duration: int):\n print(f\"{name} started\")\n try:\n await asyncio.sleep(duration)\n print(f\"{na... | trial_gpt4o_1 | {
"original_instruction": "### Asynchronous Programming with Asyncio\n\nIn this coding exercise, demonstrate your understanding of Python's asyncio package by implementing an asynchronous task manager. Your task manager will manage multiple tasks with varying completion times, handle timeouts and cancellations, and g... | 0.578062 | Docs: Python310_18149 | C | [
"async_task",
"task_manager"
] | 2 | [
[
"task_manager",
"async_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 75d05744016b1b02a0827918cc3dbc53c66ddf31 | fc55a867135d6601371e60119614c034b8d32e62 | |||
v1.0 | complete | Docs | Docs: Python310_18277_C | def validate_and_get_annotations(obj: Any) -> dict:
"""
Return the annotations of an object if they exist, or an empty dictionary if they don't.
:param obj: Any Python object such as a function, class, or module.
:return: A dictionary containing annotation names and types.
"""
pass
def unstrin... | import inspect
def validate_and_get_annotations(obj):
"""
Return the annotations of an object if they exist, or an empty dictionary if they don't.
:param obj: Any Python object such as a function, class, or module.
:return: A dictionary containing annotation names and types.
"""
try:
re... | from solution import validate_and_get_annotations, unstringize_annotations
def test_validate_and_get_annotations_no_annotations():
def func_without_annotations():
pass
assert validate_and_get_annotations(func_without_annotations) == {}
def test_validate_and_get_annotations_with_annotations():
def... | [
{
"docstring": "Return the annotations of an object if they exist, or an empty dictionary if they don't.\n:param obj: Any Python object such as a function, class, or module.\n:return: A dictionary containing annotation names and types.",
"function_declaration": "def validate_and_get_annotations(obj):",
... | [
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 inspect\n\ndef validate_and_get_annotations(obj):\n \"\"\"\n Return the annotations of an object if they exist, or an empty dictionary if they don't.\n ... | trial_gpt4o_0 | {
"original_instruction": "**Objective:**\nThe goal of this question is to assess your understanding of handling annotations in Python 3.10. You will be required to implement various functions that adhere to best practices for accessing and managing the `__annotations__` attribute.\n\n#### Problem Statement\n\nImplem... | 0.614815 | Docs: Python310_18277 | C | [
"validate_and_get_annotations",
"unstringize_annotations"
] | 2 | [
[
"unstringize_annotations",
"validate_and_get_annotations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8e26361b70898ace0d1d49174d7d6aaa26219189 | 22a2c0ff945349704feb0b431a2549fad38ac49a | |||
v1.0 | complete | Docs | Docs: Python310_18490_C | import asyncio
async def echo_server(host: str, port: int):
"""
Start an asynchronous TCP echo server.
Args:
- host (str): The host/IP address for the server.
- port (int): The port number for the server.
The server should handle multiple client connections concurrently and echo back ... | import asyncio
async def handle_client(reader, writer):
"""
Coroutine to handle client connections.
"""
try:
while True:
data = await reader.read(100)
if not data:
break
writer.write(data)
await writer.drain()
except asyncio.Ca... | import asyncio
import socket
import pytest
from solution import echo_server
@pytest.fixture
async def start_server():
server_task = asyncio.create_task(echo_server('127.0.0.1', 8888))
await asyncio.sleep(1) # give the server time to start
yield
server_task.cancel()
try:
await server_task
... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n \"\"\"\n This coroutine handles individual client connections, reading messages\n from the reader ... | trial_gpt4o_2 | {
"original_instruction": "### Asynchronous Networking with Asyncio\n\nYou are tasked with creating a simple asynchronous TCP echo server using Python's asyncio module. The server should be capable of handling multiple client connections simultaneously, echoing back any received messages to the sender.\n\nImplement t... | 0.639711 | Docs: Python310_18490 | C | [
"handle_client",
"echo_server",
"main"
] | 3 | [
[
"echo_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0a9d5ce566e12649a03608771cdd8966cc41e44b | 78b9683c5b2b0f6c5ab4f86b9c088eb41ade9cbc | |||
v1.0 | complete | Docs | Docs: Python310_18029_C | import os
import tarfile
def secure_extract(archive_path: str, output_path: str, file_extension: str) -> None:
"""
Extracts files with the specified extension from the tar archive to the specified output path,
applying security measures to prevent extraction of potentially dangerous files.
Args:
-... | import os
import tarfile
def is_within_directory(directory, target):
# Check if target is a directory within the specified directory
abs_directory = os.path.abspath(directory)
abs_target = os.path.abspath(target)
return os.path.commonpath([abs_directory]) == os.path.commonpath([abs_directory, abs_targe... | import os
import tarfile
import pytest
from solution import secure_extract
@pytest.fixture(scope="function")
def setup_tarfile(tmpdir):
test_tar_path = os.path.join(tmpdir, "test_archive.tar.gz")
test_output_path = os.path.join(tmpdir, "output")
os.makedirs(test_output_path, exist_ok=True)
with tarfi... | [
{
"docstring": null,
"function_declaration": "def is_within_directory(directory, target):",
"function_name": "is_within_directory",
"parameter_list": "(directory, target)"
},
{
"docstring": "Extracts files with the specified extension from the tar archive to the specified output path,\napply... | [
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 tarfile\n\ndef secure_extract(archive_path: str, output_path: str, file_extension: str) -> None:\n \"\"\"\n Extracts files with the specified ex... | trial_gpt4o_5 | {
"original_instruction": "### TarFile Challenge: Custom Secure Extraction\n\nYou are developing a secure backup utility that needs to handle tar archives carefully due to potential security threats from untrusted sources. To ensure secure extraction, you will implement a Python function that:\n\n1. Opens a specified... | 0.662775 | Docs: Python310_18029 | C | [
"is_within_directory",
"secure_extract"
] | 2 | [
[
"secure_extract",
"is_within_directory"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aa5db36fb4dc460443677ce94eee040ab8afb275 | ca881848dcd35d59b64c687592bf71d48d487348 | |||
v1.0 | complete | Docs | Docs: Python310_18105_C | import os
from typing import List, Dict
def count_words_in_file(file_path: str) -> Dict[str, int]:
pass
def merge_word_counts(counts: List[Dict[str, int]]) -> Dict[str, int]:
pass
def concurrent_word_frequency(files: List[str], use_threads: bool = True) -> Dict[str, int]:
""" Process multiple large text ... | import os
from typing import List, Dict
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def count_words_in_file(file_path: str) -> Dict[str, int]:
word_count = defaultdict(int)
try:
with open(file_path, 'r', encoding='utf-8') as file:
... | import os
import pytest
from solution import concurrent_word_frequency
@pytest.fixture
def create_test_files():
file_contents = {
'file1.txt': "apple banana apple",
'file2.txt': "banana orange",
'file3.txt': "apple orange banana"
}
for filename, content in file_contents.items():
... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nfrom collections import defaultdict\nfrom typing import List, Dict\n\ndef count_words... | trial_gpt4o_1 | {
"original_instruction": "**Concurrent File Processing**\n\nYou are tasked with processing multiple large text files concurrently to generate statistical data about the frequency of words in these files. To achieve optimal performance in this task, you will need to use the `concurrent.futures` module. Specifically, ... | 0.607589 | Docs: Python310_18105 | C | [
"count_words_in_file",
"merge_word_counts",
"concurrent_word_frequency"
] | 3 | [
[
"concurrent_word_frequency",
"count_words_in_file"
],
[
"concurrent_word_frequency",
"merge_word_counts"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cffb3096a1181caccc6127d902f91af5829c4c20 | 95b1d519fb8a88e392db893e4a2dad9b5ad75b45 | |||
v1.0 | complete | Docs | Docs: Python310_18166_C | import codecs
class ReverseCodec(codecs.Codec):
def encode(self, input, errors='strict'):
"""Encode the input string by reversing it.
Args:
input (str): The string to encode.
errors (str): The error handling scheme to use.
Returns:
tuple: Encoded string a... | import codecs
class ReverseCodec(codecs.Codec):
def encode(self, input, errors='strict'):
try:
if not isinstance(input, str):
raise TypeError('input should be a string')
return (input[::-1], len(input))
except Exception as e:
return ('?', len(inpu... | from solution import perform_operations, register_reverse_codec, unregister_reverse_codec, encode_string, decode_string
def test_perform_operations():
assert perform_operations() == "hello world"
def test_encoding_decoding():
register_reverse_codec()
# Test encoding
encoded = encode_string("hello... | [] | [
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 codecs\n\nclass ReverseCodec(codecs.Codec):\n\n def encode(self, input, errors='strict'):\n if not isinstance(input, str):\n raise TypeError... | trial_gpt4o_2 | {
"original_instruction": "### Coding Challenge: Custom Codec Implementation\n\nThe provided documentation describes various functions related to codec registration, codec lookup, and error handling. In this challenge, you will demonstrate your understanding of these concepts by implementing a custom codec and encodi... | 0.58949 | Docs: Python310_18166 | C | [
"reverse_codec",
"register_reverse_codec",
"unregister_reverse_codec",
"encode_string",
"decode_string",
"perform_operations"
] | 6 | [
[
"perform_operations",
"decode_string"
],
[
"perform_operations",
"encode_string"
],
[
"perform_operations",
"register_reverse_codec"
],
[
"perform_operations",
"unregister_reverse_codec"
],
[
"register_reverse_codec",
"reverse_codec"
],
[
"unregister... | 6 | [] | false | [
"ReverseCodec"
] | true | pytest | true | [] | true | 9a125f642305b363fc297dde3fbc2bffa215622a | 91818c2d68a914c82a8c24ed88d0b2e6bad5b41d | |||
v1.0 | complete | Docs | Docs: Python310_18550_C | import gettext
import os
def setup_translations():
locales_dir = os.path.join(os.path.dirname(__file__), 'locales')
os.makedirs(locales_dir, exist_ok=True)
gettext.bindtextdomain('messages', locales_dir)
gettext.textdomain('messages')
def localized_greeting(language_code: str, name: str) -> str:
... | import gettext
import os
def setup_translations():
locales_dir = os.path.join(os.path.dirname(__file__), 'locales')
os.makedirs(locales_dir, exist_ok=True)
# This setup assumes that the .mo files are already compiled and placed in appropriate directories
# English: locales/en/LC_MESSAGES/messages.... | from solution import localized_greeting # Assuming the solution is saved as solution.py
def test_localized_greeting_english():
assert localized_greeting('en', 'Alice') == "Hello, Alice!"
def test_localized_greeting_spanish():
assert localized_greeting('es', 'Carlos') == "¡Hola, Carlos!"
def test_localized_g... | [
{
"docstring": null,
"function_declaration": "def setup_translations():",
"function_name": "setup_translations",
"parameter_list": "()"
},
{
"docstring": "Returns a localized greeting message in the specified language.\n\n:param language_code: Language code (e.g., 'en' for English, 'es' for ... | [
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 gettext\nimport os\n\ndef setup_translations():\n locales_dir = os.path.join(os.path.dirname(__file__), 'locales')\n os.makedirs(locales_dir, exist_ok=True... | trial_gpt4o_0 | {
"original_instruction": "**Internationalization and Localized Greetings**\n\n### Objective:\nImplement a function that generates localized greeting messages based on user's preferred language and locale. The function should utilize the `gettext` module to fetch appropriate translations from message catalogs.\n\n###... | 0.448427 | Docs: Python310_18550 | C | [
"setup_translations",
"localized_greeting"
] | 2 | [
[
"localized_greeting",
"setup_translations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 491fb5f2853affa687d2361db742672620fd84ae | d7eb56b80413ceb76f81a2eb55d4398776b50d07 | |||
v1.0 | complete | Docs | Docs: Python310_18412_C | class CustomError(Exception):
"""Custom error for specific application needs."""
pass
def perform_operations(steps: list) -> dict:
"""Simulates an operation involving multiple steps, raising and handling exceptions as needed.
Args:
steps (list): A list of step descriptions, where each step is ... | import sys
import traceback
class CustomError(Exception):
"""
Custom error for specific application needs.
"""
pass
def log_exception(exc: Exception):
"""
Logs the details of an exception, including its type, message, and traceback.
"""
exc_type, exc_value, exc_traceback = sys.exc_info... | import pytest
from solution import CustomError, perform_operations
def test_perform_operations_value_error():
steps = [{"type": "value_error", "description": "Raise a ValueError"}]
results = perform_operations(steps)
assert results == {0: False}
def test_perform_operations_type_error():
steps = [{"typ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nimport traceback\n\nclass CustomError(Exception):\n \"\"\"\n Custom exception class for specific application needs.\n \"\"\"\n pass\n\ndef log_e... | trial_gpt4o_2 | {
"original_instruction": "### Python Exception Handling and Custom Exception Implementation\n\n#### Objective\nTo assess your understanding of Python's exception handling mechanisms, custom exception creation, and proper usage of exception functions.\n\n#### Problem Statement\nYou are required to implement a Python ... | 0.445747 | Docs: Python310_18412 | C | [
"log_exception",
"perform_operations"
] | 2 | [
[
"perform_operations",
"log_exception"
]
] | 1 | [] | false | [
"CustomError"
] | true | pytest | true | [] | true | 591f3abaa6c530d07b243ae240de603b6c7aeed8 | d21d3608c83ed3b9924055d89fea85a580e7f5f0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.