version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | instruct | Docs | Docs: Python310_27355_I | ### Question: Implement a Mailcap Configuration Checker
You are tasked with creating a Python function that utilizes the `mailcap` module to find appropriate command lines for handling files based on their MIME types. Your function should handle various MIME types, leverage user and system mailcap files, and ensure se... | import mailcap
import re
def validate_filename_and_params(filename, params):
disallowed_chars = re.compile(r'[^a-zA-Z0-9_\-.,]')
if disallowed_chars.search(filename):
return False
for param in params:
if disallowed_chars.search(param):
return False
return True
... | from solution import get_mailcap_commands
def test_no_disallowed_chars():
mime_types = ['text/plain', 'video/mpeg']
filename = 'video.mp4'
params = ['width=1920', 'height=1080']
result = get_mailcap_commands(mime_types, filename, params)
assert 'text/plain' in result
assert 'video/mpeg' in... | [
{
"docstring": null,
"function_declaration": "def validate_filename_and_params(filename, params):",
"function_name": "validate_filename_and_params",
"parameter_list": "(filename, params)"
},
{
"docstring": null,
"function_declaration": "def get_mailcap_commands(mime_types, filename, para... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import mailcap\nimport re\n\ndef validate_filename_and_params(filename, params):\n disallowed_chars = re.compile(r'[^a-zA-Z0-9_\\-.,]')\n if disallowed_chars.sear... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00027355",
"row_id": 27355,
"seed_ids": "[399]"
} | 0.522936 | Docs: Python310_27355 | I | [
"validate_filename_and_params",
"get_mailcap_commands"
] | 2 | [
[
"get_mailcap_commands",
"validate_filename_and_params"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 68c1f79af2418453e84dfa938b11cfe19f06ed09 | ab4992e220b8c69aba6ea4fad024112941166afc | |||
v1.0 | instruct | Docs | Docs: Pytorch_27369_I | ### Question: High-Performance Computation on MacOS using PyTorch MPS Backend
You are given a PyTorch neural network model and you need to run it on a MacOS device using the MPS backend. Implement the following functions to demonstrate your understanding of using the MPS backend for high-performance computation:
1. *... | import torch
def check_mps_available():
"""
Checks if the MPS backend is available on the current MacOS device.
Output:
Prints appropriate messages based on the availability of the MPS backend.
Returns:
bool: True if MPS backend is available, False otherwise.
"""
if not torch.b... | import pytest
import torch
from torch import nn
from solution import check_mps_available, move_to_mps, train_model_on_mps
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.linear = nn.Linear(10, 1)
def forward(self, x):
return self.linear(x)... | [
{
"docstring": "Checks if the MPS backend is available on the current MacOS device.\n\nOutput:\nPrints appropriate messages based on the availability of the MPS backend.\nReturns:\n bool: True if MPS backend is available, False otherwise.",
"function_declaration": "def check_mps_available():",
"funct... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef check_mps_available():\n \"\"\"\n Checks if the MPS backend is available on the current MacOS device.\n \n Output:\n Prints appropria... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00027369",
"row_id": 27369,
"seed_ids": "[167]"
} | 0.426833 | Docs: Pytorch_27369 | I | [
"check_mps_available",
"move_to_mps",
"train_model_on_mps"
] | 3 | [
[
"move_to_mps",
"check_mps_available"
],
[
"train_model_on_mps",
"check_mps_available"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | dba5083af5645f77f8082c512d09c93599e098ce | 6612f380edf4028f31d9bf858bbd7b2db56b846e | |||
v1.0 | instruct | Docs | Docs: Pandas_27390_I | #### Objective:
Demonstrate your understanding of data visualization using the `pandas.plotting` module.
#### Problem Statement:
You are given a Titanic dataset containing information about passengers. You need to visualize various aspects of this data using pandas plotting functions.
#### Input:
The input dataset wi... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pandas.plotting import scatter_matrix, parallel_coordinates, andrews_curves
def preprocess_data(df):
"""
Handle missing values and encode categorical variables.
"""
df['Age'].fillna(df['Age'].mean(), inplace=True)
df['Fare'... | import pytest
import pandas as pd
from solution import visualize_titanic_data, preprocess_data
def test_preprocess_data():
data = {
'PassengerId': [1, 2],
'Survived': [0, 1],
'Pclass': [3, 1],
'Name': ['A', 'B'],
'Sex': ['male', 'female'],
'Age': [22, None],
... | [
{
"docstring": "Handle missing values and encode categorical variables.",
"function_declaration": "def preprocess_data(df):",
"function_name": "preprocess_data",
"parameter_list": "(df)"
},
{
"docstring": "Generate various visualizations for the Titanic dataset.",
"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 pandas as pd\nfrom pandas.plotting import scatter_matrix, parallel_coordinates, andrews_curves\nimport matplotlib.pyplot as plt\n\ndef visualize_titanic_data(df:... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027390",
"row_id": 27390,
"seed_ids": "[31]"
} | 0.671329 | Docs: Pandas_27390 | I | [
"preprocess_data",
"visualize_titanic_data"
] | 2 | [
[
"visualize_titanic_data",
"preprocess_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"pandas"
] | false | b93df0185020161e217021bfbc99d255f387219f | a9903d1daecf733d995e7d380d0063c99e3230d5 | |||
v1.0 | instruct | Docs | Docs: Python310_27407_I | **Objective:**
Write a Python function that interfaces with C functions to handle integers. You will be provided with a hypothetical C interface (mimicked by Python functions) for testing purposes.
**Task:**
1. Implement a function `convert_and_add` that takes an integer, an unsigned long, and a double as inputs.
2.... | def PyLong_FromLong(v):
"""
Hypothetical C-to-Python interface function to convert long to Python integer.
"""
return int(v)
def PyLong_FromUnsignedLong(v):
"""
Hypothetical C-to-Python interface function to convert unsigned long to Python integer.
"""
return int(v)
def PyLong_FromDoub... | from solution import convert_and_add
def test_convert_and_add_positive_numbers():
assert convert_and_add(10, 20, 5.5) == 35
def test_convert_and_add_with_zero():
assert convert_and_add(0, 0, 0.0) == 0
assert convert_and_add(10, 0, 0.0) == 10
assert convert_and_add(0, 20, 0.0) == 20
assert convert_... | [
{
"docstring": "Hypothetical C-to-Python interface function to convert long to Python integer.",
"function_declaration": "def PyLong_FromLong(v):",
"function_name": "PyLong_FromLong",
"parameter_list": "(v)"
},
{
"docstring": "Hypothetical C-to-Python interface function to convert unsigned l... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def PyLong_FromLong(v):\n \"\"\"\n Hypothetical C interface function that converts a C long to a Python int.\n In reality, this is simply emulated by Python's ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00027407",
"row_id": 27407,
"seed_ids": "[52]"
} | 0.532582 | Docs: Python310_27407 | I | [
"PyLong_FromLong",
"PyLong_FromUnsignedLong",
"PyLong_FromDouble",
"convert_and_add"
] | 4 | [
[
"convert_and_add",
"PyLong_FromDouble"
],
[
"convert_and_add",
"PyLong_FromLong"
],
[
"convert_and_add",
"PyLong_FromUnsignedLong"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 5d3739e581861edfab90c7a21cf962c61fd68b1b | e2ef4a005c5105d3bb3fc6bbb87af4fb94a4a45c | |||
v1.0 | instruct | Docs | Docs: Pytorch_27425_I | **Title:** Implementing and Composing Function Transforms with torch.func
**Objective:**
Your task is to implement a function that performs gradient computation and vectorization using the `torch.func` module. You will compose the `grad` and `vmap` transforms to efficiently compute per-sample gradients of a given func... | import torch
from torch.func import grad, vmap
def f(x):
return (x.sum())**2
def per_sample_gradients(inputs: torch.Tensor) -> torch.Tensor:
grad_f = grad(f)
per_sample_grads = vmap(grad_f)(inputs)
return per_sample_grads | from solution import per_sample_gradients
import torch
def test_per_sample_gradients_two_samples():
inputs = torch.tensor([[1.0, 2.0], [3.0, 4.0]], requires_grad=True)
result = per_sample_gradients(inputs)
expected = torch.tensor([[6.0, 6.0], [14.0, 14.0]])
assert torch.allclose(result, expected), f"Ex... | [
{
"docstring": null,
"function_declaration": "def f(x):",
"function_name": "f",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def per_sample_gradients(inputs):",
"function_name": "per_sample_gradients",
"parameter_list": "(inputs)"
}
] | [
1,
0,
0,
0,
0,
0,
1,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.func import grad, vmap\n\ndef per_sample_gradients(inputs: torch.Tensor) -> torch.Tensor:\n def f(x):\n return (x.sum())**2\n \n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00027425",
"row_id": 27425,
"seed_ids": "[56]"
} | 0.56664 | Docs: Pytorch_27425 | I | [
"f",
"per_sample_gradients"
] | 2 | [
[
"per_sample_gradients",
"f"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | be9a521d2dc1fc4575b8022843be3ec8795e9c60 | d30acf1fdd3861e62b600386625943d550c9a451 | |||
v1.0 | instruct | Docs | Docs: Pytorch_27428_I | ### PyTorch Autograd Coding Assessment
#### Objective
Demonstrate your understanding of PyTorch's autograd functionalities by implementing a custom backward function and utilizing higher-level API functions (Jacobians, Hessians).
#### Problem Statement
You are required to implement a PyTorch custom function that beh... | import torch
from torch.autograd import Function
import torch.nn as nn
import torch.autograd.functional as F
class ExpWithCustomGrad(Function):
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
return input.exp()
@staticmethod
def backward(ctx, grad_output):
... | import pytest
import torch
from solution import ExpWithCustomGrad, SimpleModel, compute_loss
def test_custom_grad_function():
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = ExpWithCustomGrad.apply(x)
y.sum().backward()
expected_grad = 2 * torch.exp(x)
assert torch.allclose(x.grad, e... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.autograd import Function\nimport torch.nn as nn\nimport torch.autograd.functional as F\n\nclass ExpWithCustomGrad(Function):\n @staticmethod... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00027428",
"row_id": 27428,
"seed_ids": "[66]"
} | 0.552472 | Docs: Pytorch_27428 | I | [
"compute_loss",
"main_example"
] | 2 | [
[
"main_example",
"compute_loss"
]
] | 1 | [] | false | [
"ExpWithCustomGrad",
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | 6e2a43c5f80cded17b16e06ff8ae4a0036b86795 | d36e48f4fcba6565c91c7eea66ffe86c50f131b0 | |||
v1.0 | instruct | Docs | Docs: Python310_27449_I | #### Objective
To assess the student's ability to implement context managers for resource handling and apply advanced Python concepts in a practical scenario.
#### Problem Statement
You are required to implement a custom context manager using the `contextlib` module that handles resource management for a database conn... | from contextlib import contextmanager
class DatabaseConnection:
def connect(self):
print("Database connection opened.")
def close(self):
print("Database connection closed.")
def execute(self, query: str):
print(f"Executing query: {query}")
@contextmanager
def database_man... | from solution import DatabaseConnection, database_manager, run_queries
def test_database_connection_emulator(capsys):
db = DatabaseConnection()
db.connect()
db.execute("SELECT * FROM test")
db.close()
captured = capsys.readouterr()
assert captured.out == "Database connection opened.\nExecuting ... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from contextlib import contextmanager\n\nclass DatabaseConnection:\n def connect(self):\n print(\"Database connection opened.\")\n \n def close(self):\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027449",
"row_id": 27449,
"seed_ids": "[146]"
} | 0.386928 | Docs: Python310_27449 | I | [
"database_manager",
"run_queries"
] | 2 | [
[
"run_queries",
"database_manager"
]
] | 1 | [] | false | [
"DatabaseConnection"
] | true | pytest | true | [] | true | 21018da64a83ceeea63b66ec2afd829a1965e378 | c6f9cd6e838853000200c8011b00686f74e81a59 | |||
v1.0 | instruct | Docs | Docs: Python310_27529_I | ### Asyncio Coding Assessment Question
**Objective**: To assess the student's comprehension and practical application of asyncio coroutines, task creation, concurrent execution, and advanced asyncio handling such as timeouts and cancellation.
### Problem Statement
You are required to write an asynchronous function `... | import asyncio
import random
async def fetch(url: str) -> str:
"""
Simulate an HTTP get request to fetch content of a URL.
"""
random_delay = random.randint(1, 5)
await asyncio.sleep(random_delay)
return f"Content of {url}"
async def fetch_multiple_urls(urls: list, timeout: float) -> dict:
... | import pytest
import asyncio
from solution import fetch_multiple_urls
@pytest.mark.asyncio
async def test_fetch_multiple_urls_success():
urls = ["http://example.com", "http://example.org"]
timeout = 5.0
results = await fetch_multiple_urls(urls, timeout)
assert all(content.startswith("Content of") for c... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\n\nasync def fetch(url: str) -> str:\n \"\"\"\n Simulate an HTTP get request to fetch content of a URL.\n \"\"\"\n random_dela... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00027529",
"row_id": 27529,
"seed_ids": "[317]"
} | 0.54946 | Docs: Python310_27529 | I | [
"fetch",
"fetch_multiple_urls"
] | 2 | [
[
"fetch_multiple_urls",
"fetch"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ecc3eea44f6bec40694a4a73c2000dd8963407fb | de4b4722748e892ce7a2adbb8b4aa36137d8256e | |||
v1.0 | instruct | Docs | Docs: Python310_27552_I | You are tasked with creating a function decorator named `log_exceptions` that logs detailed information about any exceptions that occur in the decorated function. The log should include the exception type, value, and traceback. The logging should be done in a format that mimics the behavior of the Python interpreter's ... | import traceback
def log_error(message: str, file: str):
with open(file, 'a') as f:
f.write(message + '\n')
def log_exceptions(log_file: str):
"""
Decorator that logs detailed information about any exceptions
that occur in the decorated function to a specified file.
"""
def decorator(... | import os
import pytest
from solution import log_exceptions, log_error
# Helper to read the log content
def read_log(file):
with open(file, 'r') as f:
return f.read()
def test_zero_division_error():
log_file = 'error.log'
@log_exceptions(log_file)
def test_function():
return 1 / 0... | [
{
"docstring": null,
"function_declaration": "def log_error(message, file):",
"function_name": "log_error",
"parameter_list": "(message, file)"
},
{
"docstring": "Decorator that logs detailed information about any exceptions \nthat occur in the decorated function to a specified file.",
"... | [
0,
0,
0,
1,
1,
0,
1,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import traceback\n\ndef log_error(message: str, file: str):\n with open(file, 'a') as f:\n f.write(message + '\\n')\n\ndef log_exceptions(log_file: str):\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00027552",
"row_id": 27552,
"seed_ids": "[335]"
} | 0.579893 | Docs: Python310_27552 | I | [
"log_error",
"log_exceptions"
] | 2 | [
[
"log_exceptions",
"log_error"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 05b09ce18e02c5ad014c70fc1dd6fa4e85acf827 | 8ef7815928f399c3c29fff522c6e14913449ec36 | |||
v1.0 | instruct | Docs | Docs: Python310_27632_I | ## Coding Assessment Question
### Objective
The goal of this exercise is to assess your understanding of the `asyncio` module in Python, especially handling concurrency, managing tasks, and enabling debugging features to catch common asynchronous programming pitfalls.
### Problem Statement
You are required to impleme... | import asyncio
import logging
from typing import List
from aiohttp import ClientSession
# Configure logging
logging.basicConfig(level=logging.DEBUG)
async def fetch_data(session: ClientSession, url: str) -> str:
try:
async with session.get(url) as response:
response.raise_for_status()
... | import pytest
from solution import fetch_data_from_sources
@pytest.mark.asyncio
async def test_all_successful_requests():
sources = ["http://example.com/1", "http://example.com/2"]
expected = ["Data from http://example.com/1", "Data from http://example.com/2"]
data = await fetch_data_from_sources(sources)
... | [] | [
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 logging\nfrom typing import List\nfrom aiohttp import ClientSession\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG)\n\nasync def... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00027632",
"row_id": 27632,
"seed_ids": "[200]"
} | 0.52855 | Docs: Python310_27632 | I | [
"fetch_data",
"fetch_data_from_sources"
] | 2 | [
[
"fetch_data_from_sources",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 7ba84723f68ba44fd235e05b154d1f9d5921534e | dcb84c9e60772631ffe4d7550b0f21e320ee36e2 | |||
v1.0 | instruct | Docs | Docs: Python310_27640_I | ### Coding Assessment: Chat Server Implementation with Non-Blocking Sockets
#### Objective
Implement a non-blocking chat server that can handle multiple clients simultaneously. The server should be able to broadcast messages received from any client to all connected clients.
#### Requirements
1. Create a non-blocking... | import socket
import select
def chat_server(host: str, port: int):
"""
Starts a non-blocking chat server that listens on the given host and port.
Args:
host (str): The hostname or IP address on which the server should listen.
port (int): The port number on which the server should listen.
... | import socket
import threading
import time
from solution import chat_server
def start_server():
chat_server("localhost", 12345)
def test_server():
# Start the chat server in a separate thread
server_thread = threading.Thread(target=start_server)
server_thread.daemon = True
server_thread.start()
... | [
{
"docstring": "Starts a non-blocking chat server that listens on the given host and port.\n\nArgs:\n host (str): The hostname or IP address on which the server should listen.\n port (int): The port number on which the server should listen.",
"function_declaration": "def chat_server(host, port):",
... | [
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 socket\nimport select\n\ndef chat_server(host: str, port: int):\n \"\"\"\n Starts a non-blocking chat server that listens on the given host and port.\n\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00027640",
"row_id": 27640,
"seed_ids": "[63]"
} | 0.688155 | Docs: Python310_27640 | I | [
"chat_server",
"broadcast"
] | 2 | [
[
"chat_server",
"broadcast"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 53d13b62c93d9828e3dd23cbebc1a17b57c6d9bd | 4af3bb0ca9853e2608c0a4f661055c0e2a0f59b3 | |||
v1.0 | instruct | Docs | Docs: Python310_27672_I | ### Python Coding Assessment Question
**Objective**: Demonstrate understanding of Python generators and their advanced implementations.
**Problem Statement**:
Generators are a special class of iterators in Python which allow you to iterate through a sequence of values produced dynamically. Write a Python function tha... | def is_prime(number):
"""Return True if number is a prime, else False."""
if number <= 1:
return False
if number <= 3:
return True
if number % 2 == 0 or number % 3 == 0:
return False
i = 5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
... | from solution import prime_generator
def prime_list_from_generator(generator, count):
"""Helper function to get a list of primes from the generator."""
return [next(generator) for _ in range(count)]
def test_first_five_primes():
gen = prime_generator()
first_five_primes = prime_list_from_generator(gen... | [
{
"docstring": "Return True if number is a prime, else False.",
"function_declaration": "def is_prime(number):",
"function_name": "is_prime",
"parameter_list": "(number)"
},
{
"docstring": "Generates an infinite sequence of prime numbers.",
"function_declaration": "def prime_generator():... | [
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 prime_generator():\n \"\"\"\n Generates an infinite sequence of prime numbers.\n \"\"\"\n def is_prime(number):\n \"\"\"Returns True if the numbe... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027672",
"row_id": 27672,
"seed_ids": "[27]"
} | 0.665506 | Docs: Python310_27672 | I | [
"is_prime",
"prime_generator"
] | 2 | [
[
"prime_generator",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7b0b416e29046f1fb56650cdd4975684084bbcfa | 6b34119c33d726621c1209c0d2aa981de901f7af | |||
v1.0 | instruct | Docs | Docs: Python310_27693_I | ### Interactive Python Shell Enhancer
You are to implement a simplified version of a Python shell that supports basic history management and tab completion. Your task is to write a function `interactive_shell()` which reads user inputs, stores them in a history, and provides tab completion suggestions for previously e... | import readline
def completer(text, state):
options = [cmd for cmd in command_history if cmd.startswith(text)]
if state < len(options):
return options[state]
else:
return None
def interactive_shell():
global command_history
command_history = []
# Enable auto-completion
... | import builtins
from solution import interactive_shell
def test_exit():
builtins.input = lambda _: "exit()"
interactive_shell() # Should terminate without any error
def test_history():
inputs = iter(["print('Hello, World!')", "MyFunction", "!history", "exit()"])
builtins.input = lambda _: next(inputs... | [
{
"docstring": null,
"function_declaration": "def completer(text, state):",
"function_name": "completer",
"parameter_list": "(text, state)"
},
{
"docstring": null,
"function_declaration": "def interactive_shell():",
"function_name": "interactive_shell",
"parameter_list": "()"
}... | [
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 readline\n\ndef interactive_shell():\n command_history = []\n \n def completer(text, state):\n options = [cmd for cmd in command_history if cmd.s... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00027693",
"row_id": 27693,
"seed_ids": "[427]"
} | 0.392288 | Docs: Python310_27693 | I | [
"completer",
"interactive_shell"
] | 2 | [
[
"interactive_shell",
"completer"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 680f434d5d4d615cffc8e39be827cd5238399e98 | a54288b1f2fd5e9912c39e5faab659726b10afd4 | |||
v1.0 | instruct | Docs | Docs: Python310_27697_I | ### Question
You are required to write a Python function named `analyze_module` that inspects a given Python module and extracts detailed information about its classes, functions, and methods. The information should include documentation strings, parameter lists, and identifying whether functions and methods are synchr... | import inspect
def extract_function_info(func):
"""Extract information about a given function or method."""
return {
'doc': inspect.getdoc(func),
'signature': str(inspect.signature(func)),
'is_async': inspect.iscoroutinefunction(func)
}
def analyze_module(module):
"""
Inspe... | import inspect
from types import ModuleType
# Mock module to test analyze_module function
class MockModule:
"""Example mock module for testing purposes."""
class TestClass:
"""Example class within mock module."""
def method_a(self):
"""Example method A."""
... | [
{
"docstring": "Extract information about a given function or method.",
"function_declaration": "def extract_function_info(func):",
"function_name": "extract_function_info",
"parameter_list": "(func)"
},
{
"docstring": "Inspects a given module and extracts details about its classes, function... | [
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 inspect\n\ndef analyze_module(module):\n \"\"\"\n Analyzes the given module and extracts detailed information about its classes,\n functions, and method... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027697",
"row_id": 27697,
"seed_ids": "[265]"
} | 0.690985 | Docs: Python310_27697 | I | [
"extract_function_info",
"analyze_module"
] | 2 | [
[
"analyze_module",
"extract_function_info"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | abda87c6d8f4c554e67649b4ae4571f8d1453ac5 | 93cb3036f17758cb5f6e85414625bcfc341c6482 | |||
v1.0 | instruct | Docs | Docs: Scikit_27726_I | **Question: Implementing and Analyzing K-Means Clustering on Synthetic and Real Datasets**
### Objective:
To assess the understanding of K-Means clustering, data preprocessing, dimensionality reduction, and evaluation metrics in the scikit-learn package.
### Task:
1. **Implement K-Means Clustering**:
- Write a fu... | import numpy as np
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn import metrics
from typing import Tuple, Dict
def kmeans_clustering(X: np.ndarray, n_clusters: int, init: str, max_iter: int, random_state: int) -> Tuple[np.ndarray, np.ndarray, float]:
"""
Perform K-Means ... | import numpy as np
from sklearn.datasets import load_iris
from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler
from solution import kmeans_clustering, evaluate_clustering
def test_kmeans_clustering():
X, _ = make_blobs(n_samples=100, centers=3, n_features=2, random_state=42)
... | [
{
"docstring": "Perform K-Means clustering on the dataset X.\n\nParameters:\n- X (np.ndarray): Dataset of shape (n_samples, n_features).\n- n_clusters (int): Number of clusters.\n- init (str): Initialization method, either 'random' or 'k-means++'.\n- max_iter (int): Maximum number of iterations.\n- random_state... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import adjusted_rand_score, normalized_mutual_info_s... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027726",
"row_id": 27726,
"seed_ids": "[60]"
} | 0.813564 | Docs: Scikit_27726 | I | [
"kmeans_clustering",
"evaluate_clustering"
] | 2 | [
[
"evaluate_clustering",
"kmeans_clustering"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 5dc507ab865866acdbd035e220381ccda79da3d6 | a6beefbc605e3cab5a1c02d7935a16bb663f9183 | |||
v1.0 | instruct | Docs | Docs: Python310_27732_I | ### Python Coding Assessment Question
#### Objective:
Create a Python module that defines several functions and uses the `if __name__ == '__main__':` idiom to conditionally run a script. The script should include taking user input, processing it, and providing an output.
#### Task:
1. **Define a Python module** tha... | def greet_user(name: str) -> str:
"""
Generate a greeting message for the user.
Parameters:
name (str): The name of the user.
Returns:
str: A greeting message.
"""
return f"Hello, {name}!"
def calculate_square(number: int) -> int:
"""
Calculate the square of a given number.... | from solution import greet_user, calculate_square, process_input
def test_greet_user():
assert greet_user("Alice") == "Hello, Alice!"
assert greet_user("Bob") == "Hello, Bob!"
assert greet_user("") == "Hello, !"
def test_calculate_square():
assert calculate_square(3) == 9
assert calculate_square(0... | [
{
"docstring": "Generate a greeting message for the user.\nParameters:\nname (str): The name of the user.\n\nReturns:\nstr: A greeting message.",
"function_declaration": "def greet_user(name):",
"function_name": "greet_user",
"parameter_list": "(name)"
},
{
"docstring": "Calculate the square... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def greet_user(name: str) -> str:\n \"\"\"\n Generate a greeting message for the user.\n \"\"\"\n if not name:\n raise ValueError(\"Name cannot be em... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027732",
"row_id": 27732,
"seed_ids": "[306]"
} | 0.511582 | Docs: Python310_27732 | I | [
"greet_user",
"calculate_square",
"process_input",
"main"
] | 4 | [
[
"process_input",
"calculate_square"
],
[
"process_input",
"greet_user"
]
] | 2 | [
"process_input"
] | false | [] | false | pytest | true | [] | true | 1f308a83559657c613208033bfa545ec07143320 | f9506afaa9026bc8df27ddfe5d42ae8d720f4bd2 | |||
v1.0 | instruct | Docs | Docs: Python310_27764_I | #### Context:
You are tasked with developing a simple tool that maintains individual user configurations in a multithreaded application. To achieve this, you will utilize `ContextVar` to store and reset user configurations during each request processing. Additionally, you will need to ensure that changes to the configu... | from contextvars import ContextVar
from concurrent.futures import ThreadPoolExecutor
# Initialize ContextVar for user configurations
user_config_var = ContextVar('user_config', default={"theme": "default", "notifications": "enabled"})
def process_user_request(user_id: int, config_changes: dict) -> dict:
# Get the... | from solution import process_user_request, handle_multiple_requests
def test_process_user_request_single_change():
result = process_user_request(1, {"theme": "dark mode"})
assert result == {"theme": "dark mode", "notifications": "enabled"}
def test_process_user_request_multiple_changes():
result = process... | [
{
"docstring": null,
"function_declaration": "def process_user_request(user_id, config_changes):",
"function_name": "process_user_request",
"parameter_list": "(user_id, config_changes)"
},
{
"docstring": null,
"function_declaration": "def handle_multiple_requests(requests):",
"functi... | [
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 contextvars import ContextVar\nfrom concurrent.futures import ThreadPoolExecutor\n\n# Initialize ContextVar for user configurations\nuser_config_var = ContextVar('... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027764",
"row_id": 27764,
"seed_ids": "[392]"
} | 0.428523 | Docs: Python310_27764 | I | [
"process_user_request",
"handle_multiple_requests"
] | 2 | [
[
"handle_multiple_requests",
"process_user_request"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 65e9887cfea566ef782fcb74ce311d30a2193372 | 3ee3c4fcf9254765ba8a07468e67abe80e5df7ad | |||
v1.0 | instruct | Docs | Docs: Python310_27788_I | #### Objective
Implement a secure password storage system using the `hashlib` module, focusing on key derivation, salting, and hashing. This assessment will test your understanding of fundamental and advanced concepts of Python’s `hashlib` module.
#### Task
1. Write a function `derive_key(password: str, salt: bytes, i... | import os
import hashlib
def derive_key(password, salt, iterations=100000, dklen=32):
"""
Derives a key from the given password and salt using PBKDF2-HMAC-SHA256.
Parameters:
password (str): The password to derive the key from.
salt (bytes): The salt to use in the derivation.
iterations (i... | import pytest
from solution import derive_key, hash_password, verify_password
def test_derive_key():
password = "testpassword"
salt = b"randomsalt"
iterations = 100000
dklen = 32
derived_key1 = derive_key(password, salt, iterations, dklen)
derived_key2 = derive_key(password, salt, iterations, d... | [
{
"docstring": "Derives a key from the given password and salt using PBKDF2-HMAC-SHA256.\n\nParameters:\npassword (str): The password to derive the key from.\nsalt (bytes): The salt to use in the derivation.\niterations (int): The number of iterations to perform (default: 100000).\ndklen (int): The length of th... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport hashlib\n\ndef derive_key(password, salt, iterations=100000, dklen=32):\n \"\"\"\n Derive a secure key from a given password using PBKDF2-HMAC.\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027788",
"row_id": 27788,
"seed_ids": "[225]"
} | 0.688759 | Docs: Python310_27788 | I | [
"derive_key",
"hash_password",
"verify_password"
] | 3 | [
[
"hash_password",
"derive_key"
],
[
"verify_password",
"derive_key"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b27208ba0ecb22bbd5675dfdfb7d9d852c6a4a03 | 69658379c2121303dd3df9475e8362a362547367 | |||
v1.0 | instruct | Docs | Docs: Python310_27817_I | #### Objective
To assess students' understanding and application of Python's debugging and profiling tools.
#### Problem Statement
You are given a Python function that performs several complex operations. Your task is to:
1. **Optimize the Function**: Analyze the performance of the given function using Python's profi... | import random
import numpy as np
def generate_matrix(n, m):
return [[random.randint(1, 100) for _ in range(m)] for _ in range(n)]
def optimized_matrix_multiplication(A, B):
"""
Optimized matrix multiplication using NumPy for better performance.
"""
return np.dot(A, B).tolist()
# Profiling Script:... | from solution import generate_matrix, optimized_matrix_multiplication
import numpy as np
def test_generate_matrix():
matrix = generate_matrix(3, 3)
assert len(matrix) == 3
assert len(matrix[0]) == 3
assert all(1 <= element <= 100 for row in matrix for element in row)
def test_optimized_matrix_multipli... | [
{
"docstring": null,
"function_declaration": "def generate_matrix(n, m):",
"function_name": "generate_matrix",
"parameter_list": "(n, m)"
},
{
"docstring": "Optimized matrix multiplication using NumPy for better performance.",
"function_declaration": "def optimized_matrix_multiplication(... | [
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\nimport numpy as np\n\ndef generate_matrix(n, m):\n return [[random.randint(1, 100) for _ in range(m)] for _ in range(n)]\n\ndef optimized_matrix_multi... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027817",
"row_id": 27817,
"seed_ids": "[364]"
} | 0.509651 | Docs: Python310_27817 | I | [
"generate_matrix",
"optimized_matrix_multiplication",
"profile_script",
"debug_script"
] | 4 | [
[
"debug_script",
"generate_matrix"
],
[
"debug_script",
"optimized_matrix_multiplication"
],
[
"profile_script",
"generate_matrix"
],
[
"profile_script",
"optimized_matrix_multiplication"
]
] | 4 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 3473c361a4ae3afc1a2de53a103946f452dd4573 | ed312fcbd9bffb6710378adb7cf67f5c24908b38 | |||
v1.0 | instruct | Docs | Docs: Python310_27865_I | ### Problem: Extract and Format Contact Information
You are given a string containing contact information of several individuals. The format of the string is as follows:
- Each individual's information is separated by a semicolon `;`.
- Each individual has a name, an email address, and a phone number, separated by co... | import re
def normalize_phone(phone):
# Remove everything that is not a digit
phone = re.sub(r'\D', '', phone)
# Format the phone number to 123-456-7890
return f"{phone[:3]}-{phone[3:6]}-{phone[6:]}"
def extract_contacts(info_string: str) -> list:
contacts = []
individuals = info_string.split(... | from solution import extract_contacts
def test_extract_contacts_standard_case():
info_string = "John Doe,john.doe@example.com,123-456-7890;Jane Smith,jane_smith@mail.com,(123) 456 7890"
result = extract_contacts(info_string)
assert result == [
{'name': 'John Doe', 'email': 'john.doe@example.com', '... | [
{
"docstring": null,
"function_declaration": "def normalize_phone(phone):",
"function_name": "normalize_phone",
"parameter_list": "(phone)"
},
{
"docstring": null,
"function_declaration": "def extract_contacts(info_string):",
"function_name": "extract_contacts",
"parameter_list":... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef normalize_phone(phone):\n # Remove everything that is not a digit\n phone = re.sub(r'\\D', '', phone)\n # Format the phone number to 123-456-7... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00027865",
"row_id": 27865,
"seed_ids": "[69]"
} | 0.58723 | Docs: Python310_27865 | I | [
"normalize_phone",
"extract_contacts"
] | 2 | [
[
"extract_contacts",
"normalize_phone"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5ae06fbf2c6780d7c863ae498e15716e0ab0d595 | d3067eceba1c7b2e90756acae7524906ead4f03c | |||
v1.0 | instruct | Docs | Docs: Python310_27888_I | #### Objective:
Design a Python function that simulates a simple set of concurrent tasks using the `asyncio` package. The function should demonstrate the creation of tasks, concurrent execution, and implementing timeouts.
#### Problem Statement:
Write an asynchronous function named `process_data_concurrently` that:
1... | import asyncio
import random
from typing import List
async def fetch_data(url: str):
print(f"Started fetching {url}")
await asyncio.sleep(random.uniform(1, 5))
print(f"Finished fetching {url}")
async def process_data(url: str):
print(f"Started processing {url}")
await asyncio.sleep(random.uniform(... | import pytest
import asyncio
from solution import process_data_concurrently
@pytest.mark.asyncio
async def test_process_data_concurrently_timeout():
urls = [
"http://example.com/resource1",
"http://example.com/resource2",
"http://example.com/resource3"
]
await process_data_concurren... | [] | [
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 random\nfrom typing import List\n\nasync def fetch_data(url: str):\n print(f\"Started fetching {url}\")\n await asyncio.sleep(random.unifor... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00027888",
"row_id": 27888,
"seed_ids": "[317]"
} | 0.553614 | Docs: Python310_27888 | I | [
"fetch_data",
"process_data",
"fetch_and_process",
"process_data_concurrently"
] | 4 | [
[
"fetch_and_process",
"fetch_data"
],
[
"fetch_and_process",
"process_data"
],
[
"process_data_concurrently",
"fetch_and_process"
]
] | 3 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 9a144a1bea0b75571bafe2ee137e888abb1390e3 | bcdb15160e951b759f5a15c84498756238026bc6 | |||
v1.0 | instruct | Docs | Docs: Python310_27911_I | ### Question: Parallel Task Execution with `concurrent.futures`
You are a software engineer at a company that processes large datasets. One of your tasks is to implement an efficient solution to calculate the factorial of a list of numbers concurrently, leveraging both multithreading and multiprocessing capabilities p... | import concurrent.futures
import math
from typing import List, Dict
def factorial(num: int) -> int:
return math.factorial(num)
def compute_factorials(numbers: List[int], use_threads: bool = True) -> Dict[int, int]:
result = {}
executor_class = concurrent.futures.ThreadPoolExecutor if use_threads else... | from solution import compute_factorials
def test_factorials_with_threads():
numbers = [5, 10, 15]
result = compute_factorials(numbers, use_threads=True)
expected = {5: 120, 10: 3628800, 15: 1307674368000}
assert result == expected
def test_factorials_with_processes():
numbers = [5, 10, 15]
res... | [] | [
0,
0,
0,
1,
1,
0,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict\nimport concurrent.futures\nfrom math import factorial\n\ndef compute_factorials(numbers: List[int], use_threads: bool = True) -> Dict[int... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00027911",
"row_id": 27911,
"seed_ids": "[347]"
} | 0.777416 | Docs: Python310_27911 | I | [
"factorial",
"compute_factorials"
] | 2 | [
[
"compute_factorials",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3309cc76d827e543cb07ed159523aa8e8c0d1578 | 5101e31de9b79cee7dea3dd12be0d29387f1d8c7 | |||
v1.0 | instruct | Docs | Docs: Python310_27937_I | ## Coding Assessment Question
Your task is to implement a secure messaging system that uses the HMAC (Keyed-Hashing for Message Authentication) algorithm to ensure message integrity and authenticity. The implementation should include both the creation of HMACs for messages and their verification.
### Function 1: `cre... | import hmac
import hashlib
def create_hmac(key: bytes, message: str, digestmod: str) -> str:
"""
Creates an HMAC for the given message using the provided secret key and hashing algorithm.
Params:
key (bytes): The secret key.
message (str): The message to be authenticated.
digestmod... | import pytest
from solution import create_hmac, verify_hmac
def test_create_hmac_sha256():
key = b'secret_key'
message = "authenticated_message"
digestmod = "sha256"
hmac_result = create_hmac(key, message, digestmod)
expected_result = hmac.new(key, message.encode(), digestmod).hexdigest()
... | [
{
"docstring": "Creates an HMAC for the given message using the provided secret key and hashing algorithm.\n\nParams:\n key (bytes): The secret key.\n message (str): The message to be authenticated.\n digestmod (str): The hashing algorithm (e.g., 'sha256').\n\nReturns:\n str: The hexadecimal string ... | [
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 hmac\nimport hashlib\n\ndef create_hmac(key: bytes, message: str, digestmod: str) -> str:\n \"\"\"\n Creates an HMAC for a given message using a secret key... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00027937",
"row_id": 27937,
"seed_ids": "[298]"
} | 0.78055 | Docs: Python310_27937 | I | [
"create_hmac",
"verify_hmac"
] | 2 | [
[
"verify_hmac",
"create_hmac"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 14e52da7fd3fc3e447468e09e0ad94a359850072 | de1b2c3cad716f3d5add1a09b97b771e6fd3c52a | |||
v1.0 | instruct | Docs | Docs: Python310_28013_I | ### Coding Challenge
**Objective:** Implement a message authentication system using HMAC. Your task is to write several functions to simulate the process of creating and verifying message digests using secret keys.
#### Functions to Implement:
1. **`create_hmac(key: bytes, message: bytes, digestmod: str) -> bytes`**... | import hmac
import hashlib
def create_hmac(key: bytes, message: bytes, digestmod: str) -> bytes:
"""
Creates an HMAC digest using the given key, message, and digestmod algorithm.
"""
hmac_obj = hmac.new(key, message, digestmod=getattr(hashlib, digestmod))
return hmac_obj.digest()
def verify_hmac(k... | import hmac
import hashlib
from solution import create_hmac, verify_hmac, update_hmac, secure_compare
def test_create_hmac():
key = b'secret_key'
message = b'This is a message'
digestmod = 'sha256'
expected_hmac = hmac.new(key, message, digestmod=hashlib.sha256).digest()
assert create_hmac(key, mes... | [
{
"docstring": "Creates an HMAC digest using the given key, message, and digestmod algorithm.",
"function_declaration": "def create_hmac(key, message, digestmod):",
"function_name": "create_hmac",
"parameter_list": "(key, message, digestmod)"
},
{
"docstring": "Verifies an HMAC digest using ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hmac\nimport hashlib\n\ndef create_hmac(key: bytes, message: bytes, digestmod: str) -> bytes:\n \"\"\"\n Create an HMAC digest for a given key and message ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028013",
"row_id": 28013,
"seed_ids": "[298]"
} | 0.774523 | Docs: Python310_28013 | I | [
"create_hmac",
"verify_hmac",
"update_hmac",
"secure_compare"
] | 4 | [
[
"verify_hmac",
"create_hmac"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ea4319e38e9d9724c7af35f3c457b5c02487cd8e | 685ea88ac07ee96e41e3df48282093fca57f3938 | |||
v1.0 | instruct | Docs | Docs: Python310_28070_I | ### UUID Toolkit
You are tasked with creating a toolkit leveraging the `uuid` module to handle a variety of tasks related to UUID generation, validation, and analysis.
#### Part 1: UUID Generation
1. Write a function `generate_random_uuids(n: int) -> list` that generates `n` random UUIDs (using `uuid4`). The functio... | import uuid
def generate_random_uuids(n: int) -> list:
"""
Generates n random UUIDs using uuid4 and returns a list of string representations.
"""
return [str(uuid.uuid4()) for _ in range(n)]
def generate_named_uuid(namespace: str, name: str, version=5) -> str:
"""
Generates a UUID based on the... | from solution import generate_random_uuids, generate_named_uuid, is_valid_uuid, uuid_attributes
def test_generate_random_uuids():
uuids = generate_random_uuids(5)
assert len(uuids) == 5
for u in uuids:
assert is_valid_uuid(u)
def test_generate_named_uuid_v5():
namespace = 'NAMESPACE_DNS'
n... | [
{
"docstring": "Generates n random UUIDs using uuid4 and returns a list of string representations.",
"function_declaration": "def generate_random_uuids(n):",
"function_name": "generate_random_uuids",
"parameter_list": "(n)"
},
{
"docstring": "Generates a UUID based on the given namespace and... | [
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 uuid\n\ndef generate_random_uuids(n: int) -> list:\n \"\"\"\n Generates `n` random UUIDs using uuid4.\n \"\"\"\n return [str(uuid.uuid4()) for _ in r... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00028070",
"row_id": 28070,
"seed_ids": "[295]"
} | 0.469808 | Docs: Python310_28070 | I | [
"generate_random_uuids",
"generate_named_uuid",
"is_valid_uuid",
"uuid_attributes"
] | 4 | [
[
"uuid_attributes",
"is_valid_uuid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 79fa3823aa4272e7919b57d454936247ea42c1ae | 4136bd058bfc6ec6322564d0d23d7a528e9f5a49 | |||
v1.0 | instruct | Docs | Docs: Python310_28087_I | ## Asynchronous TCP Chat Server and Client
### Objective
Implement an asynchronous TCP chat server and client using the asyncio streams functionality in Python. The server should be able to handle multiple clients, broadcasting messages from any client to all other clients connected to the server.
### Instructions
1... | import asyncio
import sys
clients = []
async def handle_client(reader, writer):
client_addr = writer.get_extra_info('peername')
print(f"New connection from {client_addr}")
clients.append(writer)
try:
while True:
data = await reader.read(100)
if not data:
... | import asyncio
import pytest
from solution import start_chat_server, chat_client
@pytest.fixture
async def chat_server():
server_task = asyncio.create_task(start_chat_server('127.0.0.1', 8888))
await asyncio.sleep(1) # Give server time to start
yield
server_task.cancel()
@pytest.mark.asyncio
async ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nclients = []\n\nasync def handle_client(reader, writer):\n client_address = writer.get_extra_info('peername')\n print(f\"New client connected: {... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028087",
"row_id": 28087,
"seed_ids": "[182]"
} | 0.677378 | Docs: Python310_28087 | I | [
"handle_client",
"broadcast",
"start_chat_server",
"chat_client"
] | 4 | [
[
"handle_client",
"broadcast"
],
[
"start_chat_server",
"handle_client"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b7bd0ff3250474226885f6c56a00b64a289669d9 | 0881db1b167829d6df183182882c951ec421dfcd | |||
v1.0 | instruct | Docs | Docs: Python310_28101_I | **Objective:** Demonstrate your understanding of Unicode handling in Python by writing functions that manipulate Unicode strings and characters using the APIs discussed in the documentation.
**Problem Statement:**
You are required to implement a function `unicode_transformer` that takes a list of mixed Unicode charac... | def is_whitespace(ch):
"""
Check if the given character is a whitespace.
"""
return ch.isspace()
def to_lowercase(ch):
"""
Convert the given character to its lowercase equivalent.
"""
return ch.lower()
def to_decimal_str(ch):
"""
Convert the given decimal character to its Unico... | from solution import unicode_transformer, is_whitespace, to_lowercase, to_decimal_str
def test_is_whitespace():
assert is_whitespace(' ') == True
assert is_whitespace('\t') == True
assert is_whitespace('A') == False
assert is_whitespace('1') == False
def test_to_lowercase():
assert to_lowercase('A... | [
{
"docstring": "Check if the given character is a whitespace.",
"function_declaration": "def is_whitespace(ch):",
"function_name": "is_whitespace",
"parameter_list": "(ch)"
},
{
"docstring": "Convert the given character to its lowercase equivalent.",
"function_declaration": "def to_lower... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_whitespace(ch):\n \"\"\"\n Checks if a character is a whitespace.\n \"\"\"\n return ch.isspace()\n\ndef to_lowercase(ch):\n \"\"\"\n Converts a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028101",
"row_id": 28101,
"seed_ids": "[29]"
} | 0.593207 | Docs: Python310_28101 | I | [
"is_whitespace",
"to_lowercase",
"to_decimal_str",
"unicode_transformer"
] | 4 | [
[
"unicode_transformer",
"is_whitespace"
],
[
"unicode_transformer",
"to_decimal_str"
],
[
"unicode_transformer",
"to_lowercase"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | c1df79d0ba288ee21537e13edf5f477d9d5c4983 | 5515b7da517fde5b767659c084aa115dd39cd78a | |||
v1.0 | instruct | Docs | Docs: Scikit_28124_I | ### SVM Classification Task
You are provided with a dataset `iris.csv`, which contains the famous Iris dataset. Your task is to implement a classification model using Support Vector Machines (SVM) from the scikit-learn library. Your solution should demonstrate the following:
1. Load and preprocess the data.
2. Implem... | import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.svm import SVC, LinearSVC
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.preprocessing import StandardScaler
def load_and_preprocess_data(file_path):
df = pd.read_csv(file_path)
X = df... | import pytest
from sklearn.datasets import load_iris
import pandas as pd
from tempfile import NamedTemporaryFile
from solution import load_and_preprocess_data, linear_svm_classification, rbf_svm_classification
@pytest.fixture
def iris_data():
iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.f... | [
{
"docstring": null,
"function_declaration": "def load_and_preprocess_data(file_path):",
"function_name": "load_and_preprocess_data",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def linear_svm_classification(X_train, y_train, X_test, y_test):",
"f... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.metrics import accuracy_sc... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028124",
"row_id": 28124,
"seed_ids": "[31]"
} | 0.693474 | Docs: Scikit_28124 | I | [
"load_and_preprocess_data",
"linear_svm_classification",
"rbf_svm_classification",
"svm_classification"
] | 4 | [
[
"svm_classification",
"linear_svm_classification"
],
[
"svm_classification",
"load_and_preprocess_data"
],
[
"svm_classification",
"rbf_svm_classification"
]
] | 3 | [] | false | [] | false | pytest | true | [
"pandas",
"sklearn"
] | false | e631b2c864fb34b685aafe133694c478e13823aa | c34e2952fd7eff9d0c7f823b80f0474e11bba2e6 | |||
v1.0 | instruct | Docs | Docs: Python310_28129_I | ### Advanced Coding Assessment: Custom Statistical Calculator
**Objective**: Demonstrate your understanding of the Python `math` module by creating a custom statistical calculator that performs various computations based on given data.
**Problem Statement**:
You need to implement a custom statistical calculator that... | import math
from typing import List
def calculate_mean(numbers: List[float]) -> float:
"""
Calculate the mean (average) of a given list of numbers.
"""
return sum(numbers) / len(numbers)
def calculate_std_deviation(numbers: List[float]) -> float:
"""
Calculate the standard deviation of a given... | import pytest
from solution import (calculate_mean, calculate_std_deviation, calculate_combination,
calculate_hypotenuse, degrees_to_radians)
def test_calculate_mean():
assert calculate_mean([1.0, 2.0, 3.0, 4.0, 5.0]) == 3.0
assert calculate_mean([10.0, 20.0, 30.0]) == 20.0
assert cal... | [
{
"docstring": "Calculate the mean (average) of a given list of numbers.",
"function_declaration": "def calculate_mean(numbers):",
"function_name": "calculate_mean",
"parameter_list": "(numbers)"
},
{
"docstring": "Calculate the standard deviation of a given list of numbers.",
"function_... | [
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 math\nfrom typing import List\n\ndef calculate_mean(numbers: List[float]) -> float:\n \"\"\"\n Returns the mean (average) of a given list of numbers.\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00028129",
"row_id": 28129,
"seed_ids": "[274]"
} | 0.625686 | Docs: Python310_28129 | I | [
"calculate_mean",
"calculate_std_deviation",
"calculate_combination",
"calculate_hypotenuse",
"degrees_to_radians"
] | 5 | [
[
"calculate_std_deviation",
"calculate_mean"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9873107ac8673d4475994405a1713981f9f36ddc | 881d01517261b3f8984f9e2665387c4939f2cdd2 | |||
v1.0 | instruct | Docs | Docs: Python310_28136_I | You are required to implement a simulation of an asynchronous task management system using the `asyncio` module and the `Future` class. The system should:
1. Create multiple asynchronous tasks that perform simple computations and set their results into Future objects after a delay.
2. Implement a function to manage th... | import asyncio
import random
from typing import List, Dict
async def task_runner(i: int, future: asyncio.Future):
# Simulate a delay
await asyncio.sleep(random.randint(1, 3))
# Set the future result
future.set_result(f'Task {i} completed')
def task_callback(fut: asyncio.Future):
print(f'Completed:... | import asyncio
import random
from solution import create_tasks, manage_tasks
def test_single_task():
async def test():
futures = await create_tasks(1)
results = await manage_tasks(futures)
assert results == {'Task 0': 'Task 0 completed'}
asyncio.run(test())
def test_multiple_tasks... | [
{
"docstring": null,
"function_declaration": "def task_callback(fut):",
"function_name": "task_callback",
"parameter_list": "(fut)"
}
] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\nfrom typing import List, Dict\n\nasync def task_runner(i: int, future: asyncio.Future):\n # Simulate a delay\n await asyncio.sleep(... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00028136",
"row_id": 28136,
"seed_ids": "[113]"
} | 0.562462 | Docs: Python310_28136 | I | [
"task_runner",
"task_callback",
"create_tasks",
"manage_tasks",
"main"
] | 5 | [
[
"create_tasks",
"task_callback"
],
[
"create_tasks",
"task_runner"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 923dbee91d26bc1bd26f996af7695a0f0c981284 | d19e71a0331365c42d699410afaf1ef8149d1cb5 | |||
v1.0 | instruct | Docs | Docs: Python310_28164_I | **Problem Statement:**
You are developing a multilingual application where users can switch between multiple languages at runtime. You need to create a system that supports loading translations from `.mo` files, switching languages dynamically, and using the translations in the application.
### Requirements:
1. **Se... | import gettext
def setup_translation(domain, localedir):
"""
Bind the domain to the given locale directory and set the domain for translations.
:param domain: The text domain (e.g., 'myapplication').
:param localedir: The directory where `.mo` files are located (e.g., '/path/to/my/language/directory')... | import os
import gettext
from solution import setup_translation, switch_language, translate
def test_setup_translation():
# Setup a fake translation environment for testing
domain = 'test_application'
localedir = '/tmp/test_translations'
os.makedirs(localedir, exist_ok=True)
# Create a .mo fil... | [
{
"docstring": "Bind the domain to the given locale directory and set the domain for translations.\n\n:param domain: The text domain (e.g., 'myapplication').\n:param localedir: The directory where `.mo` files are located (e.g., '/path/to/my/language/directory').",
"function_declaration": "def setup_translat... | [
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 gettext\n\ndef setup_translation(domain, localedir):\n \"\"\"\n Bind the domain to the given locale directory and set the domain for translations.\n\n :... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00028164",
"row_id": 28164,
"seed_ids": "[161]"
} | 0.463616 | Docs: Python310_28164 | I | [
"setup_translation",
"switch_language",
"translate"
] | 3 | [
[
"translate",
"setup_translation"
],
[
"translate",
"switch_language"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0a6e4b004cdd16a9b22091dd3905845cf15a86f1 | e7bb632f3b6cdcd18902c7254ca1a4db347082cc | |||
v1.0 | instruct | Docs | Docs: Pytorch_28196_I | **Coding Assessment Question**
### Objective
To assess your understanding of PyTorch's handling of deterministic algorithms and uninitialized memory, you will write a script that demonstrates the use of the `fill_uninitialized_memory` attribute and measures its impact on program determinism and performance.
### Probl... | import torch
import time
def generate_tensor(method: str, size: int) -> torch.Tensor:
if method == "A":
torch.utils.deterministic.fill_uninitialized_memory = True
elif method == "B":
torch.utils.deterministic.fill_uninitialized_memory = False
else:
raise ValueError("Invalid method. ... | import torch
from solution import generate_tensor, measure_time, demonstrate_determinism
def test_generate_tensor_valid():
tensor_a = generate_tensor("A", 1000)
tensor_b = generate_tensor("B", 1000)
assert tensor_a.size(0) == 1000
assert tensor_b.size(0) == 1000
assert isinstance(tensor_a, torch.Te... | [
{
"docstring": null,
"function_declaration": "def generate_tensor(method, size):",
"function_name": "generate_tensor",
"parameter_list": "(method, size)"
},
{
"docstring": null,
"function_declaration": "def measure_time(method, size):",
"function_name": "measure_time",
"parameter... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport time\n\ndef generate_tensor(method: str, size: int) -> torch.Tensor:\n if method == \"A\":\n torch.utils.deterministic.fill_uninitialized... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00028196",
"row_id": 28196,
"seed_ids": "[108]"
} | 0.433532 | Docs: Pytorch_28196 | I | [
"generate_tensor",
"measure_time",
"demonstrate_determinism"
] | 3 | [
[
"measure_time",
"generate_tensor"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | d0f813ad93186a62fe0d70c2ce08a386aee56c8f | 789f7226b780d573ea14cacabc3c3c3150c9190a | |||
v1.0 | instruct | Docs | Docs: Python310_28215_I | ## Question: Managing Multiple Subprocesses in Parallel
### Objective
You need to create a function that runs multiple shell commands asynchronously and captures their outputs concurrently using asyncio.
### Task
1. Write an asynchronous function `run_commands(commands: List[str]) -> List[Dict[str, Any]]` that takes ... | import asyncio
from typing import List, Dict, Any
async def run_command(command: str) -> Dict[str, Any]:
"""
Runs a single command and captures its output.
"""
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIP... | import asyncio
from solution import run_commands
def test_run_commands():
commands = [
'echo "Hello, World!"',
'ls /nonexistent_directory',
'sleep 1; echo "Done"'
]
# Running the commands
result = asyncio.run(run_commands(commands))
# Expected results
expected ... | [] | [
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, Dict, Any\n\nasync def run_single_command(command: str) -> Dict[str, Any]:\n proc = await asyncio.create_subprocess_shell(\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028215",
"row_id": 28215,
"seed_ids": "[264]"
} | 0.770724 | Docs: Python310_28215 | I | [
"run_command",
"run_commands"
] | 2 | [
[
"run_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2c6714c3dce1946e559cbb2fcffb4306bcaa5416 | 796ff35aef5a134cd0d27f4e35c916fe4bcbde80 | |||
v1.0 | instruct | Docs | Docs: Python310_28240_I | You are tasked with creating a Python script that runs an interactive child process, captures its output, and logs it to a file. Additionally, implement functionality that allows the parent process to send a specific command to the child process and terminate the session once a particular keyword is detected in the chi... | import pty
import os
import select
def read_and_log(fd, logfile, stop_keyword, timeout=0.1):
with open(logfile, "a") as log:
while True:
rlist, _, _ = select.select([fd], [], [], timeout)
if rlist:
output = os.read(fd, 1024).decode()
log.write(output)... | import os
import pytest
from solution import run_and_log_child_process
def test_run_and_log_child_process(tmpdir):
test_file = os.path.join(tmpdir, "logfile.log")
command = "echo 'test output'"
stop_keyword = "test"
exit_code = run_and_log_child_process(command, test_file, stop_keyword)
assert... | [
{
"docstring": null,
"function_declaration": "def read_and_log(fd, logfile, stop_keyword, timeout=0.1):",
"function_name": "read_and_log",
"parameter_list": "(fd, logfile, stop_keyword, timeout=0.1)"
},
{
"docstring": null,
"function_declaration": "def run_and_log_child_process(command, ... | [
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 pty\nimport os\nimport sys\n\ndef run_and_log_child_process(command: str, logfile: str, stop_keyword: str) -> int:\n \"\"\"\n Run a given command in an int... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028240",
"row_id": 28240,
"seed_ids": "[145]"
} | 0.60284 | Docs: Python310_28240 | I | [
"read_and_log",
"run_and_log_child_process"
] | 2 | [
[
"run_and_log_child_process",
"read_and_log"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 171320047940096803b06fed8fc74c3a5adc9c08 | 35a08b33e65f2fc69fa94d46e76ab73c5fc9a115 | |||
v1.0 | instruct | Docs | Docs: Python310_28274_I | You are tasked with writing a Python program that traverses a specific directory and generates a detailed report of all its files and subdirectories. Your program should utilize the "stat" module to gather this information effectively. This assignment aims to test your proficiency with file system attributes and modes,... | import os
import stat
import time
def format_time(epoch_time):
"""Formats the epoch time to a human-readable format."""
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epoch_time))
def get_file_type(mode):
"""Returns the type of the file based on the mode."""
if stat.S_ISREG(mode):
re... | from solution import traverse_and_report
from unittest.mock import patch, mock_open
import os
def test_traverse_and_report_empty_directory(tmp_path):
with patch('builtins.print') as mocked_print:
traverse_and_report(tmp_path)
mocked_print.assert_not_called()
def test_traverse_and_report_single_fil... | [
{
"docstring": "Formats the epoch time to a human-readable format.",
"function_declaration": "def format_time(epoch_time):",
"function_name": "format_time",
"parameter_list": "(epoch_time)"
},
{
"docstring": "Returns the type of the file based on the mode.",
"function_declaration": "def ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport stat\nimport time\n\ndef format_time(epoch_time):\n \"\"\"Formats the epoch time to a human-readable format.\"\"\"\n return time.strftime('%Y-%m... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00028274",
"row_id": 28274,
"seed_ids": "[373]"
} | 0.683171 | Docs: Python310_28274 | I | [
"format_time",
"get_file_type",
"traverse_and_report"
] | 3 | [
[
"traverse_and_report",
"format_time"
],
[
"traverse_and_report",
"get_file_type"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7e8ab82b76eecda0d43fb41eb335f0f12b8295bf | 85c4ce4b060aaa68f8690cc5022e9ca319fe639c | |||
v1.0 | instruct | Docs | Docs: Python310_28278_I | **Question:**
You are given a Python function that executes some operations. Your task is to profile this function, analyze the profiling data, and provide a report that highlights key performance metrics.
### Function to Profile
```python
def example_function():
import time
for i in range(5):
time.s... | import cProfile
import pstats
def profile_example_function():
# Profile the example_function and save the profiling data to a file
with cProfile.Profile() as pr:
example_function()
pr.dump_stats('example_profile.prof')
def print_profile_insights(profile_file: str):
# Load the profiling data
... | from solution import profile_example_function, print_profile_insights, example_function
import os
def test_profile_example_function():
# Ensure no existing profiling file before test
profile_file = 'example_profile.prof'
if os.path.exists(profile_file):
os.remove(profile_file)
# Profile th... | [
{
"docstring": null,
"function_declaration": "def profile_example_function():",
"function_name": "profile_example_function",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def print_profile_insights(profile_file):",
"function_name": "print_profile_insights",
... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cProfile\nimport pstats\n\ndef example_function():\n import time\n for i in range(5):\n time.sleep(0.1)\n for i in range(3):\n for j in ra... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00028278",
"row_id": 28278,
"seed_ids": "[142]"
} | 0.550916 | Docs: Python310_28278 | I | [
"profile_example_function",
"print_profile_insights",
"example_function"
] | 3 | [
[
"profile_example_function",
"example_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9ee9a001bbd3a7ccfc8dd467ab4d52e0747a2ec0 | 8775bd0c7dbd303e4012b6367ffa327dc2cac295 | |||
v1.0 | instruct | Docs | Docs: Python310_28282_I | ## Coding Assessment Question
### Objective
Demonstrate your understanding of parallel task execution using the `concurrent.futures` module in Python.
### Problem Statement
You are provided with a list of URLs. Your task is to write a Python function that downloads the contents of these URLs in parallel and returns... | import concurrent.futures
import requests
def fetch_content(url):
try:
response = requests.get(url)
response.raise_for_status()
return url, len(response.content)
except requests.RequestException:
return url, None
def fetch_url_contents(url_list: list) -> dict:
result = {}
... | from solution import fetch_url_contents
def test_fetch_url_contents_single_url(monkeypatch):
url_list = ["http://example.com"]
responses = {
"http://example.com": "Example content."
}
def mock_requests_get(url):
class MockResponse:
def __init__(self, text):
... | [
{
"docstring": null,
"function_declaration": "def fetch_content(url):",
"function_name": "fetch_content",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def fetch_url_contents(url_list):",
"function_name": "fetch_url_contents",
"parameter_list": "(url_... | [
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 concurrent.futures\nimport requests\n\ndef fetch_url_content(url):\n \"\"\"\n Helper function to fetch content from a single URL.\n \"\"\"\n try:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028282",
"row_id": 28282,
"seed_ids": "[224]"
} | 0.567987 | Docs: Python310_28282 | I | [
"fetch_content",
"fetch_url_contents"
] | 2 | [
[
"fetch_url_contents",
"fetch_content"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 1998eee815072fe121c70c6b91e1b85997cd7cdb | a206eefd96b66844ff8e9da8a828ab99597d8d34 | |||
v1.0 | instruct | Docs | Docs: Python310_28386_I | **Question: Efficient Data Processing with Itertools and Functools**
You are given a dataset of numbers, and your task is to perform a series of operations using `itertools` and `functools` to transform and analyze the data efficiently. Specifically, you need to implement a function `process_data` that:
1. Takes a li... | from itertools import combinations
from functools import reduce
from typing import List
def is_prime(n: int) -> bool:
"""
Returns True if the given number n is a prime number, otherwise False.
"""
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
... | from solution import process_data, is_prime, sum_combinations
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(1)
assert is_prime(13)
assert not is_prime(15)
assert is_prime(17)
def test_sum_combinations():
ass... | [
{
"docstring": "Returns True if the given number n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Given a list of integers, returns a list of sums of all possible combinations.",
"f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import combinations\nfrom functools import reduce\nfrom typing import List\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Check if the given integer i... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028386",
"row_id": 28386,
"seed_ids": "[387]"
} | 0.640492 | Docs: Python310_28386 | I | [
"is_prime",
"sum_combinations",
"process_data"
] | 3 | [
[
"process_data",
"is_prime"
],
[
"process_data",
"sum_combinations"
]
] | 2 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | ed9059ffb46577e4a08e5151cc47907951f60637 | f0a2cebe4246187892e50672be952fada1340602 | |||
v1.0 | instruct | Docs | Docs: Python310_28403_I | **File Organizer Script with Command-Line Interface**
**Objective**: Write a Python script that organizes files in a specified directory based on their file extensions. The script should be able to handle different types of file compressions and produce a summary report of the actions performed.
### Instructions:
1.... | import os
import shutil
import zipfile
import gzip
import bz2
import argparse
def organize_files(src_dir, dst_dir):
files_processed = 0
decompressed_files = 0
file_count_by_extension = {}
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for filename in os.listdir(src_dir):
sou... | import os
import shutil
import pytest
from solution import organize_files
@pytest.fixture
def setup_test_environment(tmp_path):
src_dir = tmp_path / "source"
dst_dir = tmp_path / "destination"
os.makedirs(src_dir)
os.makedirs(dst_dir)
# Create test files
(src_dir / "test1.txt").write_text("Thi... | [
{
"docstring": null,
"function_declaration": "def organize_files(src_dir, dst_dir):",
"function_name": "organize_files",
"parameter_list": "(src_dir, dst_dir)"
},
{
"docstring": null,
"function_declaration": "def decompress_file(file_path, ext):",
"function_name": "decompress_file",
... | [
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport shutil\nimport zipfile\nimport gzip\nimport bz2\nimport argparse\n\ndef organize_files(src_dir, dst_dir):\n file_count = 0\n decompressed_count ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00028403",
"row_id": 28403,
"seed_ids": "[422]"
} | 0.703336 | Docs: Python310_28403 | I | [
"organize_files",
"decompress_file",
"print_report"
] | 3 | [
[
"organize_files",
"decompress_file"
],
[
"organize_files",
"print_report"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3e1a800e99fc72eeef7e35229eed681abd33fd12 | 32d226940aaf630c77fe2edc7bc845a452af8b3c | |||
v1.0 | instruct | Docs | Docs: Python310_28424_I | ### Comprehensive Python310 Coding Assessment
#### Problem Statement:
You are required to use the `concurrent.futures` module to implement a function that processes a list of numbers to determine whether they are prime. The function should handle the task in parallel using both `ThreadPoolExecutor` and `ProcessPoolExe... | from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from typing import List, Tuple
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (... | from solution import check_prime_threadpool, check_prime_processpool
def test_check_prime_threadpool():
numbers = [29, 15, 18, 47, 77, 93, 97]
expected = [(29, True), (15, False), (18, False), (47, True), (77, False), (93, False), (97, True)]
assert sorted(check_prime_threadpool(numbers, max_workers=5)) ==... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def check_prime_threadpool(numbers, max_workers):",
"function_name": "check_prime_threadpool",
"parameter_list": ... | [
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, Tuple\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nimport math\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00028424",
"row_id": 28424,
"seed_ids": "[347]"
} | 0.613059 | Docs: Python310_28424 | I | [
"is_prime",
"check_prime_threadpool",
"check_prime_processpool"
] | 3 | [
[
"check_prime_processpool",
"is_prime"
],
[
"check_prime_threadpool",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3950b3c6c60863ae62269e686a6146c335397f3e | 2f96a48001675b4c9cd62bc8d718f8ec02695cd0 | |||
v1.0 | instruct | Docs | Docs: Python310_28553_I | ### AsyncIO Tasks and Synchronization
**Objective:**
Implement a function that demonstrates the ability to perform multiple asynchronous tasks concurrently and synchronize their results.
**Task:**
Write an asynchronous function `fetch_and_process` that simulates fetching data from three different sources concurrently... | import asyncio
async def fetch_data_source_1():
await asyncio.sleep(2)
return 'Data from source 1'
async def fetch_data_source_2():
await asyncio.sleep(3)
return 'Data from source 2'
async def fetch_data_source_3():
await asyncio.sleep(1)
return 'Data from source 3'
async def fetch_and_proce... | import asyncio
from solution import fetch_and_process
def test_fetch_and_process():
result = asyncio.run(fetch_and_process())
assert result == 'Data from source 1, Data from source 2, Data from source 3'
def test_fetch_and_process_runs_concurrently():
import time
start_time = time.time()
result =... | [] | [
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 fetch_data_source_1():\n await asyncio.sleep(2)\n return 'Data from source 1'\n\nasync def fetch_data_source_2():\n await asyncio.s... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028553",
"row_id": 28553,
"seed_ids": "[270]"
} | 0.561307 | Docs: Python310_28553 | I | [
"fetch_data_source_1",
"fetch_data_source_2",
"fetch_data_source_3",
"fetch_and_process"
] | 4 | [
[
"fetch_and_process",
"fetch_data_source_1"
],
[
"fetch_and_process",
"fetch_data_source_2"
],
[
"fetch_and_process",
"fetch_data_source_3"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ed8dd441acf39b5500efde58864d68911961c85d | 6b3d3b487608192ddb4abdd10bf60130a625e9ea | |||
v1.0 | instruct | Docs | Docs: Scikit_28625_I | You are given a binary classification task with a dataset containing feature vectors and corresponding binary labels. Your objective is to train a classifier, evaluate its probability calibration, and improve it if necessary. Follow the steps below to complete this task:
#### Step-by-Step Instructions:
1. **Data Prep... | import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import brier_score_loss
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
def plot_calibration_curve(y_true, probas_p... | import pandas as pd
import numpy as np
from sklearn.datasets import make_classification
from solution import evaluate_model_calibration
def test_evaluate_model_calibration(tmp_path):
# Creating a temporary data file
X, y = make_classification(n_samples=100, n_features=20, n_informative=2, n_redundant=10, rando... | [
{
"docstring": "Plot a calibration curve using the true labels and predicted probabilities. ",
"function_declaration": "def plot_calibration_curve(y_true, probas_pred, label, ax):",
"function_name": "plot_calibration_curve",
"parameter_list": "(y_true, probas_pred, label, ax)"
},
{
"docstrin... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.metri... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00028625",
"row_id": 28625,
"seed_ids": "[49]"
} | 0.505547 | Docs: Scikit_28625 | I | [
"plot_calibration_curve",
"evaluate_model_calibration"
] | 2 | [
[
"evaluate_model_calibration",
"plot_calibration_curve"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"pandas",
"sklearn"
] | false | ef4022e1ffc578be6094428ab6985cd1993b2287 | ff59ac7bc2ab7cae17e7681abb60ee6b8cc8e154 | |||
v1.0 | instruct | Docs | Docs: Python310_28627_I | ### XML-RPC Communication: Client-Server Implementation
**Objective:**
Your task is to implement an XML-RPC server and a corresponding client to demonstrate your understanding of remote procedure calls using Python's `xmlrpc` package. The communication should involve at least one function call from the client to the... | # Server-side implementation
from xmlrpc.server import SimpleXMLRPCServer
def add_numbers(x, y):
"""
Returns the sum of x and y.
"""
return x + y
def start_server():
server = SimpleXMLRPCServer(("localhost", 8000))
print("Server started at localhost:8000")
server.register_function(add_numb... | # Unit tests for the add_numbers function in the server
from solution import add_numbers
def test_add_numbers_positive():
assert add_numbers(2, 3) == 5
def test_add_numbers_with_zero():
assert add_numbers(0, 5) == 5
assert add_numbers(5, 0) == 5
def test_add_numbers_negative():
assert add_numbers(-1,... | [
{
"docstring": "Returns the sum of x and y.",
"function_declaration": "def add_numbers(x, y):",
"function_name": "add_numbers",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def start_server():",
"function_name": "start_server",
"parameter_list": "()... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Server-side implementation\nfrom xmlrpc.server import SimpleXMLRPCServer\n\ndef add_numbers(x, y):\n \"\"\"\n Function to add two numbers and return the result.... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00028627",
"row_id": 28627,
"seed_ids": "[280]"
} | 0.464549 | Docs: Python310_28627 | I | [
"add_numbers",
"start_server",
"main"
] | 3 | [
[
"start_server",
"add_numbers"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 21af2a306f14bee38b6a0cb713ed577f25017e66 | 3f8a6259d37fdecb01dbd0e192bfd4e5273c726b | |||
v1.0 | instruct | Docs | Docs: Pytorch_28685_I | **Objective:**
Implement a PyTorch distributed training setup using the `torch.distributed.fsdp.FullyShardedDataParallel` class. Utilize mixed precision and CPU offloading to demonstrate advanced functionalities provided by the `torch.distributed.fsdp` module.
**Problem Statement:**
You are given a neural network mod... | import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torchvision.models import resnet50
from torchvision import datasets, transforms
from torch.optim import SGD
from torch.utils.data import DataLoader, DistributedSampler
from torch.distributed.fsdp import FullyShardedDataParallel as FSD... | import pytest
import torch
import torch.distributed as dist
from torch.multiprocessing import get_start_method, set_start_method
@pytest.fixture(scope="module")
def setup_distributed_mode():
try:
if get_start_method() != "spawn":
try:
set_start_method("spawn")
except... | [
{
"docstring": null,
"function_declaration": "def setup():",
"function_name": "setup",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def cleanup():",
"function_name": "cleanup",
"parameter_list": "()"
},
{
"docstring": null,
"function_declara... | [
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\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torchvision.models import resnet50\nfrom torchvision import datasets, transform... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00028685",
"row_id": 28685,
"seed_ids": "[35]"
} | 0.500353 | Docs: Pytorch_28685 | I | [
"setup",
"cleanup",
"train"
] | 3 | [
[
"train",
"cleanup"
],
[
"train",
"setup"
]
] | 2 | [] | false | [] | false | pytest | false | [
"torch",
"torchvision"
] | false | 679e90128f726791f2c1bc8125815b4dcabef29a | 4561ae1a0e2294d08bc0264b03f9602780511d08 | |||
v1.0 | instruct | Docs | Docs: Python310_28694_I | ### Coding Challenge
**Objective**: You are to create a networked chat application using Python that demonstrates your understanding of the `asyncio`, `socket`, and `ssl` modules. The application should have both server-side and client-side components and should securely communicate using SSL.
#### Requirements
1. *... | import asyncio
import socket
import ssl
clients = []
async def start_server(host: str, port: int, ssl_context: ssl.SSLContext):
server = await asyncio.start_server(handle_client, host, port, ssl=ssl_context)
async with server:
await server.serve_forever()
async def handle_client(reader: asyncio.Strea... | import asyncio
import ssl
import pytest
from solution import start_server, connect_to_server, create_ssl_context
pytestmark = pytest.mark.asyncio
async def test_server_client_communication():
certfile = "server.crt"
keyfile = "server.key"
ssl_context = create_ssl_context(certfile, keyfile)
server = a... | [
{
"docstring": null,
"function_declaration": "def create_ssl_context(certfile, keyfile):",
"function_name": "create_ssl_context",
"parameter_list": "(certfile, keyfile)"
}
] | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport socket\nimport ssl\n\nclients = []\n\nasync def start_server(host: str, port: int, ssl_context: ssl.SSLContext):\n server = await asyncio.star... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00028694",
"row_id": 28694,
"seed_ids": "[151]"
} | 0.603437 | Docs: Python310_28694 | I | [
"start_server",
"handle_client",
"connect_to_server",
"create_ssl_context"
] | 4 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 17346e5af5e2cac4deba1eac4454c81183a7409c | 6a72d9d02e67a5a64c109afee5f42d9bccbe0b0d | |||
v1.0 | instruct | Docs | Docs: Python310_28738_I | As an advanced Python programmer, you are required to create a tool that automates the process of bundling a given Python project directory into an executable zip archive. This tool must also add a specified Python interpreter shebang line and handle potential compression of the archive.
### Task
Implement a Python f... | import os
import zipapp
def create_main_py(source_dir, main_function):
main_py_path = os.path.join(source_dir, "__main__.py")
module, func = main_function.split(":")
main_py_content = f"""
if __name__ == '__main__':
from {module} import {func}
{func}()
"""
with open(main_py_path, "w") as f:
... | import os
import zipapp
from solution import bundle_project_to_zipapp
def test_bundle_project_to_zipapp():
source_dir = "test_project"
output_file = "test_project.pyz"
interpreter = "/usr/bin/env python3"
main_function = "test_module:test_function"
# Setup: Create a test project directory with... | [
{
"docstring": null,
"function_declaration": "def create_main_py(source_dir, main_function):",
"function_name": "create_main_py",
"parameter_list": "(source_dir, main_function)"
},
{
"docstring": "Bundles a given Python project directory into an executable zip archive.\n\nArgs:\n source_d... | [
1,
0,
1,
0,
1,
0,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport zipapp\nfrom typing import Optional\n\ndef bundle_project_to_zipapp(source_dir: str, output_file: str, interpreter: Optional[str], main_function: str,... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00028738",
"row_id": 28738,
"seed_ids": "[315]"
} | 0.723403 | Docs: Python310_28738 | I | [
"create_main_py",
"bundle_project_to_zipapp"
] | 2 | [
[
"bundle_project_to_zipapp",
"create_main_py"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c6924f8845f56d409fe0ca73dc8f23a390f10667 | 166dee0199167d80d7f32e94090703f511c40736 | |||
v1.0 | instruct | Docs | Docs: Python310_28755_I | #### File Organizer and Report Generator
### Objective
Design and implement a Python program that organizes files in a given directory based on their extensions and generates a summary report. The program should utilize features from the provided `python310` documentation, specifically focusing on file operations, com... | import os
import shutil
import argparse
import re
from datetime import datetime
import glob
def organize_files(input_dir, target_dir='organized_files', include_hidden=False):
if not os.path.isdir(input_dir):
raise ValueError("Input directory does not exist.")
if not os.path.exists(target_dir):
... | import os
import pytest
import shutil
from solution import organize_files
@pytest.fixture
def setup_test_environment(tmp_path):
input_dir = tmp_path / "input"
target_dir = tmp_path / "output"
input_dir.mkdir()
target_dir.mkdir()
# Create some test files
(input_dir / "file1.txt").write_text... | [
{
"docstring": null,
"function_declaration": "def organize_files(input_dir, target_dir='organized_files', include_hidden=False):",
"function_name": "organize_files",
"parameter_list": "(input_dir, target_dir='organized_files', include_hidden=False)"
},
{
"docstring": null,
"function_decl... | [
1,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport shutil\nimport argparse\nimport datetime\n\ndef organize_files(input_dir, target_dir, include_hidden):\n \"\"\"\n Organizes files in the given i... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00028755",
"row_id": 28755,
"seed_ids": "[422]"
} | 0.677457 | Docs: Python310_28755 | I | [
"organize_files",
"create_summary_report"
] | 2 | [
[
"organize_files",
"create_summary_report"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eb133f3c4b2b6b323454b40360e7b1beff89d6b5 | 38da29725e50ac46ad2a4091a5c15579d65519f7 | |||
v1.0 | instruct | Docs | Docs: Python310_28776_I | ### Question:
You are tasked with developing a small application that performs CPU-intensive calculations asynchronously, while handling logging and ensuring debugging information is available. Implement the following functions based on the given constraints.
- `perform_calculations(n)`: This is a CPU-bound function ... | import asyncio
import logging
from concurrent.futures import ThreadPoolExecutor
# Function to perform CPU-bound calculations
def perform_calculations(n):
logging.debug(f"Performing calculations for n={n}")
return sum(i*i for i in range(1, n+1))
# Function to schedule calculations asynchronously
async def sche... | import pytest
from solution import run_main, perform_calculations
def test_perform_calculations():
assert perform_calculations(5) == 55 # 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 55
@pytest.mark.asyncio
async def test_schedule_calculations():
loop = asyncio.get_event_loop()
n_vals = [1, 2, 3]
expected_results =... | [
{
"docstring": null,
"function_declaration": "def perform_calculations(n):",
"function_name": "perform_calculations",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def run_main(n_vals):",
"function_name": "run_main",
"parameter_list": "(n_vals)"
}
] | [
1,
0,
1,
1,
1,
0,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport logging\nfrom concurrent.futures import ThreadPoolExecutor\n\n# Function to perform CPU-bound calculations\ndef perform_calculations(n):\n \"\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00028776",
"row_id": 28776,
"seed_ids": "[200]"
} | 0.541823 | Docs: Python310_28776 | I | [
"perform_calculations",
"schedule_calculations",
"main",
"run_main"
] | 4 | [
[
"run_main",
"main"
],
[
"schedule_calculations",
"perform_calculations"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 29d1d44a52a6ae931e0b1274a320c6402d4a79e7 | 8867359ed2a69d9e7e082c215fead90f19b12d6d | |||
v1.0 | instruct | Docs | Docs: Python310_28797_I | #### Objective
Design a program using the `os` module to recursively search for a specific file type and replace environment variables in those files with their actual values from the system's environment.
#### Problem Statement
You need to create a Python script named `replace_env_vars.py` that performs the following... | import os
import sys
import re
def replace_env_vars_in_file(file_path):
"""
Reads the file, replaces environment variable placeholders with actual values and writes back to the file.
Placeholders are in the format ${VAR_NAME}.
"""
with open(file_path, 'r') as file:
content = file.read()
... | import os
import tempfile
from solution import replace_env_vars_in_file, search_and_replace
def setup_test_env(directory, filename, content):
"""
Helper function to setup a test file with specified content.
"""
file_path = os.path.join(directory, filename)
with open(file_path, 'w') as file:
... | [
{
"docstring": "Reads the file, replaces environment variable placeholders with actual values and writes back to the file.\nPlaceholders are in the format ${VAR_NAME}.",
"function_declaration": "def replace_env_vars_in_file(file_path):",
"function_name": "replace_env_vars_in_file",
"parameter_list":... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport sys\nimport re\n\ndef traverse_and_replace(directory, file_extension):\n \"\"\"\n Recursively traverse the given directory and replace environme... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00028797",
"row_id": 28797,
"seed_ids": "[106]"
} | 0.485808 | Docs: Python310_28797 | I | [
"replace_env_vars_in_file",
"search_and_replace"
] | 2 | [
[
"search_and_replace",
"replace_env_vars_in_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 335c7b9993cf416ba5b128b76e92b361a1cdc5bd | 9d31c68172fe4971869ef47184dffb1ed57dd051 | |||
v1.0 | instruct | Docs | Docs: Python310_28807_I | **Objective**: Write a Python function `process_manifest` that processes a list of file patterns associated with commands to include and exclude files and returns the final list of files to be included in the distribution manifest.
**Function Signature**:
```python
def process_manifest(file_list: list, commands: list)... | import fnmatch
import os
def process_manifest(file_list, commands):
included_files = set()
for command_tuple in commands:
command = command_tuple[0]
patterns = command_tuple[1]
if command == "include":
for pattern in patterns:
include_files(file_list, p... | from solution import process_manifest
def test_include_exclude():
file_list = [
"src/module1.py",
"src/module2.py",
"src/data/data1.dat",
"src/data/data2.dat",
"scripts/install.sh",
"scripts/uninstall.sh",
"docs/readme.md"
]
commands = [
("inc... | [
{
"docstring": null,
"function_declaration": "def process_manifest(file_list, commands):",
"function_name": "process_manifest",
"parameter_list": "(file_list, commands)"
},
{
"docstring": null,
"function_declaration": "def include_files(file_list, pattern, included_files, base_dir=None):... | [
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport fnmatch\n\ndef process_manifest(file_list, commands):\n inclusion_set = set(file_list) # All files initially considered for inclusion\n\n for c... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00028807",
"row_id": 28807,
"seed_ids": "[430]"
} | 0.582784 | Docs: Python310_28807 | I | [
"process_manifest",
"include_files",
"exclude_files",
"prune_dir",
"graft_dir"
] | 5 | [
[
"process_manifest",
"exclude_files"
],
[
"process_manifest",
"graft_dir"
],
[
"process_manifest",
"include_files"
],
[
"process_manifest",
"prune_dir"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | eb4211123a6bc3188f000eae79fa196477dcd413 | e3a60e8d35fed981b18c47fe880632e254ad0cf4 | |||
v1.0 | instruct | Docs | Docs: Python310_28812_I | ## Coding Assessment Question
**Problem Statement:**
You are given an XML file that contains information about various books in a catalog. Each book has the following structure:
```xml
<book id="bk101">
<author>Author Name</author>
<title>Book Title</title>
<genre>Genre</genre>
<price>Price</price>
... | import xml.etree.ElementTree as ET
def parse_books(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
books = []
for book in root.findall('book'):
book_data = {
'id': book.attrib['id'],
'author': book.find('author').text,
'title': book.find('title').t... | from solution import parse_books, generate_book_report
def test_parse_books():
books = parse_books('test_books.xml')
assert len(books) == 2
assert books[0]['id'] == 'bk101'
assert books[0]['title'] == "XML Developer's Guide"
assert books[1]['price'] == 5.95
def test_generate_book_report(capsys):
... | [
{
"docstring": null,
"function_declaration": "def parse_books(xml_file):",
"function_name": "parse_books",
"parameter_list": "(xml_file)"
},
{
"docstring": null,
"function_declaration": "def generate_book_report(xml_file):",
"function_name": "generate_book_report",
"parameter_lis... | [
1,
0,
0,
1,
0,
1,
0,
0,
1
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import xml.etree.ElementTree as ET\n\ndef parse_books(xml_file):\n \"\"\"\n Parse the books from the given XML file and return a list of dictionaries.\n \"\"\"... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00028812",
"row_id": 28812,
"seed_ids": "[283]"
} | 0.512991 | Docs: Python310_28812 | I | [
"parse_books",
"generate_book_report"
] | 2 | [
[
"generate_book_report",
"parse_books"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ded15f52f60660cf1cac0478941a72e47c906a36 | 6a87c5a4f2c9640faf105bd4edc288310c99a0c6 | |||
v1.0 | instruct | Docs | Docs: Python310_28882_I | **CSV File Processing with Custom Dialects**
You are required to create a Python script that reads data from an existing CSV file, processes the data, and writes the processed data to a new CSV file using custom dialects. Follow the guidelines below to accomplish this task:
1. **Reading the CSV File**:
- Read data... | import csv
def register_my_dialect():
"""
Registers a custom CSV dialect with the specified formatting parameters.
"""
csv.register_dialect(
'my_dialect',
delimiter=';',
quotechar='"',
quoting=csv.QUOTE_MINIMAL
)
def unregister_my_dialect():
"""
Unregisters ... | import csv
import os
from solution import process_csv, register_my_dialect, unregister_my_dialect
def setup_module(module):
with open("input.csv", "w", newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["name", "age", "city"])
writer.writerow(["Alice", "17", "new york"])
... | [
{
"docstring": "Registers a custom CSV dialect with the specified formatting parameters.",
"function_declaration": "def register_my_dialect():",
"function_name": "register_my_dialect",
"parameter_list": "()"
},
{
"docstring": "Unregisters the custom CSV dialect.",
"function_declaration":... | [
1,
1,
1,
0,
1,
0,
1,
0,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\n\ndef register_my_dialect():\n \"\"\"\n Registers a custom CSV dialect with the specified formatting parameters.\n \"\"\"\n csv.register_dialect... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00028882",
"row_id": 28882,
"seed_ids": "[272]"
} | 0.652145 | Docs: Python310_28882 | I | [
"register_my_dialect",
"unregister_my_dialect",
"process_csv"
] | 3 | [
[
"process_csv",
"register_my_dialect"
],
[
"process_csv",
"unregister_my_dialect"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 27f77b8cac71b745de9341f3119f965137b85a12 | f6d07c660e1830b2ec92fd3325c4ced426066351 | |||
v1.0 | instruct | Docs | Docs: Python310_28884_I | You are tasked with implementing a signal handling mechanism in Python. Your objective is to create a function that sets up a signal handler to catch a user-defined signal (`SIGUSR1`) and perform a custom action when this signal is received.
### Function Signature
```python
def setup_signal_handler():
pass
```
##... | import signal
import os
def signal_handler(signum, frame):
print("User-defined signal received")
def setup_signal_handler():
# Set up the signal handler for SIGUSR1
signal.signal(signal.SIGUSR1, signal_handler)
# Sending SIGUSR1 to the current process
os.kill(os.getpid(), signal.SIGUSR1) | import signal
import os
import subprocess
def test_signal_handler(capsys):
# Function to call within a subprocess to avoid interference with pytest execution
setup_signal_handler()
# Capture output
captured = capsys.readouterr()
assert "User-defined signal received" in captured.out | [
{
"docstring": null,
"function_declaration": "def signal_handler(signum, frame):",
"function_name": "signal_handler",
"parameter_list": "(signum, frame)"
},
{
"docstring": null,
"function_declaration": "def setup_signal_handler():",
"function_name": "setup_signal_handler",
"param... | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\nimport os\n\ndef signal_handler(signum, frame):\n print(\"User-defined signal received\")\n\ndef setup_signal_handler():\n # Setting up the signal ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00028884",
"row_id": 28884,
"seed_ids": "[253]"
} | 0.4971 | Docs: Python310_28884 | I | [
"signal_handler",
"setup_signal_handler"
] | 2 | [
[
"setup_signal_handler",
"signal_handler"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 7649220a40ce4caa64223d2525eaaba73ed35f69 | afd00ea755d5e9c75de1bb7957da2a7163e78f24 | |||
v1.0 | instruct | Docs | Docs: Python310_28908_I | ### Question: Log File Analyzer
**Objective:**
Write a Python program that analyzes log files to gather specific statistics. This program should process multiple log files concurrently and output the gathered statistics in a structured format.
**Details:**
You are given a directory containing multiple log files. Eac... | import os
from concurrent.futures import ThreadPoolExecutor
def count_logs_in_file(log_file_path):
"""
Counts the number of logs and categories in a log file.
:param log_file_path: Path to the log file
:return: A dictionary with counts of log levels and total logs
"""
log_counts = {'info': 0, ... | import os
import pytest
from solution import analyze_log_files
def create_log_file(directory, filename, content):
"""
Creates a log file with the specified content.
"""
with open(os.path.join(directory, filename), 'w') as file:
file.write(content)
@pytest.fixture
def setup_log_directory(tmpdir... | [
{
"docstring": "Counts the number of logs and categories in a log file.\n\n:param log_file_path: Path to the log file\n:return: A dictionary with counts of log levels and total logs",
"function_declaration": "def count_logs_in_file(log_file_path):",
"function_name": "count_logs_in_file",
"parameter_... | [
1,
0,
1,
1,
1,
1,
1,
1,
0,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef process_log_file(file_path):\n stats = {\n 'total_logs': 0,\n 'info': 0,\n '... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00028908",
"row_id": 28908,
"seed_ids": "[255]"
} | 0.643571 | Docs: Python310_28908 | I | [
"count_logs_in_file",
"analyze_log_files"
] | 2 | [
[
"analyze_log_files",
"count_logs_in_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 35b7e2b6ec2cb481571304dbf93b360af1720b83 | 9b2001b8bd8dcb679d1e3fe73c774e84766fe69f | |||
v1.0 | instruct | Docs | Docs: Scikit_28944_I | **Out-of-Core Learning with Scikit-learn**
In this question, you will implement an out-of-core learning pipeline using scikit-learn. You need to work with a large dataset that cannot fit into memory all at once. You will build a system that streams data, extracts features using the hashing trick, and trains an increme... | import numpy as np
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
def stream_data(file_path, batch_size):
"""
Generator function that reads from a large file and yields mini-batches of data.
:param file_path: str, File path to the large dataset... | import os
from tempfile import NamedTemporaryFile
from solution import stream_data, train_incremental_classifier
def create_temp_file(content):
"""
Utility function to create a temporary file with the provided content.
"""
temp_file = NamedTemporaryFile(delete=False, mode='w')
temp_file.write(conte... | [
{
"docstring": "Generator function that reads from a large file and yields mini-batches of data.\n\n:param file_path: str, File path to the large dataset.\n:param batch_size: int, The number of examples per mini-batch.\n:return: generator yielding tuples (X_batch, y_batch).",
"function_declaration": "def st... | [
0,
1,
1,
1,
1,
1,
1,
0,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\n\ndef stream_data(file_path, batch_si... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00028944",
"row_id": 28944,
"seed_ids": "[63]"
} | 0.449926 | Docs: Scikit_28944 | I | [
"stream_data",
"train_incremental_classifier"
] | 2 | [
[
"train_incremental_classifier",
"stream_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | f4cca313230d8eac6f56b4c144b4f7d808a14c53 | e566cdedf609c68b2cfe0299e679f66cef82fff6 | |||
v1.0 | instruct | Docs | Docs: Scikit_28972_I | ### Decision Tree Implementation and Evaluation
#### Objective:
To test the understanding and application of decision trees in scikit-learn for classification and regression tasks, including handling missing values, pruning, and visualizing the decision tree.
#### Task:
1. **Decision Tree Classification**:
a. Load... | import numpy as np
from sklearn.datasets import load_iris, load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, plot_tree
from sklearn.metrics import accuracy_score, mean_squared_error
import matplotlib.pyplot as plt
# Function to in... | from solution import (decision_tree_classification, decision_tree_regression,
handle_missing_values, decision_tree_pruning)
def test_decision_tree_classification():
accuracy, _ = decision_tree_classification()
assert isinstance(accuracy, float)
assert accuracy > 0.5
def test_dec... | [
{
"docstring": null,
"function_declaration": "def introduce_missing_values(X, percentage=0.1):",
"function_name": "introduce_missing_values",
"parameter_list": "(X, percentage=0.1)"
},
{
"docstring": null,
"function_declaration": "def decision_tree_classification():",
"function_name"... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.datasets import load_iris, load_diabetes\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeCl... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00028972",
"row_id": 28972,
"seed_ids": "[50]"
} | 0.549502 | Docs: Scikit_28972 | I | [
"introduce_missing_values",
"decision_tree_classification",
"decision_tree_regression",
"handle_missing_values",
"decision_tree_pruning"
] | 5 | [
[
"handle_missing_values",
"introduce_missing_values"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"sklearn"
] | false | 0a5a60cbd75a0bc135b792cc3a0790108bd715d5 | 81c33a27e6d53888982b300ff49c0768185857ee | |||
v1.0 | instruct | Docs | Docs: Python310_28978_I | **Objective:**
You are tasked with implementing a high-level asynchronous function that fetches and processes data from multiple sources concurrently. This will test your understanding of coroutines, the asyncio library, and its high-level APIs.
**Question:**
You are given a list of URLs, each containing data in JSO... | import aiohttp
import asyncio
from typing import List, Dict, Any
async def fetch_data(session: aiohttp.ClientSession, url: str) -> Dict[str, Any]:
async with session.get(url) as response:
data = await response.json()
return {
'id': data.get('id'),
'name': data.get('name'),
... | import pytest
from typing import List, Dict, Any
import asyncio
from aiohttp import web
@pytest.mark.asyncio
async def test_fetch_and_process_data():
# Set up a mock server to provide responses
async def mock_handler(request):
return web.json_response({"id": 123, "name": "Test", "value": 456})
ap... | [] | [
1,
0,
1,
1,
1,
1,
0,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import aiohttp\nimport asyncio\nfrom typing import List, Dict, Any\n\nasync def fetch_data(url: str) -> Dict[str, Any]:\n async with aiohttp.ClientSession() as sessi... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00028978",
"row_id": 28978,
"seed_ids": "[270]"
} | 0.573481 | Docs: Python310_28978 | I | [
"fetch_data",
"fetch_and_process_data"
] | 2 | [
[
"fetch_and_process_data",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 98fe3f8791d36fb6fafc7185d61ec96125f5a6ed | c19f9c63f04e961777200d74f69e85b1c50c1541 | |||
v1.0 | instruct | Docs | Docs: Python310_29084_I | ### Question
You are tasked with designing a simple chat server and client using Python's `socket` module. The chat server should be capable of handling multiple clients simultaneously and allow them to send and receive messages in real-time. Implement both the server and the client.
#### Requirements
1. The server m... | # chat_server.py
import socket
import selectors
# Create a selector object
sel = selectors.DefaultSelector()
clients = {}
HOST = 'localhost'
PORT = 12345
def accept(sock):
conn, addr = sock.accept() # Should be ready to read
print('Connected by', addr)
conn.setblocking(False)
sel.register(conn, sel... | # test_chat.py
import socket
import threading
import time
# Test the server setup by attempting to create a connection
def test_server_setup():
server_thread = threading.Thread(target=run_server)
server_thread.daemon = True
server_thread.start()
time.sleep(1) # Wait a moment for the server to start
... | [
{
"docstring": null,
"function_declaration": "def accept(sock):",
"function_name": "accept",
"parameter_list": "(sock)"
},
{
"docstring": null,
"function_declaration": "def read(conn):",
"function_name": "read",
"parameter_list": "(conn)"
},
{
"docstring": null,
"func... | [
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": "# chat_server.py\nimport socket\nimport selectors\n\nsel = selectors.DefaultSelector()\n\ndef accept(sock, mask):\n conn, addr = sock.accept() # Should be ready\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00029084",
"row_id": 29084,
"seed_ids": "[151]"
} | 0.652209 | Docs: Python310_29084 | I | [
"accept",
"read",
"broadcast",
"main",
"read",
"main"
] | 6 | [
[
"accept",
"read"
]
] | 1 | [] | false | [] | false | pytest | false | [
"chat_server"
] | false | 254e305f7fc22b100a4f91db04040d464172a3f5 | 47e22943e7ebb17e93d5c88fd3a517c3914fabc2 | |||
v1.0 | instruct | Docs | Docs: Scikit_29091_I | Using the scikit-learn library, you are required to design a data preprocessing pipeline to handle missing data and perform a classification task.
## Dataset
You will use the iris dataset and simulate missing values.
## Tasks
1. **Load the Iris Dataset**: Load the Iris dataset and introduce missing values randomly.
... | import numpy as np
from sklearn.datasets import load_iris
from sklearn.impute import SimpleImputer, MissingIndicator
from sklearn.pipeline import FeatureUnion, make_pipeline
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
# Load the Iris dataset and introduce missin... | from solution import load_data_with_missing_values, create_pipeline, train_and_evaluate
def test_load_data_with_missing_values():
X, y = load_data_with_missing_values()
assert X.shape == (150, 4)
assert y.shape == (150,)
assert np.isnan(X).sum() > 0
def test_create_pipeline():
pipeline = create_pi... | [
{
"docstring": null,
"function_declaration": "def load_data_with_missing_values():",
"function_name": "load_data_with_missing_values",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def create_pipeline():",
"function_name": "create_pipeline",
"parameter_l... | [
0,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.impute import SimpleImputer, MissingIndicator\nfrom sklearn.pipeline import FeatureUnion, make_... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00029091",
"row_id": 29091,
"seed_ids": "[32]"
} | 0.499771 | Docs: Scikit_29091 | I | [
"load_data_with_missing_values",
"create_pipeline",
"train_and_evaluate"
] | 3 | [
[
"train_and_evaluate",
"create_pipeline"
],
[
"train_and_evaluate",
"load_data_with_missing_values"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 6cff1c517565c75e8bec018cbd9b9ac31550fa57 | 409f38053139df62c758e431bf076dc62d3b1d83 | |||
v1.0 | instruct | Docs | Docs: Python310_29095_I | ### Coding Assessment: Implement a Custom Python Profiler using the `sys` module
#### Objective
Your task is to implement a Python profiling utility that uses the `sys.setprofile` functionality to track function call durations within a given Python script. Profiling is essential for performance optimization and unders... | import sys
import time
# Dictionary to keep track of the start time of each function call
profile_data = {}
def profile(frame, event, arg):
function_name = frame.f_code.co_name
if event == "call":
# Record the start time when a function is called
profile_data[function_name] = time.time()
... | import os
import time
import pytest
from solution import enable_profiling, disable_profiling
def test_function():
time.sleep(1)
def test_function_nested():
time.sleep(1)
test_function()
def test_no_profiling_output_exists_before_enabling():
if os.path.exists("profile.txt"):
os.remove("pro... | [
{
"docstring": null,
"function_declaration": "def profile(frame, event, arg):",
"function_name": "profile",
"parameter_list": "(frame, event, arg)"
},
{
"docstring": null,
"function_declaration": "def enable_profiling():",
"function_name": "enable_profiling",
"parameter_list": "(... | [
0,
0,
1,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nimport time\n\n# Dictionary to store the start time of function calls\ncall_timings = {}\n\n# List to store the profiling information\nprofile_data = []\n\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029095",
"row_id": 29095,
"seed_ids": "[348]"
} | 0.591961 | Docs: Python310_29095 | I | [
"profile",
"enable_profiling",
"disable_profiling"
] | 3 | [
[
"enable_profiling",
"profile"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 53f905f30d85b78f4019e34bd4958124f86719b9 | b39886a27ffcd0b7989edb536f52e8ef7a769119 | |||
v1.0 | instruct | Docs | Docs: Python310_29110_I | ### Unix Group Analysis Tool
#### Problem Statement
You are required to implement functions to retrieve, analyze, and manipulate Unix group data using the `grp` module. The functions should cover different aspects, from fetching information about specific groups to summarizing and filtering available groups based on ... | import grp
def get_group_by_gid(gid):
"""
Returns group information as a dictionary given a group ID (gid).
"""
if not isinstance(gid, int):
raise ValueError("gid must be an integer")
try:
group = grp.getgrgid(gid)
return {
"name": group.gr_name,
... | import pytest
from unittest.mock import patch, Mock
from solution import (get_group_by_gid, get_group_by_name, get_all_groups,
filter_groups_by_member, get_users_with_multiple_groups)
@patch('grp.getgrgid')
def test_get_group_by_gid(mock_getgrgid):
mock_group = Mock(gr_name="staff", gr_pass... | [
{
"docstring": "Returns group information as a dictionary given a group ID (gid).",
"function_declaration": "def get_group_by_gid(gid):",
"function_name": "get_group_by_gid",
"parameter_list": "(gid)"
},
{
"docstring": "Returns group information as a dictionary given a group name.",
"fun... | [
1,
1,
0,
0,
1,
0,
1,
1
] | 5 | medium | 0.625 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import grp\n\ndef get_group_by_gid(gid):\n if not isinstance(gid, int):\n raise ValueError(\"gid must be an integer.\")\n try:\n group = grp.getgrgi... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029110",
"row_id": 29110,
"seed_ids": "[268]"
} | 0.480865 | Docs: Python310_29110 | I | [
"get_group_by_gid",
"get_group_by_name",
"get_all_groups",
"filter_groups_by_member",
"get_users_with_multiple_groups"
] | 5 | [
[
"filter_groups_by_member",
"get_all_groups"
],
[
"get_users_with_multiple_groups",
"get_all_groups"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 626a212003db97347edf0ff30af87adbcfdd7622 | 7b0ca0a2c9944e85bf3a40aa779bd36fdcf73854 | |||
v1.0 | instruct | Docs | Docs: Scikit_29165_I | ### Question: Implementing and Training a Bernoulli Restricted Boltzmann Machine
**Objective**: Implement and train a Bernoulli Restricted Boltzmann Machine (RBM) using the learning algorithm discussed — Stochastic Maximum Likelihood (SML).
**Task**: Write a function `train_rbm(data, n_hidden, learning_rate, n_iterat... | import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def train_rbm(data, n_hidden, learning_rate, n_iterations):
n_samples, n_visible = data.shape
# Initialize weights and biases
np.random.seed(0)
weights = np.random.randn(n_visible, n_hidden) * 0.01
visible_bias = np.zeros(n_vi... | from solution import train_rbm
import numpy as np
def test_rbm_shapes():
data = np.array([
[0, 1, 1, 0, 1],
[1, 0, 1, 1, 0],
[0, 1, 0, 1, 0],
[1, 0, 0, 1, 1]
])
n_hidden = 3
learning_rate = 0.1
n_iterations = 1000
weights, v_bias, h_bias, samples = train_rbm(data... | [
{
"docstring": null,
"function_declaration": "def sigmoid(x):",
"function_name": "sigmoid",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def train_rbm(data, n_hidden, learning_rate, n_iterations):",
"function_name": "train_rbm",
"parameter_list": "(dat... | [
1,
1,
0,
0,
0,
0,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef sigmoid(x):\n \"\"\"\n Sigmoid activation function.\n \"\"\"\n return 1.0 / (1 + np.exp(-x))\n\ndef sample_binary(prob_matrix):\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00029165",
"row_id": 29165,
"seed_ids": "[59]"
} | 0.535228 | Docs: Scikit_29165 | I | [
"sigmoid",
"train_rbm"
] | 2 | [
[
"train_rbm",
"sigmoid"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 1e4acd9c1c76df50957c07a08d624e789a451882 | 0ad3637de1d98567bd5b1beed82a3dd259c34820 | |||
v1.0 | instruct | Docs | Docs: Pytorch_29219_I | ### Question:
You are tasked with implementing a function in PyTorch using the `torch.func` transformations, ensuring no side effects and adhering to the limitations described.
**Task:**
1. Implement a function `batched_relu` using `vmap` that applies a rectified linear unit (ReLU) to a batch of input tensors. Your ... | import torch
from torch.func import vmap, grad
def batched_relu(x: torch.Tensor) -> torch.Tensor:
"""
Applies the rectified linear unit (ReLU) function to a batch of input tensors.
:param x: A 2D tensor of shape (batch_size, features).
:return: A 2D tensor of the same shape as the input, with ReLU app... | from solution import batched_relu, grad_batched_relu
import torch
def test_batched_relu():
x = torch.tensor([[-1.0, 2.0], [3.0, -4.0], [5.0, -6.0]])
result = batched_relu(x)
expected = torch.tensor([[0.0, 2.0], [3.0, 0.0], [5.0, 0.0]])
assert torch.equal(result, expected)
def test_grad_batched_relu():... | [
{
"docstring": "Applies the rectified linear unit (ReLU) function to a batch of input tensors.\n\n:param x: A 2D tensor of shape (batch_size, features).\n:return: A 2D tensor of the same shape as the input, with ReLU applied element-wise.",
"function_declaration": "def batched_relu(x):",
"function_name"... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef batched_relu(x: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Applies the rectified linear unit (ReLU) function to a batch of input tensors.\n\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029219",
"row_id": 29219,
"seed_ids": "[136]"
} | 0.518564 | Docs: Pytorch_29219 | I | [
"batched_relu",
"grad_batched_relu"
] | 2 | [
[
"grad_batched_relu",
"batched_relu"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 0d6ca4ff052478b1991dba28a651f5383907503c | 726903045140129470a1a932f326edb100e173a9 | |||
v1.0 | instruct | Docs | Docs: Pytorch_29234_I | ### PyTorch Coding Assessment
**Objective**: Demonstrate your ability to utilize PyTorch's `torch.func` functionality, particularly focusing on `vmap` and `grad`, while adhering to the limitations and constraints described.
### Question
You are to write a function `batched_cosine_similarity` that computes the cosine... | import torch
from torch.func import vmap, grad
def batched_cosine_similarity(batch1: torch.Tensor, batch2: torch.Tensor) -> torch.Tensor:
"""
Computes the cosine similarity between two batches of vectors using vmap for batch processing.
Parameters:
- batch1 (torch.Tensor): A tensor of shape (n, d)... | import torch
from solution import batched_cosine_similarity, grad_batched_cosine_similarity
def test_batched_cosine_similarity_validity():
batch1 = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
batch2 = torch.tensor([[1.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
expected = torch.tensor([1.0, 0.0])
result = bat... | [
{
"docstring": "Computes the cosine similarity between two batches of vectors using vmap for batch processing.\n\nParameters:\n- batch1 (torch.Tensor): A tensor of shape (n, d) containing n vectors each of dimension d.\n- batch2 (torch.Tensor): A tensor of shape (n, d) containing n vectors each of dimension d.\... | [
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 torch\nfrom torch.func import vmap, grad\n\ndef batched_cosine_similarity(batch1: torch.Tensor, batch2: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Calculate... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029234",
"row_id": 29234,
"seed_ids": "[136]"
} | 0.514347 | Docs: Pytorch_29234 | I | [
"batched_cosine_similarity",
"grad_batched_cosine_similarity"
] | 2 | [
[
"grad_batched_cosine_similarity",
"batched_cosine_similarity"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 465c9b622d9cc5e7a361f2e5a9edfc4d35efe5b8 | 5bdd5e8db81e986327ccd2c51b6aef5df5bed4eb | |||
v1.0 | instruct | Docs | Docs: Python310_29248_I | **Title:** Implementing and Using Generators in Python
**Objective:**
Assess your understanding of Python generators by implementing custom generator functions and using them in various scenarios. This question will test your ability to handle lazy evaluation, memory efficiency, and writing clean, readable code.
**P... | def fibonacci_sequence(n):
"""
Generator to return Fibonacci sequence up to n terms
"""
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
def square_sequence(seq_gen):
"""
Generator to return the square of numbers from the provided sequence generator
"""
for num... | from solution import fibonacci_sequence, square_sequence, sum_of_squares
def test_fibonacci_sequence():
fib_gen = fibonacci_sequence(5)
assert list(fib_gen) == [0, 1, 1, 2, 3]
def test_square_sequence():
fib_gen = fibonacci_sequence(5)
square_gen = square_sequence(fib_gen)
assert list(square_gen) ... | [
{
"docstring": "Generator to return Fibonacci sequence up to n terms",
"function_declaration": "def fibonacci_sequence(n):",
"function_name": "fibonacci_sequence",
"parameter_list": "(n)"
},
{
"docstring": "Generator to return the square of numbers from the provided sequence generator",
... | [
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 fibonacci_sequence(n):\n \"\"\"\n Generator that yields the first n terms of the Fibonacci sequence.\n \n Parameters:\n n (int): Number of terms to g... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029248",
"row_id": 29248,
"seed_ids": "[27]"
} | 0.634538 | Docs: Python310_29248 | I | [
"fibonacci_sequence",
"square_sequence",
"sum_of_squares"
] | 3 | [
[
"sum_of_squares",
"fibonacci_sequence"
],
[
"sum_of_squares",
"square_sequence"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 828452a386c7c6ba060b1d9d2c7a2d4bb4e2af29 | 640baf552615679887c2449e062c5e38d0d4bb9d | |||
v1.0 | instruct | Docs | Docs: Python310_29250_I | ### Complex Network Application using asyncio Event Loop
#### Problem Statement:
You are tasked with implementing a simplified network monitoring tool using the asyncio event loop functionalities. This tool will act as both a client and a server. The server part listens for incoming connections and echoes back any re... | import asyncio
async def handle_client(reader, writer):
try:
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message} from {addr}")
print(f"Echoing: {message}")
writer.write(data)
awai... | import asyncio
import pytest
from solution import handle_client, start_server, run_client
@pytest.mark.asyncio
async def test_server_client_interaction():
host = '127.0.0.1'
port = 8889
message = 'Test Message'
server_task = asyncio.create_task(start_server(host, port))
await asyncio.sleep(1)... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n \"\"\"\n Handle client connections and echo received messages.\n \"\"\"\n try:\n data = ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029250",
"row_id": 29250,
"seed_ids": "[267]"
} | 0.64195 | Docs: Python310_29250 | I | [
"handle_client",
"start_server",
"run_client",
"main"
] | 4 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a918f85c22e37c19c0259bc53624da0154fa49cd | aee922089054613239e0a8fea60a4f965ed2658f | |||
v1.0 | instruct | Docs | Docs: Pandas_29312_I | #### Objective:
To assess students' understanding of pandas extensions by implementing and utilizing custom ExtensionArray and associated features.
#### Task:
You need to implement a custom pandas ExtensionArray to handle a simple data type and integrate it into a pandas DataFrame. The custom ExtensionArray should re... | from pandas.api.extensions import ExtensionArray, ExtensionDtype, register_extension_dtype
import numpy as np
import pandas as pd
class HalfFloatDtype(ExtensionDtype):
name = 'HalfFloat'
type = np.float64
na_value = np.nan
@classmethod
def construct_array_type(cls):
return HalfFloatAr... | def test_half_float_array_initialization():
data = [0.5, 1.0, 2.5, np.nan]
arr = HalfFloatArray(data)
assert len(arr) == 4
assert arr[0] == 0.5
assert np.isnan(arr[3])
def test_half_float_dtype():
assert HalfFloatDtype().name == 'HalfFloat'
assert isinstance(HalfFloatDtype().na_value, floa... | [] | [
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": "from pandas.api.extensions import ExtensionArray, ExtensionDtype, register_extension_dtype\nimport numpy as np\nimport pandas as pd\n\ndef round_to_half(x):\n \"\"\"... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00029312",
"row_id": 29312,
"seed_ids": "[44]"
} | 0.568646 | Docs: Pandas_29312 | I | [
"generate_half_float_data",
"create_half_float_dataframe"
] | 2 | [
[
"create_half_float_dataframe",
"generate_half_float_data"
]
] | 1 | [] | false | [
"HalfFloatDtype",
"HalfFloatArray",
"HalfFloatDtype"
] | true | pytest | false | [
"numpy",
"pandas"
] | false | 2dd314a3c286d8d84c358fdd15a1f80c9ef2b768 | 18e794b60acd74d6281574201ec7de4e54af8f83 | |||
v1.0 | instruct | Docs | Docs: Python310_29351_I | **Question: Implement a Multi-Layer Window Manager Using curses.panel**
### Objective:
You are required to implement a multi-layer window manager using the "curses.panel" module. Your task involves creating multiple panels, manipulating their stack order, and handling their visibility based on user input.
### Functio... | import curses
import curses.panel
def window_manager(stdscr) -> None:
curses.curs_set(0) # Hide the default cursor
stdscr.nodelay(0) # Make getch() blocking to wait for user input
max_y, max_x = stdscr.getmaxyx()
# Create windows
win1 = curses.newwin(max_y//3, max_x//3, 0, 0)
win2 = cur... | # Unit test code requires interaction which is challenging to automate.
# For testing UI components like this, end-to-end tests with a tool like 'pytest-curses' or manual testing is usually preferred.
# Here's a simple manual test guide:
# 1. Run the program.
# 2. Press '1', '2', '3' to toggle visibility of the panels... | [
{
"docstring": null,
"function_declaration": "def window_manager(stdscr):",
"function_name": "window_manager",
"parameter_list": "(stdscr)"
},
{
"docstring": null,
"function_declaration": "def toggle_visibility(panel):",
"function_name": "toggle_visibility",
"parameter_list": "(p... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import curses\nimport curses.panel\n\ndef window_manager(stdscr):\n curses.curs_set(0) # Hide the default cursor\n stdscr.nodelay(1) # Make getch() non-blockin... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029351",
"row_id": 29351,
"seed_ids": "[157]"
} | 0.34003 | Docs: Python310_29351 | I | [
"window_manager",
"toggle_visibility",
"move_panel",
"main"
] | 4 | [
[
"window_manager",
"move_panel"
],
[
"window_manager",
"toggle_visibility"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 7ba0f3477338af584a5915ca15287173c1b30234 | f659b2ae10035a5522655eecddaf17f02467bf82 | |||
v1.0 | instruct | Docs | Docs: Python310_29402_I | **Question:** Implement a simple chat server and client using the `socket` module in Python. The server should accept multiple client connections and broadcast messages sent by any client to all connected clients. Both the server and the clients should be able to run on separate machines but should handle basic errors ... | import socket
import threading
def broadcast_message(message, clients):
for client in clients:
try:
client.sendall(message.encode())
except:
client.close()
clients.remove(client)
def handle_client(client_socket, clients):
while True:
try:
... | import socket
import pytest
import threading
from time import sleep
def test_server_can_accept_clients():
server_ip = '127.0.0.1'
server_port = 5000
server_thread = threading.Thread(target=start_server, args=(server_ip, server_port))
server_thread.daemon = True
server_thread.start()
sleep(1) ... | [
{
"docstring": null,
"function_declaration": "def broadcast_message(message, clients):",
"function_name": "broadcast_message",
"parameter_list": "(message, clients)"
},
{
"docstring": null,
"function_declaration": "def handle_client(client_socket, clients):",
"function_name": "handle... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# chat_server.py\nimport socket\nimport select\n\ndef broadcast(server_socket, message, clients):\n for client in clients:\n if client != server_socket:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029402",
"row_id": 29402,
"seed_ids": "[151]"
} | 0.670246 | Docs: Python310_29402 | I | [
"broadcast_message",
"handle_client",
"start_server",
"client_program"
] | 4 | [
[
"handle_client",
"broadcast_message"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | df111a19fbafe8e606be0f3adda15a528d52fe46 | e8388f481f2cca7fff88592faee78918933cad59 | |||
v1.0 | instruct | Docs | Docs: Python310_29446_I | ### Advanced Python310 Coding Assessment: Working with Cell Objects
#### Objective
This exercise is designed to test your understanding of the `PyCellObject` and its various operations. You will be required to implement a series of functions that manipulate and utilize cell objects as described.
#### Instructions
Imp... | def create_cell(value):
"""
Creates a new cell object containing the given value.
"""
class Cell:
"""Represents a simple cell to hold a single value."""
def __init__(self, value):
self.value = value
return Cell(value)
def get_cell_value(cell):
"""
Returns the va... | from solution import create_cell, get_cell_value, set_cell_value, exchange_cell_values
def test_create_and_get_cell_value():
cell = create_cell(10)
assert get_cell_value(cell) == 10
def test_set_cell_value():
cell = create_cell(10)
set_cell_value(cell, 20)
assert get_cell_value(cell) == 20
def te... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def create_cell(value):\n \"\"\"\n Creates a cell object containing the given value.\n \n Args:\n value: Any Python object.\n \n Returns:\n A ce... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00029446",
"row_id": 29446,
"seed_ids": "[38]"
} | 0.46938 | Docs: Python310_29446 | I | [
"create_cell",
"get_cell_value",
"set_cell_value",
"exchange_cell_values"
] | 4 | [
[
"exchange_cell_values",
"set_cell_value"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 561a61cc76c564ee4c2d3cc0e7b9d1b409128404 | 3725d6022f6d8cfcfe84f50f6a81cc70877c8d2d | |||
v1.0 | instruct | Docs | Docs: Python310_29461_I | ### Custom Priority Queue Implementation
You work for a task management software development company. Your team is enhancing its core library to manage tasks with priorities using the heapq module. The requirements are as follows:
1. **Add a new task** or **update the priority of an existing task**.
2. **Remove a tas... | import heapq
import itertools
REMOVED = '<removed-task>'
def add_task(pq, task, priority, entry_finder, counter):
"""
Add a new task or update the priority of an existing task.
"""
if task in entry_finder:
remove_task(pq, task, entry_finder)
count = next(counter)
entry = [priority, cou... | import pytest
def test_add_and_pop_task():
pq = []
entry_finder = {}
counter = itertools.count()
add_task(pq, 'task1', 1, entry_finder, counter)
add_task(pq, 'task2', 2, entry_finder, counter)
assert pop_task(pq, entry_finder) == 'task1'
assert pop_task(pq, entry_finder) == 'task2'
def t... | [
{
"docstring": "Add a new task or update the priority of an existing task.",
"function_declaration": "def add_task(pq, task, priority, entry_finder, counter):",
"function_name": "add_task",
"parameter_list": "(pq, task, priority, entry_finder, counter)"
},
{
"docstring": "Mark an existing ta... | [
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 heapq\nimport itertools\n\nREMOVED = '<removed-task>' # Placeholder for a removed task\n\ndef add_task(pq, task, priority, entry_finder, counter):\n \"\"\"\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029461",
"row_id": 29461,
"seed_ids": "[241]"
} | 0.556151 | Docs: Python310_29461 | I | [
"add_task",
"remove_task",
"pop_task"
] | 3 | [
[
"add_task",
"remove_task"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 22effb748c4f79927f7871542c5365f3d3e77d27 | 38b97306360a989169c1c1f91f85caa41b739e1f | |||
v1.0 | instruct | Docs | Docs: Python310_29500_I | **Objective:**
Demonstrate your understanding of the `signal` module in Python by implementing a program that involves setting custom signal handlers and using timers.
You are required to:
1. Implement a custom signal handler for `SIGALRM` that will print the current timestamp each time it is triggered.
2. Set up an... | import signal
import time
from datetime import datetime
def timestamp_handler(signum, frame):
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
def sigint_handler(signum, frame):
print('Received SIGINT. Shutting down gracefully...')
signal.setitimer(signal.ITIMER_REAL, 0) # Disable the interval timer
... | import pytest
import signal
import subprocess
import time
def test_setup_signal_handlers():
proc = subprocess.Popen(['python3', 'solution.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Allow the process to run for a few cycles
time.sleep(7)
# Send SIGINT to the process
proc.send_sign... | [
{
"docstring": null,
"function_declaration": "def timestamp_handler(signum, frame):",
"function_name": "timestamp_handler",
"parameter_list": "(signum, frame)"
},
{
"docstring": null,
"function_declaration": "def sigint_handler(signum, frame):",
"function_name": "sigint_handler",
... | [
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 signal\nimport time\nfrom datetime import datetime\n\ndef timestamp_handler(signum, frame):\n print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n\ndef sigin... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00029500",
"row_id": 29500,
"seed_ids": "[253]"
} | 0.525839 | Docs: Python310_29500 | I | [
"timestamp_handler",
"sigint_handler",
"setup_signal_handlers",
"run_timer"
] | 4 | [
[
"setup_signal_handlers",
"sigint_handler"
],
[
"setup_signal_handlers",
"timestamp_handler"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 63fee20836380e09700e7e108a488a74509b7dc1 | 1c036608db4371b312ed91bb49619d7a5ca03177 | |||
v1.0 | instruct | Docs | Docs: Python310_29515_I | You are required to implement a function that wraps the `zipapp.create_archive` functionality and adds some additional validation and logging. The function should:
- Create an archive from a given directory, adding a shebang line with a specified Python interpreter.
- Allow optional compression of the archive.
- Valida... | import os
import zipapp
from datetime import datetime
def log_message(log_file, message):
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open(log_file, 'a') as f:
f.write(f"{timestamp} - {message}\n")
def create_executable_archive(source, target, interpreter, compress=False, log_file='c... | import os
import pytest
from unittest.mock import patch, mock_open
from solution import create_executable_archive, log_message
def test_create_executable_archive_success(tmpdir):
source = tmpdir.mkdir("source")
source.join("__main__.py").write("print('Hello, World!')")
target = tmpdir.join("myapp.pyz")
... | [
{
"docstring": null,
"function_declaration": "def log_message(log_file, message):",
"function_name": "log_message",
"parameter_list": "(log_file, message)"
},
{
"docstring": "Create an executable Python archive from a source directory.\n\nParameters:\n- source (str): Path to the source direc... | [
0,
0,
0,
0,
0,
0,
1,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport zipapp\nimport logging\nfrom datetime import datetime\n\ndef create_executable_archive(source, target, interpreter, compress=False, log_file='creation... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00029515",
"row_id": 29515,
"seed_ids": "[315]"
} | 0.777326 | Docs: Python310_29515 | I | [
"log_message",
"create_executable_archive"
] | 2 | [
[
"create_executable_archive",
"log_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cd3065c9e707f889df16e4ef02866500d53c0f7a | 8ddc18e73e1e79a349a1101fbebdc7b302a0a702 | |||
v1.0 | instruct | Docs | Docs: Python310_29559_I | **Title: Asyncio Concurrency and Debugging**
**Objective**: To assess the student's understanding of asyncio's concurrency mechanisms, enabling debug mode, running blocking code in an executor, and handling potential pitfalls such as unawaited coroutines and unhandled exceptions.
**Problem Statement**:
You are taske... | import asyncio
import logging
from typing import List
def factorial(n: int) -> int:
if n == 0:
return 1
else:
return n * factorial(n-1)
async def fetch_and_process_data(url: str) -> str:
# Simulate fetching data
await asyncio.sleep(1)
# Offload CPU-bound task to a separate thr... | import asyncio
import logging
from solution import fetch_and_process_data, main
async def test_fetch_and_process_data():
url = "http://example.com"
result = await fetch_and_process_data(url)
assert "processed with factorial 3628800" in result
async def test_main():
urls = ["http://example.com/data1", ... | [
{
"docstring": null,
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
}
] | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport logging\nfrom typing import List\n\ndef factorial(n: int) -> int:\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00029559",
"row_id": 29559,
"seed_ids": "[200]"
} | 0.465359 | Docs: Python310_29559 | I | [
"factorial",
"fetch_and_process_data",
"main"
] | 3 | [
[
"fetch_and_process_data",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1b025242fd371d96d91ffb47228515bd31f48820 | c9498c0f0dd8ea242019155096774fb741a3bb37 | |||
v1.0 | instruct | Docs | Docs: Python310_29564_I | **Problem Statement:**
You are developing a secure file verification system. The system will generate a hash for each file and store these hashes in a repository. Later, when the files need to be verified, the system will re-compute the hash for each file and compare it with the stored hash to ensure that the file has... | import hashlib
def generate_file_hash(file_path: str, algorithm: str = 'sha256') -> str:
"""
Generate the hash of a file's contents using the specified algorithm.
Args:
- file_path (str): The path to the file to hash.
- algorithm (str): The hashing algorithm to use ('sha256', 'sha512', 'blake2... | import pytest
import os
from solution import generate_file_hash, verify_file_integrity
def create_test_file(file_path, content):
with open(file_path, 'w') as file:
file.write(content)
def test_generate_file_hash_sha256():
# Setup
file_path = 'test_file.txt'
content = "Hello, world!"
create... | [
{
"docstring": "Generate the hash of a file's contents using the specified algorithm.\n\nArgs:\n- file_path (str): The path to the file to hash.\n- algorithm (str): The hashing algorithm to use ('sha256', 'sha512', 'blake2b').\n\nReturns:\n- str: The hexadecimal representation of the file's hash.",
"functio... | [
0,
0,
1,
1,
1,
1,
1,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\n\ndef generate_file_hash(file_path: str, algorithm: str = 'sha256') -> str:\n \"\"\"\n Generate the hash for a given file using the specified algo... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00029564",
"row_id": 29564,
"seed_ids": "[225]"
} | 0.728546 | Docs: Python310_29564 | I | [
"generate_file_hash",
"verify_file_integrity"
] | 2 | [
[
"verify_file_integrity",
"generate_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a69b8efcfce85bc213f548f242f8fa3f8a90283a | b427deda92ed829b26ac3b796bc799e97d83e3ff | |||
v1.0 | instruct | Docs | Docs: Pytorch_29644_I | ### PyTorch Parallel Processing Assessment
#### Objective:
Implement a function using PyTorch that demonstrates the use of both synchronous and asynchronous operations, leveraging inter-op and intra-op parallelism. You will need to configure the number of threads and measure the performance impact of different setting... | import torch
import timeit
# Synchronous matrix multiplication
def synchronous_mm(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""
Perform synchronous matrix multiplication.
Args:
x: torch.Tensor - First matrix.
y: torch.Tensor - Second matrix.
Returns:
torch.Tensor - The re... | import torch
from solution import synchronous_mm, asynchronous_mm
def test_synchronous_mm():
x = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
y = torch.tensor([[5.0, 6.0], [7.0, 8.0]])
expected = torch.tensor([[19.0, 22.0], [43.0, 50.0]])
result = synchronous_mm(x, y)
assert torch.allclose(result, expect... | [
{
"docstring": "Perform synchronous matrix multiplication.\n\nArgs:\nx: torch.Tensor - First matrix.\ny: torch.Tensor - Second matrix.\n\nReturns:\ntorch.Tensor - The result of matrix multiplication.",
"function_declaration": "def synchronous_mm(x, y):",
"function_name": "synchronous_mm",
"parameter... | [
1,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport timeit\n\n# Synchronous matrix multiplication\ndef synchronous_mm(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Perform synch... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00029644",
"row_id": 29644,
"seed_ids": "[169]"
} | 0.496159 | Docs: Pytorch_29644 | I | [
"synchronous_mm",
"compute_mm",
"asynchronous_mm",
"experiment"
] | 4 | [
[
"asynchronous_mm",
"compute_mm"
],
[
"experiment",
"asynchronous_mm"
],
[
"experiment",
"synchronous_mm"
]
] | 3 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 824c46e3f88db4d715e0c26325a4f690b50ba2ae | e6b62fb9d10a374d75e08752b055ebc08851cb59 | |||
v1.0 | instruct | Docs | Docs: Python310_29699_I | **Title: Implementing a Timeout for a Long-Running Function with Signal Handling**
**Objective:**
Implement a function that limits the execution time of another function using the `signal` module. If the execution exceeds the specified time, an exception should be raised. This requires understanding signal handlers, ... | import signal
class TimeoutError(Exception):
pass
def _handle_timeout(signum, frame):
raise TimeoutError("Function execution exceeded the timeout")
def run_with_timeout(func, args, timeout):
"""
Executes a function with a given timeout.
Parameters:
func (callable): The function to execut... | import pytest
import time
from solution import run_with_timeout, TimeoutError
def long_running_function(x, y):
time.sleep(x)
return x + y
def quick_function(x, y):
return x + y
def test_run_with_timeout_success():
assert run_with_timeout(quick_function, (2, 3), 5) == 5
def test_run_with_timeout_exce... | [] | [
0,
0,
0,
1,
0,
1,
1,
1,
0
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\n\ndef _timeout_handler(signum, frame):\n raise TimeoutError(\"Function execution exceeded the timeout\")\n\ndef run_with_timeout(func, args, timeout):... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00029699",
"row_id": 29699,
"seed_ids": "[253]"
} | 0.601931 | Docs: Python310_29699 | I | [
"_handle_timeout",
"run_with_timeout"
] | 2 | [
[
"run_with_timeout",
"_handle_timeout"
]
] | 1 | [] | false | [
"TimeoutError"
] | true | pytest | true | [] | true | 146693125aa03e6056e868065830312e29b0251b | f43e177bab903de9d116b3804379851b3d4bb54c | |||
v1.0 | instruct | Docs | Docs: Python310_29704_I | <|Analysis Begin|>
The provided documentation explains the functionality of the `telnetlib` module, which is used to implement a Telnet client in Python. It discusses the `Telnet` class, its initialization, and the methods available for performing various Telnet operations. Key methods include:
- `read_until()`: Reads... | import telnetlib
import time
def connect_to_server(host: str, port: int, timeout: int) -> telnetlib.Telnet:
tn = telnetlib.Telnet()
tn.open(host, port, timeout)
return tn
def login(tn: telnetlib.Telnet, username: str, password: str) -> bool:
try:
tn.read_until(b"login: ")
tn.write(user... | from unittest.mock import Mock, patch
from solution import connect_to_server, login, execute_commands, set_debug_level, fault_tolerant_connection
@patch('telnetlib.Telnet.open')
def test_connect_to_server(mock_open):
tn = connect_to_server('localhost', 23, 10)
mock_open.assert_called_with('localhost', 23, 10)
... | [
{
"docstring": null,
"function_declaration": "def connect_to_server(host, port, timeout):",
"function_name": "connect_to_server",
"parameter_list": "(host, port, timeout)"
},
{
"docstring": null,
"function_declaration": "def login(tn, username, password):",
"function_name": "login",
... | [
0,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import telnetlib\nimport time\n\ndef connect_to_server(host: str, port: int, timeout: int) -> telnetlib.Telnet:\n tn = telnetlib.Telnet()\n tn.open(host, port, ti... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00029704",
"row_id": 29704,
"seed_ids": "[217]"
} | 0.489543 | Docs: Python310_29704 | I | [
"connect_to_server",
"login",
"execute_commands",
"set_debug_level",
"fault_tolerant_connection"
] | 5 | [
[
"fault_tolerant_connection",
"connect_to_server"
],
[
"fault_tolerant_connection",
"execute_commands"
],
[
"fault_tolerant_connection",
"login"
],
[
"fault_tolerant_connection",
"set_debug_level"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | b2cf21cb64900a83748771bf4455b415cc2a9392 | cf5ad1d3ed9555de1e358ace24f1e4945053b740 | |||
v1.0 | instruct | Docs | Docs: Scikit_29728_I | #### SVM Classification and Custom Kernels
You are tasked with utilizing scikit-learn's Support Vector Machine (SVM) functionality to:
1. Perform binary classification on a given dataset.
2. Implement and use a custom kernel for the SVM classifier.
**Requirements:**
1. **Binary Classification:**
- Load a provided... | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import accuracy_score, precision_score, recall_score
import numpy as np
# Load data
def load_data(file_path):
data = pd.read_csv(file_path)
X = data.iloc[:, :-1].values
y = data.iloc[:, -1]... | from solution import svm_classification
# Mocking the function for test purposes
import pandas as pd
from sklearn.datasets import make_classification
# Create a mock dataset function
def create_mock_dataset():
X, y = make_classification(n_samples=100, n_features=20, n_classes=2, random_state=42)
mock_data = p... | [
{
"docstring": null,
"function_declaration": "def load_data(file_path):",
"function_name": "load_data",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def custom_poly_kernel(X, Y):",
"function_name": "custom_poly_kernel",
"parameter_list": "(X, Y... | [
0,
0,
0,
0,
0,
1,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\nfrom sklearn.metrics import accuracy_score, precision_score, recall_... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00029728",
"row_id": 29728,
"seed_ids": "[31]"
} | 0.598829 | Docs: Scikit_29728 | I | [
"load_data",
"custom_poly_kernel",
"svm_classification"
] | 3 | [
[
"svm_classification",
"load_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | f953655994047ec37aab25a6ab5ac13279186c55 | 327efde72cb84f284ad0ef2a74e5c2ba7079267c | |||
v1.0 | instruct | Docs | Docs: Python310_29795_I | ### Question: Implement a Directory Overview Tool using Python `stat` Module
You are tasked with implementing a Python script that provides an overview of all files and directories within a specified directory. The overview should include file types, permissions, and other relevant attributes.
#### Function Specifica... | import os
import stat
import time
def file_type(mode):
if stat.S_ISDIR(mode):
return "Directory"
elif stat.S_ISREG(mode):
return "Regular File"
elif stat.S_ISLNK(mode):
return "Symbolic Link"
elif stat.S_ISCHR(mode):
return "Character Device"
elif stat.S_ISBLK(mode):... | from solution import directory_overview
import os
import pytest
def setup_test_directory():
if not os.path.exists('test_dir'):
os.mkdir('test_dir')
with open('test_dir/file1.txt', 'w') as f:
f.write('hello world')
with open('test_dir/file2.txt', 'w') as f:
f.write('p... | [
{
"docstring": null,
"function_declaration": "def file_type(mode):",
"function_name": "file_type",
"parameter_list": "(mode)"
},
{
"docstring": null,
"function_declaration": "def permissions_string(mode):",
"function_name": "permissions_string",
"parameter_list": "(mode)"
},
... | [
1,
1,
0,
1,
1,
1,
1,
1,
0
] | 7 | easy | 0.778 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport stat\nimport time\n\ndef get_file_type(mode):\n if stat.S_ISDIR(mode):\n return \"Directory\"\n elif stat.S_ISREG(mode):\n return ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00029795",
"row_id": 29795,
"seed_ids": "[373]"
} | 0.624393 | Docs: Python310_29795 | I | [
"file_type",
"permissions_string",
"directory_overview"
] | 3 | [
[
"directory_overview",
"file_type"
],
[
"directory_overview",
"permissions_string"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4d0574246081976288e373c6c43be0fe4e365fca | 8d8dbdc544c14b6191f4d5bd6821299e159678ce | |||
v1.0 | instruct | Docs | Docs: Python310_29839_I | ### **Netrc File Manipulation and Security Assessment**
You are tasked with creating a Python script to read, manipulate, and enhance the security of a `.netrc` file using the `netrc` class. Your implementation should include the following functionalities:
1. **Initialization and Reading**:
- Write a function `rea... | import os
import stat
from netrc import netrc, NetrcParseError
class SecurityRiskAlert(Exception):
pass
def read_netrc(file=None):
"""
Initializes a netrc object from the given file. If no file is provided,
defaults to .netrc in the user's home directory.
"""
if file is None:
file = os... | from solution import read_netrc, get_authenticator, assess_security, netrc_to_string, SecurityRiskAlert
import os
import stat
import pytest
from tempfile import NamedTemporaryFile
def test_read_netrc():
with NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(b"machine example.com login user1 pa... | [] | [
0,
0,
0,
0,
1,
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 os\nfrom netrc import netrc, NetrcParseError\n\ndef read_netrc(file=None):\n \"\"\"\n Initializes a netrc object. If a file path is provided, it uses that ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00029839",
"row_id": 29839,
"seed_ids": "[383]"
} | 0.364319 | Docs: Python310_29839 | I | [
"read_netrc",
"get_authenticator",
"assess_security",
"netrc_to_string"
] | 4 | [
[
"get_authenticator",
"read_netrc"
],
[
"netrc_to_string",
"read_netrc"
]
] | 2 | [] | false | [
"SecurityRiskAlert"
] | true | pytest | true | [] | true | 39022d7cb4d643e69a5d226cab8dd692099b1f4e | 6044993b49654cfb8eabe64855ab5176a9f2f3ef | |||
v1.0 | instruct | Docs | Docs: Python310_29857_I | ### Password Authentication System with Crypt Module
You are required to implement a password authentication system using the legacy `crypt` module in Python. This system should:
1. Register new users by storing their username and hashed password.
2. Authenticate existing users by comparing provided passwords with sto... | import crypt
import hmac
from typing import Dict
# In-memory storage for user data, simulate the database.
user_db: Dict[str, str] = {}
def register_user(username: str, password: str) -> None:
"""
Registers a new user by hashing the provided password and storing the username with the hashed password.
"""
... | import pytest
from solution import register_user, authenticate_user, change_password
def setup_module(module):
"""
Setup method for the test module.
"""
global user_db
user_db = {}
def test_register_and_authenticate_user():
register_user('alice', 'wonderland123')
assert authenticate_user('... | [
{
"docstring": "Registers a new user by hashing the provided password and storing the username with the hashed password.",
"function_declaration": "def register_user(username, password):",
"function_name": "register_user",
"parameter_list": "(username, password)"
},
{
"docstring": "Authentic... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import crypt\nimport hmac\n\n# In-memory user storage\nuser_store = {}\n\ndef get_strongest_available_hash():\n \"\"\"\n Returns the strongest available hash meth... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00029857",
"row_id": 29857,
"seed_ids": "[185]"
} | 0.613382 | Docs: Python310_29857 | I | [
"register_user",
"authenticate_user",
"change_password"
] | 3 | [
[
"change_password",
"authenticate_user"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 32d439856a427df423a152e9759596574c116909 | feff83769defaed4cc8325fc8b17ca1f78c6a7e7 | |||
v1.0 | instruct | Docs | Docs: Python310_29871_I | **Problem Statement: Concurrent Web Scraping with Retry Logic**
You are tasked with implementing a Python function using asyncio to perform concurrent web scraping. Your function will take a list of URLs to scrape concurrently and retry fetching each URL up to a specified number of times in case of a failure. The func... | import asyncio
async def fetch_data(url):
# Simulated fetch logic, replace with actual network request
await asyncio.sleep(1) # Simulate network delay
if url == "http://example.com/bad":
raise Exception(f"Failed to fetch data from {url}")
return f"Data from {url}"
async def fetch_with_retries... | import asyncio
from solution import fetch_urls
async def test_fetch_urls():
urls_to_fetch = [
"http://example.com/good1",
"http://example.com/good2",
"http://example.com/bad"
]
result = await fetch_urls(urls_to_fetch, 3)
assert result == {
"http://example.com/good1": "Da... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def fetch_data(url):\n # This is a simulated fetch function\n await asyncio.sleep(1)\n if \"bad\" in url:\n raise Exception(f\"F... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00029871",
"row_id": 29871,
"seed_ids": "[317]"
} | 0.591897 | Docs: Python310_29871 | I | [
"fetch_data",
"fetch_with_retries",
"fetch_urls"
] | 3 | [
[
"fetch_urls",
"fetch_with_retries"
],
[
"fetch_with_retries",
"fetch_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a6b0b88ff0b5a8f4239e2b201e54795fdb91a244 | 919ee6b13545c9df1ac2b30c72a835808ec5f141 | |||
v1.0 | instruct | Docs | Docs: Pandas_29916_I | **Pandas String Operations and Data Cleaning**
**Objective:**
To assess your understanding of pandas string handling and manipulation techniques by performing a series of transformations on a dataset.
**Background:**
You are provided with a DataFrame containing data about various products sold by a retailer. The data... | import pandas as pd
import numpy as np
import re
def clean_product_id(df):
df['Product ID'] = df['Product ID'].str.strip().str.upper()
df['Product ID'] = df['Product ID'].str.replace(r'[^A-Z0-9]', '', regex=True)
return df
def clean_product_name(df):
df['Product Name'] = df['Product Name'].str.strip()... | import pandas as pd
from solution import clean_product_id, clean_product_name, clean_product_description, clean_price, apply_cleaning_functions
def test_clean_product_id():
data = {'Product ID': [' P1 ', ' P2 ', ' P3', ' p4 ', ' P-5']}
df = pd.DataFrame(data)
expected = ['P1', 'P2', 'P3', 'P4', 'P5']
... | [
{
"docstring": null,
"function_declaration": "def clean_product_id(df):",
"function_name": "clean_product_id",
"parameter_list": "(df)"
},
{
"docstring": null,
"function_declaration": "def clean_product_name(df):",
"function_name": "clean_product_name",
"parameter_list": "(df)"
... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport numpy as np\n\ndef clean_product_id(df):\n \"\"\"\n Cleans the 'Product ID' column in the given DataFrame.\n Strip leading/trailing... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00029916",
"row_id": 29916,
"seed_ids": "[20]"
} | 0.758608 | Docs: Pandas_29916 | I | [
"clean_product_id",
"clean_product_name",
"clean_product_description",
"clean_price",
"apply_cleaning_functions"
] | 5 | [
[
"apply_cleaning_functions",
"clean_price"
],
[
"apply_cleaning_functions",
"clean_product_description"
],
[
"apply_cleaning_functions",
"clean_product_id"
],
[
"apply_cleaning_functions",
"clean_product_name"
]
] | 4 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas"
] | false | ddc8b6cc2294f67fbb4e1068b8660425aa1ab610 | 824e7d83eff7c12963fb80e4b0dba21cd3053923 | |||
v1.0 | instruct | Docs | Docs: Python310_29958_I | ### CGI Script for Processing Form Data
**Description:**
You are required to write a CGI (Common Gateway Interface) script using the deprecated `cgi` module in Python. This script should be capable of handling a simple HTML form submission. The form will contain fields for a user's first name, last name, and email add... | #!/usr/bin/python3
import cgi
import cgitb
cgitb.enable() # Enables CGI tracebacks for debugging
def html_response(message):
print("Content-type: text/html\n")
print("<html><head>")
print("<title>CGI Form Response</title>")
print("</head><body>")
print(f"<h2>{message}</h2>")
print("</body></h... | def test_html_response(capsys):
html_response("Test message")
captured = capsys.readouterr()
assert "Content-type: text/html\n" in captured.out
assert "<h2>Test message</h2>" in captured.out
def test_process_form_valid_post(monkeypatch, capsys):
def mock_fieldstorage():
class MockFieldStora... | [
{
"docstring": null,
"function_declaration": "def html_response(message):",
"function_name": "html_response",
"parameter_list": "(message)"
},
{
"docstring": null,
"function_declaration": "def process_form():",
"function_name": "process_form",
"parameter_list": "()"
}
] | [
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": "#!/usr/bin/python3\n\nimport cgi\nimport cgitb\ncgitb.enable() # Enable CGI traceback for debugging\n\ndef html_response(message):\n \"\"\"\n Generates a simple ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00029958",
"row_id": 29958,
"seed_ids": "[193]"
} | 0.599199 | Docs: Python310_29958 | I | [
"html_response",
"process_form"
] | 2 | [
[
"process_form",
"html_response"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | a0f479393e13e472811a7f3aa3f8838600c7f251 | d5af2a13730963ab547f3e79f3ad34c168ceefe5 | |||
v1.0 | instruct | Docs | Docs: Python310_29991_I | Efficient Prime Number Generation using Multiprocessing
In this task, you are required to generate a list of prime numbers up to a given integer `n` efficiently by utilizing the `multiprocessing` module. This will test your ability to implement process-based parallel programming and apply different multiprocessing str... | import multiprocessing
def is_prime(num):
"""
Checks if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
re... | import multiprocessing
from solution import is_prime, generate_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(29) == True
assert is_prime(30) == False
assert is_prime(1) == False
as... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Generates prime numbers up to n using num_processes processes.",
"function_declaration": "def generate_primes(n, num_proc... | [
1,
0,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from multiprocessing import Pool\n\ndef is_prime(num):\n \"\"\"\n Returns True if num is a prime number else False.\n \"\"\"\n if num <= 1:\n return ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00029991",
"row_id": 29991,
"seed_ids": "[338]"
} | 0.554366 | Docs: Python310_29991 | I | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c7ec016fa4c2062c0cd8da3249188366a8ee9b2e | 56974df1b63fd53d3bcedc047142e3b89ae3f450 | |||
v1.0 | instruct | Docs | Docs: Python310_29995_I | ### Warning Control and Testing in Python
**Objective**:
To assess your understanding of the `warnings` module in Python, particularly how to handle, filter, and test runtime warnings.
**Problem Statement**:
You are developing a Python package, and you want to ensure that your package is robust and correctly handles... | import warnings
from contextlib import contextmanager
def trigger_warning(warning_type: str, message: str) -> None:
"""
Triggers a warning of the specified type with a custom message.
:param warning_type: Type of warning to trigger.
:param message: Custom warning message.
"""
warning_types... | import pytest
from solution import trigger_warning, configure_warning_filter, suppress_warnings, test_warning_capture
def test_trigger_warning_user():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
trigger_warning("user", "This is a user warning")
assert len... | [
{
"docstring": "Triggers a warning of the specified type with a custom message.\n\n:param warning_type: Type of warning to trigger.\n:param message: Custom warning message.",
"function_declaration": "def trigger_warning(warning_type, message):",
"function_name": "trigger_warning",
"parameter_list": ... | [
0,
1,
0,
0,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import warnings\n\ndef trigger_warning(warning_type: str, message: str) -> None:\n \"\"\"\n Triggers a warning of the specified type with the provided message.\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00029995",
"row_id": 29995,
"seed_ids": "[125]"
} | 0.490903 | Docs: Python310_29995 | I | [
"trigger_warning",
"configure_warning_filter",
"suppress_warnings",
"test_warning_capture"
] | 4 | [
[
"test_warning_capture",
"trigger_warning"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0d41f2168100e9433549967aa970f903e903d57c | 92b53b912e47695ebde43516c358af1c8f51e371 | |||
v1.0 | instruct | Docs | Docs: Python310_30026_I | #### Objective:
Design and implement an asynchronous Python program that performs both network I/O operations and CPU-bound computations. The program should utilize the asyncio library effectively, ensuring proper error handling, logging, and debugging.
#### Description:
1. Implement an asynchronous function called `... | import asyncio
import logging
import random
from concurrent.futures import ThreadPoolExecutor
async def fetch_data():
await asyncio.sleep(random.randint(1, 5))
return random.randint(1, 100)
def compute_factorial(n):
if n == 1:
return 1
else:
return n * compute_factorial(n - 1)
async d... | import asyncio
import logging
from solution import fetch_data, compute_factorial, process_tasks
def test_fetch_data():
loop = asyncio.get_event_loop()
result = loop.run_until_complete(fetch_data())
assert 1 <= result <= 100
def test_compute_factorial():
assert compute_factorial(1) == 1
assert comp... | [
{
"docstring": null,
"function_declaration": "def compute_factorial(n):",
"function_name": "compute_factorial",
"parameter_list": "(n)"
}
] | [
1,
1,
1,
1,
1,
0,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport logging\nimport random\nfrom concurrent.futures import ThreadPoolExecutor\n\nasync def fetch_data():\n await asyncio.sleep(random.randint(1, 5... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00030026",
"row_id": 30026,
"seed_ids": "[200]"
} | 0.583022 | Docs: Python310_30026 | I | [
"fetch_data",
"compute_factorial",
"process_tasks"
] | 3 | [
[
"process_tasks",
"compute_factorial"
],
[
"process_tasks",
"fetch_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c53c145e2426588774ebb8048cfed808758923af | d74ed27020c1183f67951c83693ad08a2815ecf8 | |||
v1.0 | instruct | Docs | Docs: Python310_30033_I | ### Advanced Asyncio Queue Operations
**Objective:**
Implement a solution that demonstrates advanced usage of `asyncio.Queue` and its variants (`PriorityQueue`, `LifoQueue`). Your task is to simulate a job processing system where jobs have varying priorities and specific handling time. The system should efficiently m... | import asyncio
from typing import List, Tuple
async def worker(name: str, queue: asyncio.PriorityQueue):
while True:
priority, processing_time = await queue.get()
print(f"{name} started job with priority {priority} for {processing_time} seconds")
await asyncio.sleep(processing_time)
... | import asyncio
import pytest
from solution import process_jobs
def job_processing_test():
jobs = [(1, 1.0), (2, 2.0), (1, 3.0), (3, 4.0)]
n = 2
async def run_test():
await process_jobs(jobs, n)
asyncio.run(run_test())
def test_jobs_processed_correctly():
jobs = [(1, 0.1), (2, 0.2), (1, 0... | [] | [
0,
1,
0,
1,
1,
0,
0,
0,
1
] | 4 | medium | 0.444 | {
"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(worker_id: int, queue: asyncio.PriorityQueue):\n while True:\n job = await queue.get()\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00030033",
"row_id": 30033,
"seed_ids": "[111]"
} | 0.593556 | Docs: Python310_30033 | I | [
"worker",
"process_jobs"
] | 2 | [
[
"process_jobs",
"worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0651add6798912612f077d2c41673c7e2c369d15 | 8b23a5b31e755b2afa56bb5c8266813c5823ac1d | |||
v1.0 | instruct | Docs | Docs: Pytorch_30044_I | ### PyTorch Distributed Metrics Handler
#### Objective
In this assessment, your goal is to demonstrate your understanding of metrics handling in a distributed training setup with PyTorch, using the `torchelastic` framework. You will implement a function to configure and use multiple metric handlers during a training ... | import datetime
def put_metric(name, value, handler):
"""
Mock function to put the metric using the handler
"""
handler(name, value)
def ConsoleMetricHandler(name, value):
"""
Mock ConsoleMetricHandler function
"""
print(f"[{datetime.datetime.now()}] {name}: {value}")
def NullMetr... | import io
import sys
from solution import train_with_metrics
def test_train_with_metrics():
captured_output = io.StringIO()
sys.stdout = captured_output
train_with_metrics(5)
sys.stdout = sys.__stdout__
output = captured_output.getvalue()
expected_output_lines = [
f"training_l... | [
{
"docstring": "Mock function to put the metric using the handler",
"function_declaration": "def put_metric(name, value, handler):",
"function_name": "put_metric",
"parameter_list": "(name, value, handler)"
},
{
"docstring": "Mock ConsoleMetricHandler function",
"function_declaration": "... | [
0,
1,
0,
1,
0,
0,
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 torch\nfrom torchelastic.metrics import ConsoleMetricHandler, NullMetricHandler, put_metric\n\ndef train_with_metrics(epochs: int) -> None:\n \"\"\"\n Conf... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00030044",
"row_id": 30044,
"seed_ids": "[151]"
} | 0.528187 | Docs: Pytorch_30044 | I | [
"put_metric",
"ConsoleMetricHandler",
"NullMetricHandler",
"train_with_metrics"
] | 4 | [
[
"train_with_metrics",
"put_metric"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 085a82e832ba343deaf95cfa25f45c187f44e516 | 4537a48849a58844f2b3ada3e763c7a93a1ebd5b | |||
v1.0 | instruct | Docs | Docs: Pytorch_30081_I | #### Objective:
Demonstrate your understanding of `torch.futures.Future` for handling asynchronous operations in PyTorch by creating and managing multiple `Future` objects.
#### Task:
Write a Python function `asynchronous_computation` that accepts a list of numbers. For each number, it should create an asynchronous ta... | import torch
from torch.futures import Future, collect_all, wait_all
import time
import asyncio
def async_square(num):
"""
Asynchronous function to compute the square of a number after 1 second.
"""
async def compute_square():
await asyncio.sleep(1) # Simulating a 1-second delay
return... | from solution import asynchronous_computation
def test_asynchronous_computation():
nums = [1, 2, 3, 4, 5]
expected = [1, 4, 9, 16, 25]
assert asynchronous_computation(nums) == expected
def test_asynchronous_computation_empty():
nums = []
expected = []
assert asynchronous_computation(nums) == e... | [
{
"docstring": "Asynchronous function to compute the square of a number after 1 second.",
"function_declaration": "def async_square(num):",
"function_name": "async_square",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def asynchronous_computation(nums):",
... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.futures import Future, collect_all, wait_all\nimport time\n\ndef asynchronous_computation(nums):\n futures = []\n\n # Function to simulat... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00030081",
"row_id": 30081,
"seed_ids": "[53]"
} | 0.519935 | Docs: Pytorch_30081 | I | [
"async_square",
"asynchronous_computation"
] | 2 | [
[
"asynchronous_computation",
"async_square"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | b22ff4cc0a87a740a4583961e9e4806540e49418 | 3f314e4bcd09cb7055e262684eeb2ffcc1c879dd | |||
v1.0 | instruct | Docs | Docs: Python310_30203_I | #### Objective
Implement a server that can handle multiple client connections using the `select` module in Python 3.10. The server must be able to read messages from clients and broadcast these messages to all connected clients (except the sender). This will test the student's ability to manage multiple I/O streams and... | import socket
import select
def setup_server(port):
"""
Create and set up the server socket to listen for incoming connections.
"""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('0.0.0.0'... | import socket
import threading
def test_server_startup():
"""
Test the server startup.
"""
server_thread = threading.Thread(target=run_server, args=(12345,), daemon=True)
server_thread.start()
test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
test_socket.connect(... | [
{
"docstring": "Create and set up the server socket to listen for incoming connections.",
"function_declaration": "def setup_server(port):",
"function_name": "setup_server",
"parameter_list": "(port)"
},
{
"docstring": "Accept new client connection and add it to the list of input sockets.",
... | [
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 socket\nimport select\n\ndef setup_server(port):\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_socket.setsockopt(socket.SOL_... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00030203",
"row_id": 30203,
"seed_ids": "[172]"
} | 0.646486 | Docs: Python310_30203 | I | [
"setup_server",
"accept_connections",
"broadcast_message",
"run_server"
] | 4 | [
[
"run_server",
"accept_connections"
],
[
"run_server",
"broadcast_message"
],
[
"run_server",
"setup_server"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 4907c2a693aca564db807bc7dcb19612e2d6562f | d0d76b799bcdddd42dde93bf36f513721b418aef | |||
v1.0 | instruct | Docs | Docs: Python310_30210_I | Using asyncio for Multithreading and Debugging
#### Objective
You are asked to demonstrate your understanding of the asyncio library in Python, particularly focusing on multithreading, handling blocking code, and debugging. You will implement a function that performs a blocking operation in a separate thread, schedule... | import asyncio
import concurrent.futures
import logging
def cpu_bound_task():
import time
time.sleep(2)
return "CPU-bound task complete"
async def async_callback():
print("Asynchronous callback executed")
async def perform_async_operations():
loop = asyncio.get_running_loop()
loop.set_debug(T... | import pytest
import asyncio
from solution import cpu_bound_task, async_callback, perform_async_operations
def test_cpu_bound_task():
assert cpu_bound_task() == "CPU-bound task complete"
@pytest.mark.asyncio
async def test_async_callback(capfd):
await async_callback()
captured = capfd.readouterr()
ass... | [
{
"docstring": null,
"function_declaration": "def cpu_bound_task():",
"function_name": "cpu_bound_task",
"parameter_list": "()"
}
] | [
0,
1,
0,
1,
1,
1,
0,
1,
1
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport concurrent.futures\nimport logging\nimport time\n\ndef cpu_bound_task():\n \"\"\"\n Simulates a heavy computation by sleeping for 2 seconds... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00030210",
"row_id": 30210,
"seed_ids": "[200]"
} | 0.524244 | Docs: Python310_30210 | I | [
"cpu_bound_task",
"async_callback",
"perform_async_operations"
] | 3 | [
[
"perform_async_operations",
"async_callback"
],
[
"perform_async_operations",
"cpu_bound_task"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a6e0f3f0b9e1d00ccc5dd19a46f7912e3ec4f9be | 6a46e2bf25929c09b61a1caa02c1a3f5e319ee99 | |||
v1.0 | instruct | Docs | Docs: Python310_30260_I | **Title: Asynchronous Task Execution with Synchronization Primitives**
**Objective:**
Write a Python program using the `asyncio` library that demonstrates the management and synchronization of multiple asynchronous tasks. You will implement a function that processes a list of URLs, fetching data from them concurrently... | import asyncio
import random
from typing import List
async def fetch_url(url: str) -> str:
await asyncio.sleep(random.randint(1, 3))
return f"Data retrieved from {url}"
async def process_urls(urls: List[str]) -> List[str]:
semaphore = asyncio.Semaphore(3)
async def sem_fetch(url):
async w... | import pytest
import asyncio
import random
from solution import fetch_url, process_urls
# Patching random.randint to control the sleep time for predictability in tests
@pytest.fixture(autouse=True)
def patch_random_sleep(monkeypatch):
def mock_randint(start, end):
return 1 # Always sleep for 1 second in t... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\nfrom typing import List\n\nasync def fetch_url(url: str) -> str:\n \"\"\"\n Simulates fetching data from a URL by sleeping for a ra... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00030260",
"row_id": 30260,
"seed_ids": "[270]"
} | 0.552481 | Docs: Python310_30260 | I | [
"fetch_url",
"process_urls",
"main"
] | 3 | [
[
"process_urls",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 43ed3959a720503cd0d03a90168527dbd3a46494 | aaafc6964699e0f4b173cbe9c861cc95625adfbc | |||
v1.0 | instruct | Docs | Docs: Seaborn_30301_I | #### Objective
Your task is to demonstrate your understanding of Seaborn's `husl_palette` function by creating various color palettes, modifying their parameters, and applying them to different visualizations.
#### Question
1. **Generate Color Palettes**:
- a. Create a default HUSL palette with 6 colors and print ... | import seaborn as sns
import matplotlib.pyplot as plt
def generate_and_print_palettes():
# a. Create a default HUSL palette with 6 colors and print it
palette_default = sns.husl_palette()
print("Default HUSL palette (6 colors):", palette_default)
# b. Create a HUSL palette with 8 colors and print it
... | from solution import generate_and_print_palettes
def test_generate_and_print_palettes():
palette_default, palette_8, palette_custom, colormap_continuous = generate_and_print_palettes()
assert len(palette_default) == 6 # Default HUSL palette should have 6 colors
assert len(palette_8) == 8 # HUSL palette ... | [
{
"docstring": null,
"function_declaration": "def generate_and_print_palettes():",
"function_name": "generate_and_print_palettes",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def visualize_palettes():",
"function_name": "visualize_palettes",
"parameter... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef generate_palettes_and_visualizations():\n # Part 1: Generate Color Palettes\n # a.\n palette_defa... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00030301",
"row_id": 30301,
"seed_ids": "[59]"
} | 0.670115 | Docs: Seaborn_30301 | I | [
"generate_and_print_palettes",
"visualize_palettes"
] | 2 | [
[
"visualize_palettes",
"generate_and_print_palettes"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"seaborn"
] | false | 9475eb550f27b0ce95cdc4e5f05f4a19e15194e0 | 0dece89c88a9c1d11863098f197b60622f8b8560 | |||
v1.0 | instruct | Docs | Docs: Python310_30350_I | **Objective:**
Write a Python program using the `contextvars` module to manage and manipulate context-specific variables.
**Problem Statement:**
You are required to implement a set of functions to demonstrate your understanding of `contextvars` module in Python. Specifically, you should:
1. Create a new context an... | import contextvars
# Function to create and return a new context
def create_context():
"""
Creates and returns a new context.
"""
return contextvars.copy_context()
# Function to create a context variable with a default value
def create_context_var(name, default_value=None):
"""
Creates and ret... | import pytest
from solution import create_context, create_context_var, set_context_var, get_context_var, context_simulation
def test_create_context():
ctx = create_context()
assert isinstance(ctx, contextvars.Context)
def test_create_context_var():
ctx_var = create_context_var('test_var', 'default_value')... | [
{
"docstring": "Creates and returns a new context.",
"function_declaration": "def create_context():",
"function_name": "create_context",
"parameter_list": "()"
},
{
"docstring": "Creates and returns a new context variable with the given name and default value.",
"function_declaration": "... | [
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 contextvars\n\ndef create_context() -> contextvars.Context:\n \"\"\"\n Create a new context and return it.\n \"\"\"\n return contextvars.Context()\n\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00030350",
"row_id": 30350,
"seed_ids": "[60]"
} | 0.41191 | Docs: Python310_30350 | I | [
"create_context",
"create_context_var",
"set_context_var",
"get_context_var",
"context_simulation"
] | 5 | [
[
"context_simulation",
"create_context"
],
[
"context_simulation",
"create_context_var"
],
[
"context_simulation",
"get_context_var"
],
[
"context_simulation",
"set_context_var"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 11479a29733c1f8139bd0e869301c4f07c57cb10 | 475a628e2106956f9dd5d5cf225c3f1e08a93f16 | |||
v1.0 | instruct | Docs | Docs: Python310_30359_I | **Problem Statement:**
You are tasked with creating a secure data verification system using the `hmac` module. This system should be able to generate HMAC digests for given messages and verify the authenticity of messages using a shared secret key.
**Function 1: generate_hmac**
Implement a function `generate_hmac(k... | import hmac
import hashlib
def generate_hmac(key: bytes, msg: bytes, digestmod: str) -> str:
"""
Generate an HMAC digest for the provided message and key using the specified digest mode.
:param key: Secret key as bytes object.
:param msg: Message to be authenticated as bytes object.
:param dig... | import pytest
from solution import generate_hmac, verify_hmac
def test_generate_hmac_sha256():
key = b'secret_key'
msg = b'This is a secret message'
digestmod = 'sha256'
expected_hmac_hex = hmac.new(key, msg, digestmod).hexdigest()
assert generate_hmac(key, msg, digestmod) == expected_hmac_hex... | [
{
"docstring": "Generate an HMAC digest for the provided message and key using the specified digest mode.\n\n:param key: Secret key as bytes object.\n:param msg: Message to be authenticated as bytes object.\n:param digestmod: Digest mode to use (e.g., 'sha256').\n:return: Hexadecimal HMAC digest as a string.",
... | [
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 hmac\nimport hashlib\n\ndef generate_hmac(key: bytes, msg: bytes, digestmod: str) -> str:\n \"\"\"\n Generate an HMAC digest for the provided message and k... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00030359",
"row_id": 30359,
"seed_ids": "[298]"
} | 0.72082 | Docs: Python310_30359 | I | [
"generate_hmac",
"verify_hmac"
] | 2 | [
[
"verify_hmac",
"generate_hmac"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a1a3e429b6119375616d282201cc46bee17c5393 | 29ae76a6917f55e03c4f9a8dcc3d1d408bfa6ebe | |||
v1.0 | instruct | Docs | Docs: Python310_30362_I | ### Question: Concurrent Number Processing
Given a list of integers, design a Python program to perform the following operations concurrently using the `concurrent.futures` module. Your task is to implement a function `process_numbers(numbers: List[int]) -> Dict[str, int]` that performs these steps:
1. **Sum of Squar... | from concurrent.futures import ThreadPoolExecutor
from typing import List, Dict
def sum_of_squares(numbers: List[int]) -> int:
return sum(x ** 2 for x in numbers)
def sum_of_cubes(numbers: List[int]) -> int:
return sum(x ** 3 for x in numbers)
def max_number(numbers: List[int]) -> int:
return max(numbers... | from solution import process_numbers
def test_process_numbers_basic():
numbers = [1, 2, 3, 4, 5]
result = process_numbers(numbers)
assert result == {
'sum_of_squares': 1**2 + 2**2 + 3**2 + 4**2 + 5**2,
'sum_of_cubes': 1**3 + 2**3 + 3**3 + 4**3 + 5**3,
'max_number': 5,
'min_n... | [
{
"docstring": null,
"function_declaration": "def sum_of_squares(numbers):",
"function_name": "sum_of_squares",
"parameter_list": "(numbers)"
},
{
"docstring": null,
"function_declaration": "def sum_of_cubes(numbers):",
"function_name": "sum_of_cubes",
"parameter_list": "(numbers... | [
1,
1,
0,
1,
0,
1,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\nfrom typing import List, Dict\n\ndef compute_sum_of_squares(numbers):\n return sum(x**2 for x in numbers)\n\ndef compute_sum_of_cubes(numb... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00030362",
"row_id": 30362,
"seed_ids": "[206]"
} | 0.614499 | Docs: Python310_30362 | I | [
"sum_of_squares",
"sum_of_cubes",
"max_number",
"min_number",
"process_numbers"
] | 5 | [
[
"process_numbers",
"max_number"
],
[
"process_numbers",
"min_number"
],
[
"process_numbers",
"sum_of_cubes"
],
[
"process_numbers",
"sum_of_squares"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 96e608cb76cd6dac52e7ede365390ff2c630f1c9 | 6987fcdbefc030e8e6e8732a87f125bcc424a380 | |||
v1.0 | instruct | Docs | Docs: Python310_30397_I | ### Python Signal Handling Assessment
**Objective**: Demonstrate your understanding of Python's `signal` module by implementing signal handling in a practical scenario.
### Problem Statement
You are required to implement a Python program that monitors the execution time of a long-running computation and safely handl... | import signal
import time
def long_running_computation():
while True:
# Simulate some long-running computation
time.sleep(1)
def limit_computation_time(time_limit):
def handle_alarm(signum, frame):
raise TimeoutError("Computation timed out")
def handle_interrupt(signum, frame):
... | import multiprocessing
import os
import pytest
import time
from solution import limit_computation_time
def computation_with_timeout(time_limit):
from solution import limit_computation_time
limit_computation_time(time_limit)
def test_timeout():
p = multiprocessing.Process(target=computation_with_timeout, ... | [
{
"docstring": null,
"function_declaration": "def long_running_computation():",
"function_name": "long_running_computation",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def limit_computation_time(time_limit):",
"function_name": "limit_computation_time",
... | [
0,
1,
0,
0,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\n\ndef long_running_computation():\n \"\"\"\n Simulates a long-running computation by entering an infinite loop.\n \"\"\"\n while True:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00030397",
"row_id": 30397,
"seed_ids": "[253]"
} | 0.520387 | Docs: Python310_30397 | I | [
"long_running_computation",
"limit_computation_time"
] | 2 | [
[
"limit_computation_time",
"long_running_computation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 267b6961d575e3edd48925656dfa5d84a19dcb4a | a0bbe8a3b900789e67a4dfcdeb33f1d577c02f76 | |||
v1.0 | instruct | Docs | Docs: Python310_30415_I | **Question: Email Organizer**
In this exercise, you will implement a function that organizes emails from an mbox mailbox file into categorized Maildir mailboxes based on their subject lines. Your function should split emails into different folders depending on specific keywords present in the subject line. The Maildir... | import os
import mailbox
import email
def create_maildir(base_path, folder_name):
folder_path = os.path.join(base_path, folder_name)
maildir = mailbox.Maildir(folder_path, factory=None, create=True)
return maildir
def organize_emails(mbox_path, keywords_to_folders, output_dir):
# Open the mbox file
... | import os
import shutil
import pytest
import mailbox
from solution import organize_emails
@pytest.fixture(scope="module")
def setup_mbox(tmp_path_factory):
mbox_dir = tmp_path_factory.mktemp("mbox")
mbox_path = os.path.join(mbox_dir, "test.mbox")
mbox = mailbox.mbox(mbox_path)
mbox.lock()
mes... | [
{
"docstring": null,
"function_declaration": "def create_maildir(base_path, folder_name):",
"function_name": "create_maildir",
"parameter_list": "(base_path, folder_name)"
},
{
"docstring": null,
"function_declaration": "def organize_emails(mbox_path, keywords_to_folders, output_dir):",
... | [
1,
0,
1,
0,
0,
1,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport mailbox\nfrom email.utils import getaddresses\n\ndef organize_emails(mbox_path, keywords_to_folders, output_dir):\n \"\"\"\n Organizes emails fr... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00030415",
"row_id": 30415,
"seed_ids": "[361]"
} | 0.462751 | Docs: Python310_30415 | I | [
"create_maildir",
"organize_emails"
] | 2 | [
[
"organize_emails",
"create_maildir"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4fb8a058978232fc7339622c2770ceb64b7b0397 | 3512678365fe0afcc29973889aa01ba7f7e3c3ce |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.