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_20552_I | ### Question: Multi-Stage Data Transformation Pipeline
You are required to implement a data transformation pipeline. This pipeline will accept a list of dictionaries as input, each representing a user's data, and will output a list of dictionaries after processing.
The transformation will involve multiple stages:
1.... | def filter_users(users, age_threshold):
"""
Filters the users whose age is greater than or equal to the age_threshold.
Parameters:
users (list): A list of user dictionaries.
age_threshold (int): Age threshold for filtering.
Returns:
list: A list of filtered user dictionaries.
... | from solution import filter_users, transform_users, aggregate_data, data_pipeline
def test_filter_users():
users = [
{"first_name": "John", "last_name": "Doe", "age": 25, "email": "JOHN.DOE@MAIL.COM"},
{"first_name": "Jane", "last_name": "Doe", "age": 22, "email": "JANE.DOE@MAIL.COM"},
{"fi... | [
{
"docstring": "Filters the users whose age is greater than or equal to the age_threshold.\n\nParameters:\n users (list): A list of user dictionaries.\n age_threshold (int): Age threshold for filtering.\n\nReturns:\n list: A list of filtered user dictionaries.",
"function_declaration": "def filter_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def filter_users(users, age_threshold):\n \"\"\"\n Filters the users list based on the age threshold.\n \n Args:\n users (list): List of user dictionarie... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020552",
"row_id": 20552,
"seed_ids": "[426]"
} | 0.465873 | Docs: Python310_20552 | I | [
"filter_users",
"transform_users",
"aggregate_data",
"data_pipeline"
] | 4 | [
[
"data_pipeline",
"aggregate_data"
],
[
"data_pipeline",
"filter_users"
],
[
"data_pipeline",
"transform_users"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 072710f3c791bfa2088e54d22a3322c0639371c8 | 8eb13ee2bac1f757b5af5b083052086cdba7bc53 | |||
v1.0 | instruct | Docs | Docs: Python310_20604_I | #### Objective:
Implement a Python module that effectively demonstrates the comprehension of exception handling mechanisms. You will write functions to raise custom exceptions, handle those exceptions, and provide pertinent details (such as traceback and error messages).
#### Task:
1. **Create a CustomException** - D... | import traceback
class CustomException(Exception):
def __init__(self, message: str):
super().__init__(message)
self.message = message
def raise_exception():
raise CustomException("This is a custom exception with a detailed error message")
def handle_exception():
try:
raise_excepti... | import pytest
from solution import CustomException, raise_exception, handle_exception, recursive_function, query_error_state
def test_custom_exception():
with pytest.raises(CustomException) as exc_info:
raise_exception()
assert str(exc_info.value) == "This is a custom exception with a detailed error me... | [] | [
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 traceback\n\nclass CustomException(Exception):\n def __init__(self, message: str):\n super().__init__(message)\n self.message = message\n\ndef r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020604",
"row_id": 20604,
"seed_ids": "[33]"
} | 0.476105 | Docs: Python310_20604 | I | [
"raise_exception",
"handle_exception",
"recursive_function",
"query_error_state"
] | 4 | [
[
"handle_exception",
"raise_exception"
]
] | 1 | [] | false | [
"CustomException"
] | true | pytest | true | [] | true | 0f23addd88ea6ca3f0219353ddccf899aea77897 | e67d678539d015babe13e4e6dc3802b93713cd87 | |||
v1.0 | instruct | Docs | Docs: Pytorch_20606_I | **Question:**
**Implement and Manage Remote References (RRefs) using PyTorch Distributed RPC**
### Objective:
Demonstrate your understanding of Remote References (RRefs) by implementing, sharing, and managing RRef instances in a distributed PyTorch environment.
### Problem Statement:
You are given a distributed PyTo... | import torch
import torch.distributed.rpc as rpc
from torch.distributed.rpc import RRef
def add_tensors(t1, t2):
return t1 + t2
def multiply_tensors(t1, t2):
return t1 * t2
def worker_a_task():
# Create an RRef to a tensor of ones on worker_A
rref = RRef(torch.ones((3, 3)))
return rref
def worke... | import torch
import torch.distributed.rpc as rpc
from solution import add_tensors, multiply_tensors, worker_a_task, worker_b_task, worker_c_task
def test_add_tensors():
t1 = torch.ones((3, 3))
t2 = torch.full((3, 3), 2)
result = add_tensors(t1, t2)
expected = torch.full((3, 3), 3)
assert torch.equa... | [
{
"docstring": null,
"function_declaration": "def add_tensors(t1, t2):",
"function_name": "add_tensors",
"parameter_list": "(t1, t2)"
},
{
"docstring": null,
"function_declaration": "def multiply_tensors(t1, t2):",
"function_name": "multiply_tensors",
"parameter_list": "(t1, t2)"... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.distributed.rpc as rpc\nfrom torch.distributed.rpc import RRef\n\ndef add_tensors(rref, tensor):\n return rref.to_here() + tensor\n\ndef m... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020606",
"row_id": 20606,
"seed_ids": "[158]"
} | 0.347609 | Docs: Pytorch_20606 | I | [
"add_tensors",
"multiply_tensors",
"worker_a_task",
"worker_b_task",
"worker_c_task",
"run_worker"
] | 6 | [
[
"run_worker",
"worker_a_task"
],
[
"run_worker",
"worker_b_task"
],
[
"run_worker",
"worker_c_task"
]
] | 3 | [] | false | [] | false | pytest | true | [
"torch"
] | false | d97901dd4c1d82e0376a1dc02e69e871aeb41033 | 7839a0f193a61da910df334c47291cb1eb5d0deb | |||
v1.0 | instruct | Docs | Docs: Python310_20615_I | ## Coding Assessment Question
### Objective:
Design a function that demonstrates your understanding of `asyncio.Future` and its associated methods and functionality. You will create a system that gathers results from multiple asynchronous operations concurrently and process them once all operations are complete.
### ... | import asyncio
async def complete_future(future, delay, result):
await asyncio.sleep(delay)
future.set_result(result)
async def collect_future_results(async_funcs, delay, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
futures = [func() for func in async_funcs]
tasks = [
... | import asyncio
import pytest
from solution import collect_future_results
async def example_future():
return asyncio.Future()
@pytest.mark.asyncio
async def test_collect_future_results():
async_funcs = [example_future for _ in range(3)]
delay = 1
results = await collect_future_results(async_funcs, dela... | [] | [
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 collect_future_results(async_funcs, delay, loop=None):\n if loop is None:\n loop = asyncio.get_running_loop()\n\n async def exe... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020615",
"row_id": 20615,
"seed_ids": "[113]"
} | 0.606208 | Docs: Python310_20615 | I | [
"complete_future",
"collect_future_results"
] | 2 | [
[
"collect_future_results",
"complete_future"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 794aa633fe02286e47fbfbfc66f0098c5555636c | 76d637bd46ea8605b4ec1820bd1c92a76b4dfeb2 | |||
v1.0 | instruct | Docs | Docs: Pytorch_20626_I | ### PyTorch Deterministic Operations and Reproducibility
#### Objective
You are required to write a PyTorch program that demonstrates how to achieve reproducible results by controlling sources of randomness and handling nondeterministic behavior across various components including PyTorch, NumPy, and custom modules us... | import torch
import numpy as np
import random
def set_random_seeds(seed_value):
"""
Sets the random seed for PyTorch, NumPy, and Python's random module.
:param seed_value: int - the seed value.
"""
torch.manual_seed(seed_value)
torch.cuda.manual_seed(seed_value)
torch.cuda.manual_seed_... | import torch
from torch.utils.data import DataLoader, Dataset
import numpy as np
import random
from solution import set_random_seeds, create_neural_network, generate_random_input, demonstrate_determinism, demonstrate_dataloader_determinism
def test_set_random_seeds():
set_random_seeds(42)
assert torch.initial... | [
{
"docstring": "Sets the random seed for PyTorch, NumPy, and Python's random module.\n\n:param seed_value: int - the seed value.",
"function_declaration": "def set_random_seeds(seed_value):",
"function_name": "set_random_seeds",
"parameter_list": "(seed_value)"
},
{
"docstring": "Creates a s... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport numpy as np\nimport random\n\ndef set_random_seeds(seed_value):\n \"\"\"\n Sets the random seed for PyTorch, NumPy, an... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00020626",
"row_id": 20626,
"seed_ids": "[174]"
} | 0.518019 | Docs: Pytorch_20626 | I | [
"set_random_seeds",
"create_neural_network",
"generate_random_input",
"demonstrate_determinism",
"demonstrate_dataloader_determinism"
] | 5 | [
[
"demonstrate_dataloader_determinism",
"set_random_seeds"
],
[
"demonstrate_determinism",
"set_random_seeds"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"torch",
"torchvision"
] | false | a7202ac307d4efef45448cfaf46aad32f41db9ac | b727b0410a58108dceee010a3177753090f90d8e | |||
v1.0 | instruct | Docs | Docs: Python310_20711_I | ### Asyncio Web Scraper
#### Objective
Write an asynchronous web scraper using the `asyncio` module in Python. The web scraper should take a list of URLs, fetch their contents concurrently, and return a dictionary with URLs as keys and their HTML contents as values.
#### Requirements
1. Implement a function `async de... | import asyncio
from typing import List, Dict, Tuple
import aiohttp
async def fetch_url(session, url: str) -> Tuple[str, str]:
try:
async with session.get(url) as response:
html = await response.text()
return url, html
except Exception as e:
return url, ""
async def fetc... | import asyncio
from solution import fetch_all
def test_fetch_all_single_url():
urls = ["http://httpbin.org/html"]
result = asyncio.run(fetch_all(urls))
assert len(result) == 1
assert "http://httpbin.org/html" in result
assert len(result["http://httpbin.org/html"]) > 0
def test_fetch_all_multiple_u... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Dict, Tuple\nimport aiohttp\n\nasync def fetch_url(session, url: str) -> Tuple[str, str]:\n \"\"\"\n Fetches the HTML con... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020711",
"row_id": 20711,
"seed_ids": "[151]"
} | 0.68492 | Docs: Python310_20711 | I | [
"fetch_url",
"fetch_all"
] | 2 | [
[
"fetch_all",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | ab8e77ca3acb9f7e2cda4b3abda85ead1a60c568 | 9c74a686b3c3a8055c8ef5302337f920ec82a3ad | |||
v1.0 | instruct | Docs | Docs: Python310_20721_I | ### Asynchronous Programming with asyncio
In this assessment, you are required to create a Python program that demonstrates your understanding of Python's asyncio library, specifically focusing on concurrency, handling long-running tasks, and using the debug features of asyncio.
#### Problem Statement
You are tasked... | import asyncio
import logging
import random
import time
from typing import List
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
async def fetch_data(source: str) -> str:
"""Simulates fetching data from a given source with a random delay."""
delay = random.uniform(0.1, 0.5)
awa... | import asyncio
import pytest
from unittest.mock import patch
from solution import fetch_data, process_data, main
@pytest.mark.asyncio
async def test_fetch_data():
with patch('solution.random.uniform', return_value=0.1):
data = await fetch_data("source_test")
assert data == "data_from_source_test"
... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport logging\nimport random\nimport time\nfrom typing import List\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020721",
"row_id": 20721,
"seed_ids": "[200]"
} | 0.532693 | Docs: Python310_20721 | I | [
"fetch_data",
"process_data",
"main",
"fetch_and_process"
] | 4 | [
[
"fetch_and_process",
"fetch_data"
],
[
"fetch_and_process",
"process_data"
]
] | 2 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | a423ebd76dc03597aa200103cc2593787ce6d983 | 9007f3b221e48239020bed18d33b102f6e9c5033 | |||
v1.0 | instruct | Docs | Docs: Scikit_20919_I | #### Objective:
Demonstrate understanding of out-of-core learning in scikit-learn by building an incremental learning pipeline.
#### Problem Statement:
You are given a text dataset that is too large to fit into memory at once. Your task is to implement an out-of-core learning pipeline to classify text documents using ... | import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
def stream_data(file_path, batch_size):
"""
Function to stream data in mini-batches from... | import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import tempfile
import os
# Testing the functions and pipeline
def test_stream_data():
# Cre... | [
{
"docstring": "Function to stream data in mini-batches from a CSV file with columns 'text' and 'label'.",
"function_declaration": "def stream_data(file_path, batch_size):",
"function_name": "stream_data",
"parameter_list": "(file_path, batch_size)"
},
{
"docstring": "Implements an out-of-co... | [
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\nimport numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.met... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020919",
"row_id": 20919,
"seed_ids": "[63]"
} | 0.498241 | Docs: Scikit_20919 | I | [
"stream_data",
"out_of_core_learning_pipeline"
] | 2 | [
[
"out_of_core_learning_pipeline",
"stream_data"
]
] | 1 | [] | false | [] | false | pytest | false | [
"matplotlib",
"numpy",
"pandas",
"sklearn"
] | false | f7dacf966e16421140bfa0c3354cb45a7b7d2806 | d3a2b7d62e92a0e6e8bd236fc5587313bb61adc4 | |||
v1.0 | instruct | Docs | Docs: Python310_20923_I | ### Question: Warning Management in Python
You are tasked with writing a Python function named `custom_warning_handler()` that will utilize the `warnings` module to manage and process warnings in a specific manner.
#### Requirements:
1. **Custom Warning Category**:
- Define a custom warning category named `CustomW... | import warnings
# Define a custom warning category
class CustomWarning(UserWarning):
pass
def emit_warning():
warnings.warn("This is a custom warning", CustomWarning)
def custom_warning_handler():
captured_warnings = []
# Filter to always show CustomWarning
warnings.simplefilter("always", Custom... | from solution import custom_warning_handler, CustomWarning
def test_custom_warning_handler():
warnings_list = custom_warning_handler()
# Two warnings should be captured
assert len(warnings_list) == 2
# Check the content of captured warnings
assert "This is a custom warning" in warnings_li... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import warnings\n\n# Define a custom warning category\nclass CustomWarning(UserWarning):\n pass\n\ndef emit_warning():\n warnings.warn(\"This is a custom warning\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020923",
"row_id": 20923,
"seed_ids": "[125]"
} | 0.522378 | Docs: Python310_20923 | I | [
"emit_warning",
"custom_warning_handler"
] | 2 | [
[
"custom_warning_handler",
"emit_warning"
]
] | 1 | [] | false | [
"CustomWarning"
] | true | pytest | true | [] | true | a2810288f0ae7ef468ba2ca45716730fd3c6c559 | b8f46d04f0b4421d42c33d2aafffa395e744f196 | |||
v1.0 | instruct | Docs | Docs: Python310_20991_I | **Title:** Implement an Automated FTP Client with File Verification
**Objective:**
To assess the student's ability to utilize the `ftplib` module for performing various FTP operations, error handling, and verifying the integrity of downloaded files.
**Problem Statement:**
You are required to implement a function `a... | import ftplib
import hashlib
def calculate_sha256_checksum(file_path):
"""
Calculate the SHA256 checksum of the given file.
:param file_path: The path to the file for which to calculate the checksum.
:return: The hexadecimal SHA256 checksum string.
"""
sha256 = hashlib.sha256()
with op... | from solution import automated_ftp_client
import hashlib
import os
# Mock ftp server settings
hostname = "test.rebex.net"
username = "demo"
password = "password"
def test_ftp_client_success(monkeypatch):
import ftplib
from io import BytesIO
# Create a fake FTP server for testing
class MockFTP:
... | [
{
"docstring": "Calculate the SHA256 checksum of the given file.\n\n:param file_path: The path to the file for which to calculate the checksum.\n:return: The hexadecimal SHA256 checksum string.",
"function_declaration": "def calculate_sha256_checksum(file_path):",
"function_name": "calculate_sha256_chec... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import ftplib\nimport hashlib\n\ndef automated_ftp_client(hostname: str, username: str, password: str, directory: str, filename: str, checksum: str) -> bool:\n try:\... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00020991",
"row_id": 20991,
"seed_ids": "[135]"
} | 0.6698 | Docs: Python310_20991 | I | [
"calculate_sha256_checksum",
"automated_ftp_client"
] | 2 | [
[
"automated_ftp_client",
"calculate_sha256_checksum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7628ed5f66465143034746d6a90d2d10f9d90e77 | 88b1e4528abb271c439199c158e407a1952f4192 | |||
v1.0 | instruct | Docs | Docs: Python310_21020_I | **Question: Implement a Comprehensive URL Fetch and Parse Utility**
*Objective:* Demonstrate your understanding of Python’s `urllib`, `http.client`, and `ipaddress` modules by implementing a utility function that fetches a URL, parses its content, and performs certain operations on the retrieved information.
*Scenari... | import urllib.request
from urllib.parse import urlparse, urljoin
from typing import List, Dict, Any
from bs4 import BeautifulSoup
import ipaddress
def fetch_html_content(url: str) -> str:
"""
Fetch the HTML content from the given URL.
Args:
- url (str): The URL to fetch HTML from.
Returns... | import pytest
from solution import fetch_html_content, extract_hyperlinks, validate_ip_addresses, url_fetch_and_parse
def test_fetch_html_content():
content = fetch_html_content("https://www.example.com")
assert "<html" in content
def test_extract_hyperlinks():
html = """
<html>
<body>
... | [
{
"docstring": "Fetch the HTML content from the given URL.\n\nArgs:\n- url (str): The URL to fetch HTML from.\n\nReturns:\n- str: The HTML content of the URL.",
"function_declaration": "def fetch_html_content(url):",
"function_name": "fetch_html_content",
"parameter_list": "(url)"
},
{
"docs... | [
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 urllib.request\nfrom urllib.parse import urlparse\nfrom bs4 import BeautifulSoup\nimport ipaddress\nfrom typing import List, Any, Dict\n\ndef fetch_html_content(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021020",
"row_id": 21020,
"seed_ids": "[160]"
} | 0.743564 | Docs: Python310_21020 | I | [
"fetch_html_content",
"extract_hyperlinks",
"validate_ip_addresses",
"url_fetch_and_parse"
] | 4 | [
[
"url_fetch_and_parse",
"extract_hyperlinks"
],
[
"url_fetch_and_parse",
"fetch_html_content"
],
[
"url_fetch_and_parse",
"validate_ip_addresses"
]
] | 3 | [] | false | [] | false | pytest | true | [
"bs4"
] | false | 25473db6a1fb2c89f340905da7123d1ab423c25d | 90f76086ac2a04fd11ffb4a37dcbff6b5678d49f | |||
v1.0 | instruct | Docs | Docs: Scikit_21021_I | **Question: Implementing an Out-of-Core Learning System**
You are asked to design an out-of-core learning system to handle a large text classification problem using scikit-learn. Your task is to:
1. Stream text data from a hypothetical large dataset.
2. Extract features using the HashingVectorizer.
3. Train an increm... | from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
def stream_data(file_path):
"""
Generator function that reads lines from a file and yields class label and text data.
Parameters:
file_path (str): Path to the text data file.
Yield... | import os
import pytest
from solution import stream_data, train_model
@pytest.fixture
def create_test_file():
file_path = "test_text_data.txt"
lines = [
"class1 This is a test sentence.",
"class2 Another test sentence goes here.",
"class1 Yet another test line.",
"class3 A compl... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nimport numpy as np\n\ndef stream_data(file_path):\n \"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021021",
"row_id": 21021,
"seed_ids": "[63]"
} | 0.420821 | Docs: Scikit_21021 | I | [
"stream_data",
"train_model"
] | 2 | [
[
"train_model",
"stream_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sklearn"
] | false | 1df94d5758f796a8efaa82cbb329b3c6f659ef52 | 7bba52c65f15bdc1a1562a7d42a40a45c116bb08 | |||
v1.0 | instruct | Docs | Docs: Pytorch_21030_I | Mixed Backend Model Execution
**Context:**
You are required to implement a functionality in PyTorch that checks if the ONNX Runtime (ONNXRT) backend is supported in the current environment and then performs model conversion and execution using this backend if supported.
**Task:**
1. **Check Backend Support**: Write ... | import torch
import torch.onnx
def check_onnx_backend_support() -> bool:
try:
return torch.onnx.is_onnxrt_backend_supported()
except AttributeError:
# Function is_onnxrt_backend_supported might not be available in all versions.
return False
def convert_and_run_model(model: torch.nn.Mod... | import torch
import torch.nn as nn
from solution import check_onnx_backend_support, convert_and_run_model
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = nn.Linear(2, 2)
def forward(self, x):
return self.fc(x)
def test_check_onnx_bac... | [
{
"docstring": null,
"function_declaration": "def check_onnx_backend_support():",
"function_name": "check_onnx_backend_support",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def convert_and_run_model(model, input_tensor):",
"function_name": "convert_and_run... | [
0,
0,
0,
1,
0,
1,
1,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.onnx\n\ndef check_onnx_backend_support() -> bool:\n try:\n return torch.onnx.is_onnxrt_backend_supported()\n except AttributeErr... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00021030",
"row_id": 21030,
"seed_ids": "[55]"
} | 0.447913 | Docs: Pytorch_21030 | I | [
"check_onnx_backend_support",
"convert_and_run_model"
] | 2 | [
[
"convert_and_run_model",
"check_onnx_backend_support"
]
] | 1 | [] | false | [] | false | pytest | true | [
"onnxruntime",
"torch"
] | false | e402f84ab58ea5eb2b89dcd1b05da4b040537e40 | 13e36195d0eb94a8a18c91dbde8e8ace8f5a44b4 | |||
v1.0 | instruct | Docs | Docs: Python310_21043_I | **Objective:**
Implement a function to perform various operations using the `fractions` module in Python. This task will assess your ability to create and manipulate `Fraction` instances, utilize arithmetic operations, and apply methods like `limit_denominator` and rounding.
**Instructions:**
1. **Function Definition:... | from fractions import Fraction
def parse_fraction(fraction):
if isinstance(fraction, str):
return Fraction(fraction)
elif isinstance(fraction, list) and len(fraction) == 2:
return Fraction(fraction[0], fraction[1])
return Fraction(fraction) # handle any other input cases as appropriate
de... | from solution import manipulate_fractions
def test_create_fractions():
operations = [{'operation': 'create', 'args': [3, 4]},
{'operation': 'create', 'args': "2/3"}]
expected = ["3/4", "2/3"]
assert manipulate_fractions(operations) == expected
def test_add_fractions():
operations = [... | [
{
"docstring": null,
"function_declaration": "def parse_fraction(fraction):",
"function_name": "parse_fraction",
"parameter_list": "(fraction)"
},
{
"docstring": null,
"function_declaration": "def manipulate_fractions(operations):",
"function_name": "manipulate_fractions",
"param... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from fractions import Fraction\n\ndef manipulate_fractions(operations):\n results = []\n \n for op in operations:\n operation = op['operation']\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021043",
"row_id": 21043,
"seed_ids": "[334]"
} | 0.689706 | Docs: Python310_21043 | I | [
"parse_fraction",
"manipulate_fractions"
] | 2 | [
[
"manipulate_fractions",
"parse_fraction"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e995402ff590137400d93c425651e19253f858e7 | e44c314440078afc9fbc2bf5a5817e2ea4926eb6 | |||
v1.0 | instruct | Docs | Docs: Scikit_21147_I | ### Code Optimization and Profiling with scikit-learn
In this assessment, you are required to demonstrate your understanding of code optimization using the scikit-learn library. You will be given a simple machine learning task, where you need to implement, profile, and optimize the code.
#### Task:
1. **Implementati... | from sklearn.decomposition import NMF
from sklearn.datasets import load_digits
import numpy as np
# Step 1: Load digits dataset
X, _ = load_digits(return_X_y=True)
# Step 2: Implement and profile the NMF fitting
def original_nmf():
model = NMF(n_components=16, tol=1e-2, init='random', random_state=0)
W = mode... | from solution import original_nmf, optimized_nmf
import numpy as np
def test_original_nmf():
W, H = original_nmf()
assert W.shape[0] == 1797 # Number of samples in digits dataset
assert W.shape[1] == 16 # Number of components
assert H.shape[0] == 16 # Number of components
assert H.shape[1] =... | [
{
"docstring": null,
"function_declaration": "def original_nmf():",
"function_name": "original_nmf",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def profile_original_nmf():",
"function_name": "profile_original_nmf",
"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 sklearn.decomposition import NMF\nfrom sklearn.datasets import load_digits\nimport numpy as np\nimport timeit\n\n# Step 1: Load digits dataset\nX, _ = load_digits(... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021147",
"row_id": 21147,
"seed_ids": "[11]"
} | 0.534622 | Docs: Scikit_21147 | I | [
"original_nmf",
"profile_original_nmf",
"optimized_nmf",
"profile_optimized_nmf"
] | 4 | [
[
"profile_optimized_nmf",
"optimized_nmf"
],
[
"profile_original_nmf",
"original_nmf"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 8b7e7fb2fe29cf88e759f55a7ad968414b779c54 | e57b0f6ad7eb56015ce0e1cec7dfe58ce477e2b5 | |||
v1.0 | instruct | Docs | Docs: Python310_21156_I | ### Advanced Python Programming Assessment
**Objective:**
Implement a file processing utility in Python that demonstrates your understanding of various compound statements, exception handling, context management, function definitions, class designs, and asynchronous programming.
**Description:**
You are required to... | import os
from typing import List, Dict
import asyncio
import time
from collections import defaultdict
class FileStatistics:
def __init__(self):
self.total_words = 0
self.unique_words = set()
def process_file(self, file_content: str):
words = file_content.split()
self.total... | from solution import read_and_process_files, async_read_and_process, write_statistics_to_file, FileStatistics
import asyncio
def create_test_file(filename, content):
with open(filename, 'w', encoding='utf-8') as file:
file.write(content)
def test_read_and_process_files():
content1 = "Hello world"
... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nfrom typing import List, Dict\nimport asyncio\nimport time\nfrom collections import defaultdict\n\nclass FileStatistics:\n def __init__(self):\n se... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021156",
"row_id": 21156,
"seed_ids": "[96]"
} | 0.666222 | Docs: Python310_21156 | I | [
"read_and_process_files",
"async_read_and_process",
"read_file",
"write_statistics_to_file"
] | 4 | [
[
"async_read_and_process",
"read_file"
]
] | 1 | [] | false | [
"FileStatistics"
] | true | pytest | true | [] | true | 474a91db36037cd3a6edd39a7d1cdec4818f7891 | 353a277da163d44a2c95f115823950ff2de13ad1 | |||
v1.0 | instruct | Docs | Docs: Python310_21308_I | **Objective:**
In this assessment, you are required to demonstrate your understanding of the Python codec registry and support functions. Specifically, you will implement functions to register a custom error handler for encoding errors and create mechanisms to encode and decode strings using the codec API.
**Function... | import codecs
def custom_error_handler(exception):
"""
Custom error handler to replace problematic sections with "(error)".
"""
# exception is a UnicodeEncodeError or UnicodeDecodeError object
if isinstance(exception, (UnicodeEncodeError, UnicodeDecodeError)):
return ("(error)", exception.s... | from solution import register_custom_error_handler, custom_encode, custom_decode
def test_register_custom_error_handler():
register_custom_error_handler()
def test_custom_encode_ascii():
register_custom_error_handler()
result = custom_encode("hello π world", encoding='ascii')
assert result == b'hello ... | [
{
"docstring": "Custom error handler to replace problematic sections with \"(error)\".",
"function_declaration": "def custom_error_handler(exception):",
"function_name": "custom_error_handler",
"parameter_list": "(exception)"
},
{
"docstring": "Registers the custom error handler with the cod... | [
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 codecs\n\ndef custom_error_handler(exception):\n if isinstance(exception, (UnicodeEncodeError, UnicodeDecodeError)):\n return (\"(error)\", exception.e... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021308",
"row_id": 21308,
"seed_ids": "[47]"
} | 0.647077 | Docs: Python310_21308 | I | [
"custom_error_handler",
"register_custom_error_handler",
"custom_encode",
"custom_decode"
] | 4 | [
[
"register_custom_error_handler",
"custom_error_handler"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bd236d0a5055d1b3e7091d62674cebdf0a50e934 | d8e636b2c70c0e19f0b2371fb36004407a775bdd | |||
v1.0 | instruct | Docs | Docs: Pytorch_21342_I | **Coding Assessment Question:**
### Objective
Demonstrate your understanding of Pytorch Hub by implementing and publishing a custom model, and then loading and using this model from the Hub.
### Task
1. Create a simple custom neural network model using Pytorch.
2. Define an entrypoint function for this model in a `h... | # Step 1: Implement the Custom Model
import torch
import torch.nn as nn
class SimpleNN(nn.Module):
def __init__(self):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(10, 5)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(5, 2)
def forward(self, x):
x = self.fc1(x)
... | import torch
from solution import SimpleNN, simple_nn_model, load_from_hub
def test_model_structure():
model = SimpleNN()
assert isinstance(model, nn.Module)
assert isinstance(model.fc1, nn.Linear)
assert isinstance(model.fc2, nn.Linear)
assert isinstance(model.relu, nn.ReLU)
assert model.fc1.i... | [] | [
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\nimport torch.nn as nn\nimport torch.hub\n\nclass SimpleFFNN(nn.Module):\n def __init__(self):\n super(SimpleFFNN, self).__init__()\n self... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021342",
"row_id": 21342,
"seed_ids": "[33]"
} | 0.525711 | Docs: Pytorch_21342 | I | [
"simple_nn_model",
"load_from_hub"
] | 2 | [
[
"load_from_hub",
"simple_nn_model"
]
] | 1 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"torch"
] | false | 0c83bf21cba0c2323ceefbd2dcb9590bcd76e1a8 | 0ee149503317d33282ed4eb7d62f384f56310f9e | |||
v1.0 | instruct | Docs | Docs: Pytorch_21370_I | **Coding Assessment Question**
### Distributed Multiprocessing with Subprocesses in PyTorch
**Objective**:
Implement a function that demonstrates the usage of PyTorch's `SubprocessHandler` to manage multiple subprocesses running a simple distributed computation task.
### Problem Statement:
You are required to implem... | import torch.multiprocessing as mp
from typing import List, Any, Dict
def compute(proc_id: int) -> Dict[str, Any]:
result = {
"proc_id": proc_id,
"value": proc_id * proc_id
}
return result
def run_computation_process(proc_id: int, results: List):
results.append(compute(proc_id))
def r... | def test_run_distributed_computation():
from solution import run_distributed_computation
def equivalent_to_compute(proc_id):
return {"proc_id": proc_id, "value": proc_id * proc_id}
num_procs = 4
expected_results = [equivalent_to_compute(i) for i in range(num_procs)]
results = run_distribut... | [
{
"docstring": null,
"function_declaration": "def compute(proc_id):",
"function_name": "compute",
"parameter_list": "(proc_id)"
},
{
"docstring": null,
"function_declaration": "def run_computation_process(proc_id, results):",
"function_name": "run_computation_process",
"parameter... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch.multiprocessing as mp\nfrom typing import List, Any, Dict\n\ndef compute(proc_id: int) -> Dict[str, Any]:\n result = {\n \"proc_id\": proc_id,\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021370",
"row_id": 21370,
"seed_ids": "[152]"
} | 0.595441 | Docs: Pytorch_21370 | I | [
"compute",
"run_computation_process",
"run_distributed_computation"
] | 3 | [
[
"run_computation_process",
"compute"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | d19db0d2e7fef4347eaf29a643b4b4c81d26a267 | e9e886174efdd1d1c53d60a0d4b20e5d17fe3115 | |||
v1.0 | instruct | Docs | Docs: Python310_21372_I | **Coding Question: Profiling and Analyzing a Python Function**
### Objective
The goal of this exercise is to assess your understanding of Python's profiling tools ("cProfile", "pstats") and your ability to analyze the performance of a given function.
### Description
You are given a function `process_data(data: list) ... | import cProfile
import pstats
from io import StringIO
import os
import time
import random
# Dummy process_data function provided for testing purposes
def process_data(data: list) -> list:
def helper_func(item):
time.sleep(random.uniform(0.001, 0.003))
return item ** 2
result = []
for item ... | import os
from solution import profile_process_data, analyze_profile_results
def test_profile_process_data():
data = [i for i in range(100)]
profile_filename = profile_process_data(data)
assert os.path.isfile(profile_filename) == True
def test_analyze_profile_results():
data = [i for i in range(100)]
... | [
{
"docstring": null,
"function_declaration": "def process_data(data):",
"function_name": "process_data",
"parameter_list": "(data)"
},
{
"docstring": "Profile the process_data function using cProfile.\n\nParameters:\ndata (list): The input data to be processed.\n\nReturns:\nstr: The name of ... | [
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 cProfile\nimport pstats\nimport io\n\ndef profile_process_data(data: list) -> str:\n \"\"\"\n Profiles the process_data function, stores the profiling resu... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021372",
"row_id": 21372,
"seed_ids": "[142]"
} | 0.555389 | Docs: Python310_21372 | I | [
"process_data",
"profile_process_data",
"analyze_profile_results"
] | 3 | [
[
"profile_process_data",
"process_data"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | df47d597b7ce6404ba7054618587b3f064944d67 | 6368c209c7a92312b8bbb70e8a6b5b851c3a9cdb | |||
v1.0 | instruct | Docs | Docs: Python310_21417_I | ### Password Hashing and Validation
**Objective**: Implement a secure password hashing and validation system using the `hashlib` module in Python.
### Problem Statement
You are required to develop two functions `hash_password` and `validate_password` that utilizes the `hashlib` module to hash passwords and validate ... | import hashlib
def hash_password(password: str, salt: str) -> str:
"""
Hashes the given password concatenated with the salt using SHA-256.
Args:
password (str): The plain-text password.
salt (str): The salt string.
Returns:
str: The hexadecimal digest of the hashed pas... | from solution import hash_password, validate_password
def test_hash_password():
assert hash_password("SuperSecurePassword123!", "16CharSaltString") == hashlib.sha256(("SuperSecurePassword123!" + "16CharSaltString").encode()).hexdigest()
def test_hash_password_invalid_salt():
try:
hash_password("SuperS... | [
{
"docstring": "Hashes the given password concatenated with the salt using SHA-256.\n\nArgs:\n password (str): The plain-text password.\n salt (str): The salt string.\n\nReturns:\n str: The hexadecimal digest of the hashed password concatenated with the salt.",
"function_declaration": "def hash_pas... | [
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 hashlib\n\ndef hash_password(password: str, salt: str) -> str:\n \"\"\"\n Hashes a password with a given salt using SHA-256 and returns the hex digest stri... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021417",
"row_id": 21417,
"seed_ids": "[394]"
} | 0.756602 | Docs: Python310_21417 | I | [
"hash_password",
"validate_password"
] | 2 | [
[
"validate_password",
"hash_password"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 306989572fe9b11d0a951f528d1e6d8ab28e2f34 | 7f774f0f304c2e99482479342f569bc0f64c2a27 | |||
v1.0 | instruct | Docs | Docs: Python310_21465_I | #### Task
You are required to implement a command-line utility using the deprecated `optparse` module in Python. The utility will be a simplified version of a task manager that allows users to add, list, and delete tasks. You must demonstrate your understanding of the `optparse` module by implementing the functions de... | import os
import optparse
TASK_FILE = 'tasks.txt'
def load_tasks():
"""Load tasks from the tasks file."""
if not os.path.exists(TASK_FILE):
return []
with open(TASK_FILE, 'r') as file:
tasks = file.readlines()
return [task.strip() for task in tasks]
def save_tasks(tasks):
"""Save ... | import os
import pytest
import shutil
from solution import add_task, list_tasks, delete_task, TASK_FILE
@pytest.fixture
def setup_tasks_file():
"""Prepare a clean tasks.txt file before each test."""
if os.path.exists(TASK_FILE):
shutil.copyfile(TASK_FILE, TASK_FILE + '.bak')
yield
if os.path.ex... | [
{
"docstring": "Load tasks from the tasks file.",
"function_declaration": "def load_tasks():",
"function_name": "load_tasks",
"parameter_list": "()"
},
{
"docstring": "Save tasks to the tasks file.",
"function_declaration": "def save_tasks(tasks):",
"function_name": "save_tasks",
... | [
0,
0,
0,
1,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nfrom optparse import OptionParser\n\nTASKS_FILE = 'tasks.txt'\n\ndef save_tasks(tasks):\n with open(TASKS_FILE, 'w') as file:\n for task in tasks:\... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00021465",
"row_id": 21465,
"seed_ids": "[193]"
} | 0.488323 | Docs: Python310_21465 | I | [
"load_tasks",
"save_tasks",
"add_task",
"list_tasks",
"delete_task",
"main"
] | 6 | [
[
"add_task",
"load_tasks"
],
[
"add_task",
"save_tasks"
],
[
"delete_task",
"load_tasks"
],
[
"delete_task",
"save_tasks"
],
[
"list_tasks",
"load_tasks"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 63c6315f159d21045f857442e9c5da3943bd8938 | 30da062204a0c4f459aaa00b156bc87b9941e976 | |||
v1.0 | instruct | Docs | Docs: Python310_21475_I | **File Synchronizer Application**
### Problem Statement
You are required to implement a Python function `sync_directories(src_dir: str, dst_dir: str) -> None` using the `os` module. The function should synchronize the contents of the source directory (`src_dir`) to the destination directory (`dst_dir`). Specifically, ... | import os
import shutil
def copy_file_with_metadata(src: str, dst: str):
shutil.copy2(src, dst)
def sync_directories(src_dir: str, dst_dir: str) -> None:
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for root, dirs, files in os.walk(src_dir):
relative_path = os.path.relpath(root, s... | import os
import pytest
import shutil
from solution import sync_directories
def setup_test_environment(src_content, dst_content):
src_dir = 'test_src_dir'
dst_dir = 'test_dst_dir'
if os.path.exists(src_dir):
shutil.rmtree(src_dir)
if os.path.exists(dst_dir):
shutil.rmtree(dst_dir)
... | [
{
"docstring": null,
"function_declaration": "def copy_file_with_metadata(src, dst):",
"function_name": "copy_file_with_metadata",
"parameter_list": "(src, dst)"
},
{
"docstring": null,
"function_declaration": "def sync_directories(src_dir, dst_dir):",
"function_name": "sync_director... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport shutil\nfrom filecmp import dircmp\n\ndef sync_directories(src_dir: str, dst_dir: str) -> None:\n \"\"\"\n Recursively synchronizes the contents... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021475",
"row_id": 21475,
"seed_ids": "[106]"
} | 0.651757 | Docs: Python310_21475 | I | [
"copy_file_with_metadata",
"sync_directories"
] | 2 | [
[
"sync_directories",
"copy_file_with_metadata"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | afcae25dee8083ef436f84bce59ed1c71663a583 | 63aadfc5f6b38199bc5620452c760a8703ffef36 | |||
v1.0 | instruct | Docs | Docs: Python310_21510_I | #### Objective
Implement a function using the asyncio library that fetches data from multiple dummy URLs concurrently, processes the fetched data, and combines the results into a single output.
#### Function Signature
```python
import asyncio
async def fetch_and_process(urls: list, processing_func) -> list:
"""
... | import asyncio
async def fetch(url):
"""
Simulates fetching data from a URL by sleeping for a random time between 1 and 5 seconds.
"""
await asyncio.sleep(1)
return url
async def fetch_and_process(urls: list, processing_func) -> list:
"""
Fetches data asynchronously from a list of URLs and... | import asyncio
from solution import fetch_and_process
async def mock_processing_func(data):
await asyncio.sleep(1)
return f"processed_{data}"
def test_fetch_and_process():
urls = ["url1", "url2", "url3"]
processed_data = asyncio.run(fetch_and_process(urls, mock_processing_func))
assert processed_d... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def fetch(url):\n \"\"\"\n Simulates fetching data from a URL. \n The simulated fetch will just wait for a random period between 1 and ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021510",
"row_id": 21510,
"seed_ids": "[270]"
} | 0.590369 | Docs: Python310_21510 | I | [
"fetch",
"fetch_and_process"
] | 2 | [
[
"fetch_and_process",
"fetch"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fbffbe2908d9bd8777f1bd5307024a46bad3acfa | dea7826052aacb01b8daa038342222190f8e30d6 | |||
v1.0 | instruct | Docs | Docs: Python310_21585_I | **Question:**
You are tasked with implementing a Python function using the `tarfile` module to create a tar archive from a given directory, including only specific file types, and to extract that archive to a specified destination directory, ensuring certain security measures.
### Function signature:
```python
def cr... | import os
import tarfile
def is_within_directory(directory, target):
"""
Check if a file is within a given directory.
"""
abs_directory = os.path.abspath(directory)
abs_target = os.path.abspath(target)
prefix = os.path.commonprefix([abs_directory, abs_target])
return prefix == abs_directory... | import os
import pytest
import tarfile
import shutil
from solution import create_and_extract_tar
@pytest.fixture
def setup_dirs(tmp_path):
# Setup temporary directories
input_dir = tmp_path / "input_dir"
extract_dir = tmp_path / "extract_dir"
input_dir.mkdir()
extract_dir.mkdir()
# Create ... | [
{
"docstring": "Check if a file is within a given directory.",
"function_declaration": "def is_within_directory(directory, target):",
"function_name": "is_within_directory",
"parameter_list": "(directory, target)"
},
{
"docstring": null,
"function_declaration": "def create_and_extract_ta... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport tarfile\n\ndef is_within_directory(directory, target):\n \"\"\"\n Check if a file is within a given directory.\n \"\"\"\n abs_directory = ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021585",
"row_id": 21585,
"seed_ids": "[163]"
} | 0.661447 | Docs: Python310_21585 | I | [
"is_within_directory",
"create_and_extract_tar"
] | 2 | [
[
"create_and_extract_tar",
"is_within_directory"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5dd7e0a7df97584b666245216070364b5e26b831 | 6b041600f5f1ed7c8db9062526e22a906bc7483a | |||
v1.0 | instruct | Docs | Docs: Python310_21632_I | You are tasked with creating a Python script that periodically checks the status of multiple URLs and alerts when any of the URLs become inaccessible (i.e., return a status code other than 200).
**Requirements**:
1. Your solution should use the `urllib.request` module.
2. Implement a function `check_urls(urls: list, i... | import urllib.request
import time
import logging
logging.basicConfig(level=logging.INFO)
def check_url(url):
try:
response = urllib.request.urlopen(url)
status_code = response.getcode()
if status_code != 200:
logging.warning(f"ALERT: {url} is down! Status: {status_code}")
... | from unittest.mock import patch, Mock
from solution import check_url
def test_check_url_200():
with patch('urllib.request.urlopen', return_value = Mock(getcode = lambda: 200)):
check_url("http://www.example.com")
def test_check_url_404():
with patch('urllib.request.urlopen', return_value = Mock(getcod... | [
{
"docstring": null,
"function_declaration": "def check_url(url):",
"function_name": "check_url",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def check_urls(urls, interval):",
"function_name": "check_urls",
"parameter_list": "(urls, interval)"
}
] | [
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 urllib.request\nimport time\n\ndef check_urls(urls: list, interval: int) -> None:\n \"\"\"\n Periodically checks the status of multiple URLs and alerts whe... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021632",
"row_id": 21632,
"seed_ids": "[343]"
} | 0.686883 | Docs: Python310_21632 | I | [
"check_url",
"check_urls"
] | 2 | [
[
"check_urls",
"check_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a5738f10ab0f2a26fc6ba377a953dc436b3e8ff9 | a10ef29aa5c56822f5627dc976688f60d03e6bcd | |||
v1.0 | instruct | Docs | Docs: Python310_21684_I | ### Asynchronous File Reader with Timeout and Exception Handling
#### Background
You are given the task of implementing a function to read data from a file asynchronously, handle various asyncio-related exceptions, and ensure a timeout for the read operation.
#### Objective
Implement a function `read_file_async_with_... | import asyncio
from typing import Union
from asyncio import IncompleteReadError, LimitOverrunError
async def async_file_read(file_path: str) -> bytes:
"""
Simulates asynchronous file read operation.
"""
await asyncio.sleep(1) # Simulate I/O operation
with open(file_path, 'rb') as f:
return... | import pytest
import asyncio
from solution import read_file_async_with_timeout
@pytest.fixture
def create_test_file(tmp_path):
file_path = tmp_path / "test_file.txt"
with open(file_path, "w") as f:
f.write("Hello, World!")
return file_path
@pytest.mark.asyncio
async def test_read_file_async_with_t... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import Union\nfrom asyncio import IncompleteReadError, LimitOverrunError\n\nasync def async_file_read(file_path: str) -> bytes:\n \"\"\"\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021684",
"row_id": 21684,
"seed_ids": "[396]"
} | 0.518 | Docs: Python310_21684 | I | [
"async_file_read",
"read_file_async_with_timeout"
] | 2 | [
[
"read_file_async_with_timeout",
"async_file_read"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f4f62fe875e85150b8d92294c1a857f6e49d3e90 | 11f20032b6bb10e113977ccda47a958af46be2a6 | |||
v1.0 | instruct | Docs | Docs: Python310_21693_I | **Secure Token Management System**
Given the necessity to secure sensitive information and manage secure communication, you are tasked to implement a token management system using Python's `secrets` module. Your implementation should include the following functionalities:
1. **Generate a Secure Token**:
- Implemen... | import secrets
import string
def generate_token(token_type: str, length: int = None) -> str:
"""
Generates a secure token.
Args:
token_type (str): The type of token ('hex', 'bytes', 'urlsafe').
length (int): The number of bytes for the token. If None, default length is used.
Returns:
... | from solution import generate_token, generate_password, generate_secure_url
def test_generate_token_hex_default_length():
token = generate_token('hex')
assert len(token) == 64 # 32 bytes * 2 hex chars per byte
def test_generate_token_hex_specific_length():
token = generate_token('hex', 16)
assert len... | [
{
"docstring": "Generates a secure token.\n\nArgs:\ntoken_type (str): The type of token ('hex', 'bytes', 'urlsafe').\nlength (int): The number of bytes for the token. If None, default length is used.\n\nReturns:\nstr: The generated token.",
"function_declaration": "def generate_token(token_type, length=None... | [
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 secrets\nimport string\n\ndef generate_token(token_type: str, length: int = None) -> str:\n \"\"\"\n Generates a secure token based on the provided type an... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021693",
"row_id": 21693,
"seed_ids": "[331]"
} | 0.559282 | Docs: Python310_21693 | I | [
"generate_token",
"generate_password",
"generate_secure_url"
] | 3 | [
[
"generate_secure_url",
"generate_token"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4126b0623e8de1d39a9499e16d6136b7d8df4510 | 1fae98d5eb7a2915d182824e8673274c22e195c5 | |||
v1.0 | instruct | Docs | Docs: Python310_21702_I | **Objective:** Write a Python program using the `signal` module that handles multiple types of signals and implements a timer-based execution mechanism for a critical section of code.
**Task:**
1. Create a custom signal handler that logs the signal number and the stack frame information.
2. Set up handlers for `SIGIN... | import signal
import time
import os
import traceback
LOG_FILE = 'signal_log.txt'
def log_signal(signum, frame):
"""
Logs the signal number and stack frame information to a file.
"""
with open(LOG_FILE, 'a') as f:
f.write(f"Signal received: {signum}, Frame: {repr(frame)}\n")
if signum =... | import os
import signal
from time import sleep
# Duplicate part of the solution for the testing scope
def log_signal(signum, frame):
with open(LOG_FILE, 'a') as f:
f.write(f"Signal received: {signum}, Frame: {repr(frame)}\n")
if signum == signal.SIGALRM:
f.write("SIGALRM received, termi... | [
{
"docstring": "Logs the signal number and stack frame information to a file.",
"function_declaration": "def log_signal(signum, frame):",
"function_name": "log_signal",
"parameter_list": "(signum, frame)"
},
{
"docstring": null,
"function_declaration": "def handler(signum, frame):",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\nimport time\nimport os\nimport traceback\n\nLOG_FILE = 'signal_log.txt'\n\ndef log_signal(signum, frame):\n \"\"\"\n Logs the signal number and sta... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021702",
"row_id": 21702,
"seed_ids": "[253]"
} | 0.506198 | Docs: Python310_21702 | I | [
"log_signal",
"handler",
"sigusr1_handler",
"critical_section",
"main"
] | 5 | [
[
"handler",
"log_signal"
],
[
"sigusr1_handler",
"log_signal"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 3b3259ab773981774c0e0aa05f96321effdecd03 | a672b7228966745612c841999757df9b776ab82a | |||
v1.0 | instruct | Docs | Docs: Python310_21710_I | **Question: Parsing Command-Line Arguments for a Data Processing Script**
You are tasked with writing a Python script that processes data from a list of input files and performs various operations (such as summing or averaging numeric values) based on command-line arguments. You need to use the `argparse` module to ha... | import argparse
import sys
def process_file(file):
with open(file, 'r') as f:
data = f.read().split()
return list(map(float, data))
def process_arguments(argv=None):
parser = argparse.ArgumentParser(description='Process some numeric data.')
group = parser.add_mutually_exclusive_group(... | from solution import process_arguments
import pytest
import tempfile
import os
# Utility function to create a temporary file with given content
def create_temp_file(content):
temp_file = tempfile.NamedTemporaryFile(delete=False)
with open(temp_file.name, 'w') as f:
f.write(content)
return temp_file... | [
{
"docstring": null,
"function_declaration": "def process_file(file):",
"function_name": "process_file",
"parameter_list": "(file)"
},
{
"docstring": null,
"function_declaration": "def process_arguments(argv=None):",
"function_name": "process_arguments",
"parameter_list": "(argv=... | [
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 argparse\nimport sys\n\ndef read_file_data(filepaths):\n data = []\n for filepath in filepaths:\n with open(filepath, 'r') as file:\n for... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00021710",
"row_id": 21710,
"seed_ids": "[139]"
} | 0.527223 | Docs: Python310_21710 | I | [
"process_file",
"process_arguments"
] | 2 | [
[
"process_arguments",
"process_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6967e9737f77411c490cdf89ff25ebb6b34c401c | ecab51ccfefb0e11736e290eab7ab9080b865f27 | |||
v1.0 | instruct | Docs | Docs: Python310_21725_I | **System-Level Interaction Challenge**
Python provides various utility functions to interact with the underlying system's internal states and capabilities considered part of stable ABI. Your task is to implement a Python program that simulates a practical scenario using these utility functions to ensure the proper han... | import os
import signal
import ctypes
# Using ctypes to bind necessary C functions
libc = ctypes.CDLL(None)
libc.isatty.argtypes = [ctypes.c_int]
libc.isatty.restype = ctypes.c_int
libc.fdopen.argtypes = [ctypes.c_int, ctypes.c_char_p]
libc.fdopen.restype = ctypes.c_void_p
# Interactive file check function
def is_int... | from solution import is_interactive_file, get_and_set_signal_handler, decode_locale_string, encode_locale_string
import os
import signal
def test_is_interactive_file():
assert is_interactive_file("/dev/tty") == True # Interactive if terminal
tmp_filename = 'tmp_regular_file.txt'
with open(tmp_filename, ... | [
{
"docstring": null,
"function_declaration": "def is_interactive_file(filepath):",
"function_name": "is_interactive_file",
"parameter_list": "(filepath)"
},
{
"docstring": null,
"function_declaration": "def PyOS_getsig(n):",
"function_name": "PyOS_getsig",
"parameter_list": "(n)"... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import ctypes\nimport locale\nimport signal\n\n# Attempting to create Python bindings using ctypes for the specified C functions.\n# Normally, these are not available d... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021725",
"row_id": 21725,
"seed_ids": "[49]"
} | 0.511027 | Docs: Python310_21725 | I | [
"is_interactive_file",
"PyOS_getsig",
"PyOS_setsig",
"get_and_set_signal_handler",
"decode_locale_string",
"encode_locale_string"
] | 6 | [
[
"get_and_set_signal_handler",
"PyOS_getsig"
],
[
"get_and_set_signal_handler",
"PyOS_setsig"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8e92356862d745c05853dcd4b05eb457ff549d6b | f94a58bd95c6e9872b29ea93bcdd8d8472597552 | |||
v1.0 | instruct | Docs | Docs: Python310_21732_I | #### Advanced Argument Parsing and Automatic Signature Generation in Python
**Objective:**
You are tasked with creating a Python utility that mimics some of the features of CPython's Argument Clinic for Python functions. This utility will help define functions with specific argument types, default values, and automati... | import functools
def argument_clinic(metadata):
def decorator(func):
# Generate the signature
args_signature = ', '.join(
f"{name}: {arg_type.__name__}={repr(default_value)}" if not is_positional_only else f"{name}: {arg_type.__name__}={repr(default_value)}"
for name, arg_ty... | import pytest
from solution import calculate
def test_calculate_addition():
assert calculate(1, 2, operation='add') == 3
assert calculate(1, 2) == 3 # Default 'add' operation
def test_calculate_subtraction():
assert calculate(3, 1, operation='subtract') == 2
def test_calculate_invalid_operation():
w... | [
{
"docstring": null,
"function_declaration": "def argument_clinic(metadata):",
"function_name": "argument_clinic",
"parameter_list": "(metadata)"
},
{
"docstring": null,
"function_declaration": "def calculate(x, y, operation):",
"function_name": "calculate",
"parameter_list": "(x... | [
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 functools\nimport inspect\n\ndef argument_clinic(metadata):\n def decorator(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021732",
"row_id": 21732,
"seed_ids": "[64]"
} | 0.673917 | Docs: Python310_21732 | I | [
"argument_clinic",
"calculate"
] | 2 | [
[
"calculate",
"argument_clinic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7956131a951bdb69c8e677cfad0a13fa5086cdbe | 275830f6fa882782935b678d96c392ce6479375b | |||
v1.0 | instruct | Docs | Docs: Python310_21812_I | ### PyCapsule Manipulation in Python
You are provided with several C API functions to create and manipulate PyCapsule objects in Python. Implement the following functions in Python that would simulate the behavior of some of these C API functions while maintaining the encapsulated pointer's integrity.
#### Function 1... | def create_capsule(pointer: int, name: str, destructor: callable = None) -> dict:
"""
Create a PyCapsule encapsulating the pointer.
Parameters:
pointer (int): An integer representing the memory address (simulated pointer).
name (str): A string name for the capsule.
destructor (callable, optiona... | from solution import create_capsule, is_capsule_valid, get_capsule_pointer, set_capsule_name
def test_create_capsule():
capsule = create_capsule(123456789, "module.attribute")
assert capsule["pointer"] == 123456789
assert capsule["name"] == "module.attribute"
assert capsule["destructor"] is None
def t... | [
{
"docstring": "Create a PyCapsule encapsulating the pointer.\n\nParameters:\npointer (int): An integer representing the memory address (simulated pointer).\nname (str): A string name for the capsule.\ndestructor (callable, optional): A destructor function to be called upon capsule deletion.\n\nReturns:\ndict: ... | [
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_capsule(pointer: int, name: str, destructor: callable = None) -> dict:\n \"\"\"\n Create a PyCapsule encapsulating the pointer.\n\n Parameters:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021812",
"row_id": 21812,
"seed_ids": "[16]"
} | 0.36937 | Docs: Python310_21812 | I | [
"create_capsule",
"is_capsule_valid",
"get_capsule_pointer",
"set_capsule_name"
] | 4 | [
[
"get_capsule_pointer",
"is_capsule_valid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5c2bb462cdc8df291fab39cbfff023cf79e5005c | 367a4ddfcaac6e86e7c6a7346c54658138d29578 | |||
v1.0 | instruct | Docs | Docs: Python310_21826_I | ### asyncio Server-Client Communication
#### Objective:
Your task is to implement a simple server-client architecture using the asyncio package in Python 3.10. The server should handle multiple client connections, and the client should be able to send messages to the server and receive responses. You will also need to... | import asyncio
class CustomServerProtocol(asyncio.Protocol):
def __init__(self):
super().__init__()
self.transport = None
def connection_made(self, transport):
self.transport = transport
peername = transport.get_extra_info('peername')
print(f'Connection made from {peer... | import asyncio
from solution import start_server, start_client
async def test_server_response():
server_task = asyncio.create_task(run_server())
await asyncio.sleep(1) # allow server time to start
response = await tcp_client('Hello, server!')
assert response == 'Server Response: Hello, server!'
... | [] | [
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\nclass EchoServerProtocol(asyncio.Protocol):\n def connection_made(self, transport):\n self.transport = transport\n print('Connection ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021826",
"row_id": 21826,
"seed_ids": "[101]"
} | 0.641804 | Docs: Python310_21826 | I | [
"run_server",
"tcp_client",
"start_server",
"start_client"
] | 4 | [
[
"start_client",
"tcp_client"
],
[
"start_server",
"run_server"
]
] | 2 | [] | false | [
"CustomServerProtocol"
] | true | pytest | true | [] | true | 0718d9cb3ae64bb41b63fd6d03b5e7d120364285 | 8b16b828514345d27ebcb192b6fb841cf719f40d | |||
v1.0 | instruct | Docs | Docs: Python310_21853_I | ### Mailcap File Handler Implementation
Mailcap files are essential for configuring how MIME-aware applications handle files with different MIME types. Python's `mailcap` module provides tools to interact with these files. In this task, you are required to work with a subset of this module's functionalities to demonst... | import re
def get_caps_from_string(mailcap_string):
"""
Parses a string containing mailcap entries and returns a dictionary mapping
MIME types to lists of action dictionaries.
Args:
- mailcap_string (str): A string where each line is a mailcap entry, in the format
'MIMEtype; action'
... | from solution import get_caps_from_string, find_match
def test_get_caps_from_string():
mailcap_string = """
video/mpeg; xmpeg %s
text/html; browser %s
text/plain; cat %s
application/pdf; pdfreader %s
"""
expected_output = {
'video/mpeg': [{'view': 'xmpeg %s'}],
'text/html': ... | [
{
"docstring": "Parses a string containing mailcap entries and returns a dictionary mapping\nMIME types to lists of action dictionaries.\n\nArgs:\n- mailcap_string (str): A string where each line is a mailcap entry, in the format\n 'MIMEtype; action'\n\nReturns:\n- dict: A dictionary where each key is a MIME t... | [
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef get_caps_from_string(mailcap_string):\n \"\"\"\n Parses a string containing mailcap entries and returns a dictionary mapping\n MIME types to l... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00021853",
"row_id": 21853,
"seed_ids": "[399]"
} | 0.546618 | Docs: Python310_21853 | I | [
"get_caps_from_string",
"valid_filename",
"find_match"
] | 3 | [
[
"find_match",
"valid_filename"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a588f65ed52532fa87992a871fe16229e96c1518 | bada5eadf6edd133544d0be5c29819e4e589174d | |||
v1.0 | instruct | Docs | Docs: Pytorch_21866_I | ### Custom Function Implementation and Gradient Check
#### Objective:
Implement a custom function in PyTorch and verify its gradient using `torch.autograd.gradcheck`. This exercise will test your understanding of automatic differentiation, both in the real and complex domains, and the use of PyTorch's `gradcheck` util... | import torch
from torch.autograd import Function
class FReal(Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return torch.sin(x) * x ** 2
@staticmethod
def backward(ctx, grad_output):
x, = ctx.saved_tensors
grad_x = grad_output * (2 * x * torch.si... | import torch
from solution import verify_gradients, f_real, f_complex
def test_gradcheck_real():
real_ok, _ = verify_gradients()
assert real_ok, "Gradcheck for f_real did not pass."
def test_gradcheck_complex():
_, complex_ok = verify_gradients()
assert complex_ok, "Gradcheck for f_complex did not pas... | [] | [
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 torch\nfrom torch.autograd import Function\n\nclass FReal(Function):\n @staticmethod\n def forward(ctx, x):\n ctx.save_for_backward(x)\n retu... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00021866",
"row_id": 21866,
"seed_ids": "[179]"
} | 0.437377 | Docs: Pytorch_21866 | I | [
"f_real",
"f_complex",
"verify_gradients"
] | 3 | [
[
"verify_gradients",
"f_complex"
],
[
"verify_gradients",
"f_real"
]
] | 2 | [] | false | [
"FReal",
"FComplex"
] | true | pytest | true | [
"torch"
] | false | 4f147866a3370a0b3ca635491a87640ff36c6d48 | e6309d24a7e7c89bb7c945f3c57714b212d64455 | |||
v1.0 | instruct | Docs | Docs: Pytorch_21899_I | ### PyTorch FX Numeric Suite: Compute Tensor Metrics
**Objective:**
In this assessment, you'll demonstrate your understanding of the PyTorch FX numeric suite utilities by implementing functions that utilize core metrics to compare two input tensors. You will be required to:
1. Use the provided utility functions to co... | import torch
from torch.ao.ns.fx.utils import compute_sqnr, compute_normalized_l2_error, compute_cosine_similarity
from typing import Dict
def compute_sqnr_metric(tensor1: torch.Tensor, tensor2: torch.Tensor) -> float:
if tensor1.shape != tensor2.shape:
raise ValueError("The shapes of tensor1 and tensor2 m... | import torch
import pytest
from solution import compute_sqnr_metric, compute_normalized_l2_metric, compute_cosine_similarity_metric, compute_all_metrics
@pytest.fixture
def sample_tensors():
tensor1 = torch.tensor([1.0, 2.0, 3.0])
tensor2 = torch.tensor([1.0, 2.1, 2.9])
return tensor1, tensor2
def test_co... | [
{
"docstring": null,
"function_declaration": "def compute_sqnr_metric(tensor1, tensor2):",
"function_name": "compute_sqnr_metric",
"parameter_list": "(tensor1, tensor2)"
},
{
"docstring": null,
"function_declaration": "def compute_normalized_l2_metric(tensor1, tensor2):",
"function_n... | [
0,
0,
0,
0,
0,
0,
1,
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\nfrom torch.ao.ns.fx.utils import compute_sqnr, compute_normalized_l2_error, compute_cosine_similarity\nfrom typing import Dict\n\ndef compute_sqnr_metric(... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00021899",
"row_id": 21899,
"seed_ids": "[57]"
} | 0.556385 | Docs: Pytorch_21899 | I | [
"compute_sqnr_metric",
"compute_normalized_l2_metric",
"compute_cosine_similarity_metric",
"compute_all_metrics"
] | 4 | [
[
"compute_all_metrics",
"compute_cosine_similarity_metric"
],
[
"compute_all_metrics",
"compute_normalized_l2_metric"
],
[
"compute_all_metrics",
"compute_sqnr_metric"
]
] | 3 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 2f0a2a2cb8842b5473e1c5db7f03bdfbac2a6394 | 1bf2c7abca0c66ddd4f477d346a802ec91702e29 | |||
v1.0 | instruct | Docs | Docs: Pytorch_21975_I | ### Distributed Training with PyTorch
**Objective:**
Your task is to implement a fault-tolerant distributed training script using PyTorch and Torch Distributed Elastic. This will assess your understanding of setting up distributed training, handling node synchronization, and ensuring the training is resilient to node... | import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
import torch.distributed.elastic.multiprocessing as mp
from torch.utils.data import DataLoader, DistributedSampler
import torch.optim as optim
import torch.nn as nn
import os
def initialize_distributed_process_gr... | import os
from solution import SimpleModel, save_model, load_model
def test_model_save_and_load():
model = SimpleModel()
save_path = "test_checkpoint.pth"
# Initial epoch to save
save_model(model, 3, path=save_path)
assert os.path.exists(save_path), "Checkpoint file not created."
new_model = ... | [] | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport torch\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00021975",
"row_id": 21975,
"seed_ids": "[21]"
} | 0.463492 | Docs: Pytorch_21975 | I | [
"initialize_distributed_process_group",
"load_data",
"save_model",
"load_model",
"train"
] | 5 | [
[
"train",
"initialize_distributed_process_group"
],
[
"train",
"load_data"
],
[
"train",
"load_model"
],
[
"train",
"save_model"
]
] | 4 | [] | false | [
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | 7ee9b565bb76f0622ac5a17b3d0a3cc8f39db0dc | 897e48c0601f88941b77c60fae06460ec91afda1 | |||
v1.0 | instruct | Docs | Docs: Python310_21982_I | The `tabnanny` module is used to detect ambiguous indentation in Python files. It includes functions to check files and directories for such issues and provides diagnostic messages.
Your task is to implement a simplified version of a tool similar to `tabnanny` that checks Python files for specific whitespace-related i... | import tokenize
import os
def check_indentation(file_path):
"""
Checks the file for mixed or inconsistent indentation and prints issues found.
"""
with open(file_path, 'r') as f:
tokens = list(tokenize.generate_tokens(f.readline))
last_indent = None
spaces = 0
tabs = 0
for token... | import os
import pytest
from solution import check_indentation, check_directory
def test_check_indentation_mixed():
with open("mixed_indentation.py", "w") as f:
f.write("def function():\n\t print('hello')\n")
expected_output = [
"File: mixed_indentation.py, Line: 2 - Mixed indentation"
]
... | [
{
"docstring": "Checks the file for mixed or inconsistent indentation and prints issues found.",
"function_declaration": "def check_indentation(file_path):",
"function_name": "check_indentation",
"parameter_list": "(file_path)"
},
{
"docstring": "Recursively checks all .py files in the direc... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import tokenize\nimport os\n\ndef check_indentation(file_path: str) -> None:\n with open(file_path, 'r') as f:\n tokens = tokenize.generate_tokens(f.readline)... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00021982",
"row_id": 21982,
"seed_ids": "[293]"
} | 0.539198 | Docs: Python310_21982 | I | [
"check_indentation",
"check_directory"
] | 2 | [
[
"check_directory",
"check_indentation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0236abef4f2a79aea7bd0a40bdd59d6806a54af4 | 16468cba4d6fc73ac38e5f62f64e0eca89a1ce9a | |||
v1.0 | instruct | Docs | Docs: Python310_21984_I | ### Contextual Data Management in Concurrent Tasks
As an exercise, you will implement a function `manage_context_data` to demonstrate the use of the contextvars module for handling contextual data within asynchronous tasks. This function will be composed of a nested structure of asynchronous tasks where different cont... | import asyncio
import contextvars
var1 = contextvars.ContextVar('var1', default=0)
var2 = contextvars.ContextVar('var2', default=None)
async def task1():
"""
Task 1 sets the context variables var1 and var2 and runs task2 within its context.
"""
token1 = var1.set(10)
var2.set(20)
print(f"Values... | import pytest
import asyncio
from contextvars import ContextVar
from solution import manage_context_data, var1, var2
@pytest.mark.asyncio
async def test_manage_context_data_initial_values():
# Test initial values
assert var1.get() == 0
assert var2.get() is None
@pytest.mark.asyncio
async def test_manage_c... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport contextvars\n\nvar1 = contextvars.ContextVar('var1', default=0)\nvar2 = contextvars.ContextVar('var2', default=None)\n\nasync def task1():\n \... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021984",
"row_id": 21984,
"seed_ids": "[60]"
} | 0.499547 | Docs: Python310_21984 | I | [
"task1",
"task2",
"manage_context_data"
] | 3 | [
[
"manage_context_data",
"task1"
],
[
"task1",
"task2"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ebe7d434518177869e237be683278a40d076fb70 | 639c40765ad9af7203d7868a508b842aaa07be70 | |||
v1.0 | instruct | Docs | Docs: Python310_22012_I | #### Background:
You are tasked with building a simple producer-consumer system where multiple producers are generating data, and multiple consumers are processing that data. You will use the `asyncio` library to implement this system asynchronously.
#### Task:
Write a Python function named `producer_consumer_system... | import asyncio
from typing import NoReturn
async def producer(queue: asyncio.Queue, id: int) -> None:
for i in range(1, 11):
await asyncio.sleep(0.1) # Simulate time taken to produce an item
await queue.put(f'Producer {id}: {i}')
async def consumer(queue: asyncio.Queue, id: int) -> None:
... | import asyncio
import io
import pytest
from solution import producer_consumer_system
@pytest.mark.asyncio
async def test_producer_consumer_system(monkeypatch, capsys):
# Capture print statements from consumer coroutine
monkeypatch.setattr('sys.stdout', io.StringIO())
await producer_consumer_system()... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import NoReturn\n\nasync def producer(queue: asyncio.Queue, producer_id: int) -> None:\n for i in range(1, 11):\n await asyncio.sl... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022012",
"row_id": 22012,
"seed_ids": "[270]"
} | 0.529324 | Docs: Python310_22012 | I | [
"producer",
"consumer",
"producer_consumer_system"
] | 3 | [
[
"producer_consumer_system",
"consumer"
],
[
"producer_consumer_system",
"producer"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 70834e27dbab1f6069ce8a9026ad69ca3a5cdaba | d5976b6c297e196ce0907a5036679b42956aae07 | |||
v1.0 | instruct | Docs | Docs: Python310_22039_I | ### Asynchronous HTTP Server Assessment
Implement an Asynchronous HTTP Server using `asyncio` streams that can handle multiple client connections simultaneously. The server should be capable of accepting HTTP GET requests and responding with a simple HTML page. Clients can connect, request an HTML page, and receive th... | import asyncio
async def handle_client(reader, writer):
try:
request = (await reader.read(1024)).decode('utf-8')
if request.startswith('GET'):
response = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<html><body><h1>Hello, World!</h1></body></html>\r\n'
else:
re... | import asyncio
import socket
import pytest
from solution import start_http_server
@pytest.fixture(scope="module")
def event_loop():
loop = asyncio.get_event_loop()
yield loop
loop.close()
@pytest.fixture(scope="module")
def server(event_loop):
task = event_loop.create_task(start_http_server('127.0.0.1... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n try:\n request = (await reader.read(1024)).decode('utf-8')\n if request.startswith('GET'):... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00022039",
"row_id": 22039,
"seed_ids": "[182]"
} | 0.615031 | Docs: Python310_22039 | I | [
"handle_client",
"start_http_server"
] | 2 | [
[
"start_http_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aab672b24e5a07c61aa4400ba0d9d837c92413e9 | a7df682257609687b37e559882c57224bd3f60db | |||
v1.0 | instruct | Docs | Docs: Python310_22044_I | Advanced Python Debugging
#### Objective:
Demonstrate your understanding of the Python Debugger (`pdb` module) by creating and debugging a Python script. The task will evaluate your ability to use breakpoints, inspect stack frames, evaluate expressions, and handle post-mortem debugging.
#### Task Description:
You are... | import pdb
def process_numbers(numbers):
pdb.set_trace() # Part 1: Setting a breakpoint at the start of the function
result = 0
for num in numbers:
if num % 2 == 0:
result += num ** 2
else:
result -= 'NaN' # Intentional bug: cannot subtract string from int
ret... | from solution import process_numbers_fixed
def test_process_numbers_fixed_with_even_and_odd_numbers():
assert process_numbers_fixed([1, 2, 3, 4, 5, 6]) == 56
def test_process_numbers_fixed_with_even_numbers_only():
assert process_numbers_fixed([2, 4, 6, 8]) == 120
def test_process_numbers_fixed_with_odd_numb... | [
{
"docstring": null,
"function_declaration": "def process_numbers(numbers):",
"function_name": "process_numbers",
"parameter_list": "(numbers)"
},
{
"docstring": null,
"function_declaration": "def main():",
"function_name": "main",
"parameter_list": "()"
},
{
"docstring":... | [
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": "# Fixed faulty program with pdb debugging\n\nimport pdb\n\ndef process_numbers(numbers):\n result = 0\n \n # Part 1: Use set_trace method to set a breakpoint\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00022044",
"row_id": 22044,
"seed_ids": "[342]"
} | 0.585481 | Docs: Python310_22044 | I | [
"process_numbers",
"main",
"process_numbers_fixed",
"main_fixed"
] | 4 | [
[
"main_fixed",
"process_numbers_fixed"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e6d91c10690714bb1501d979e6648dcbb5c2b637 | 6f1028dcdb734348706c6b3162b2147fa9073b10 | |||
v1.0 | instruct | Docs | Docs: Python310_22101_I | **Question:**
As a Pythonista, you may sometimes need to ensure the 'pip' package installer is available in your Python environment programmatically. To assess your understanding of the `ensurepip` package, you are required to write a function that uses this package to check the current version of "pip" available and ... | import ensurepip
import subprocess
def is_version_less(current_version, min_version):
current_parts = list(map(int, current_version.split('.')))
min_parts = list(map(int, min_version.split('.')))
return current_parts < min_parts
def bootstrap_pip_if_needed(upgrade=False, user_install=False, verbosity_leve... | from unittest.mock import patch, MagicMock
import subprocess
import ensurepip
from solution import bootstrap_pip_if_needed, is_version_less
def test_is_version_less():
assert is_version_less("20.3", "21.0") == True
assert is_version_less("21.0", "21.0") == False
assert is_version_less("21.1", "21.0") == Fa... | [
{
"docstring": null,
"function_declaration": "def is_version_less(current_version, min_version):",
"function_name": "is_version_less",
"parameter_list": "(current_version, min_version)"
},
{
"docstring": null,
"function_declaration": "def bootstrap_pip_if_needed(upgrade=False, user_insta... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import ensurepip\nimport subprocess\n\ndef is_version_less(current_version, min_version):\n current_parts = list(map(int, current_version.split('.')))\n min_parts... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022101",
"row_id": 22101,
"seed_ids": "[194]"
} | 0.587749 | Docs: Python310_22101 | I | [
"is_version_less",
"bootstrap_pip_if_needed"
] | 2 | [
[
"bootstrap_pip_if_needed",
"is_version_less"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2e5696b675309022cb73b828eaa160884ec3975b | 34566d3d851c0f170f3ee5de6d54cbb5850f1fbd | |||
v1.0 | instruct | Docs | Docs: Python310_22105_I | ### Advanced Coding Assessment: Custom Set Manipulations in Python
You are required to implement advanced functionalities for set manipulations in Python. This will involve creating and operating on `set` and `frozenset` types. You should demonstrate your understanding of these operations by completing the following t... | def create_set(iterable):
"""
Create a new set from the given iterable.
Parameters:
iterable: An iterable from which to create the set. Can be None.
Returns:
set: A new set containing the elements from the iterable.
"""
return set() if iterable is None else set(iterable)
def c... | from solution import create_set, contains_element, add_element, remove_element, clear_set
def test_create_set():
assert create_set([1, 2, 3]) == {1, 2, 3}
assert create_set(None) == set()
assert create_set("abc") == {'a', 'c', 'b'}
def test_contains_element():
s = {1, 2, 3}
assert contains_element... | [
{
"docstring": "Create a new set from the given iterable.\n\nParameters:\niterable: An iterable from which to create the set. Can be None.\n\nReturns:\nset: A new set containing the elements from the iterable.",
"function_declaration": "def create_set(iterable):",
"function_name": "create_set",
"par... | [
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_set(iterable):\n \"\"\"\n Create a new set from the given iterable.\n \n Parameters:\n iterable: An iterable from which to create the set. Can... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022105",
"row_id": 22105,
"seed_ids": "[24]"
} | 0.462856 | Docs: Python310_22105 | I | [
"create_set",
"contains_element",
"add_element",
"remove_element",
"clear_set"
] | 5 | [
[
"add_element",
"contains_element"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c324eb9012f237bfdc86e43e7db694369cfa3633 | 5024ede6b72013f64c0d9dac573fa16955bffa75 | |||
v1.0 | instruct | Docs | Docs: Python310_22139_I | ### Secure File Hashing and Integrity Verification
In this programming assessment, you will implement a Python script that securely hashes the contents of a file and verifies its integrity. The solution will make use of the `hashlib` module for hashing and must be capable of handling different hashing algorithms provi... | import hashlib
def hash_file(file_path: str, algorithm: str, salt: bytes = None, key: bytes = None, digest_size: int = None) -> str:
try:
with open(file_path, 'rb') as f:
file_content = f.read()
except FileNotFoundError:
raise FileNotFoundError(f"No such file: {file_path}")
... | from solution import hash_file, verify_file_integrity
import tempfile
import os
def create_temp_file(content):
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.write(content)
temp_file.close()
return temp_file.name
def remove_temp_file(file_path):
os.remove(file_path)
def test_hash... | [
{
"docstring": null,
"function_declaration": "def hash_file(file_path, algorithm, salt=None, key=None, digest_size=None):",
"function_name": "hash_file",
"parameter_list": "(file_path, algorithm, salt=None, key=None, digest_size=None)"
},
{
"docstring": null,
"function_declaration": "def... | [
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 hashlib\n\ndef hash_file(file_path: str, algorithm: str, salt: bytes = None, key: bytes = None, digest_size: int = None) -> str:\n h = None\n if algorithm.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022139",
"row_id": 22139,
"seed_ids": "[225]"
} | 0.658289 | Docs: Python310_22139 | I | [
"hash_file",
"verify_file_integrity"
] | 2 | [
[
"verify_file_integrity",
"hash_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dd3a3f55bebf2cbbaa1834a8568a10d2dba4f4bf | 65c01514eaf359d870507b39410c0f27d689d4b2 | |||
v1.0 | instruct | Docs | Docs: Pytorch_22150_I | ### PyTorch Threading and Parallelism Challenge
#### Objective
Design a function utilizing PyTorch's TorchScript to perform parallel computations and adjust thread settings to optimize performance for matrix multiplication operations.
#### Problem Statement
You are given two matrices, `A` and `B`, both of size `N x N... | import torch
import timeit
@torch.jit.script
def matrix_multiplication(A: torch.Tensor, B: torch.Tensor, C: torch.Tensor) -> torch.Tensor:
# Perform asynchronous matrix multiplication
result = torch.jit._fork(torch.mm, A, B)
out = torch.jit._wait(result)
return out + C
def optimize_and_benchmark(N: in... | from solution import matrix_multiplication, optimize_and_benchmark
def test_matrix_multiplication():
N = 4
A = torch.tensor([[1.0, 2.0, 3.0, 4.0],
[5.0, 6.0, 7.0, 8.0],
[9.0, 10.0, 11.0, 12.0],
[13.0, 14.0, 15.0, 16.0]])
B = torch.tensor([[1... | [
{
"docstring": null,
"function_declaration": "def matrix_multiplication(A, B, C):",
"function_name": "matrix_multiplication",
"parameter_list": "(A, B, C)"
},
{
"docstring": null,
"function_declaration": "def optimize_and_benchmark(N):",
"function_name": "optimize_and_benchmark",
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport timeit\n\n@torch.jit.script\ndef matrix_multiplication(A: torch.Tensor, B: torch.Tensor, C: torch.Tensor) -> torch.Tensor:\n result = torch.mm(A... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00022150",
"row_id": 22150,
"seed_ids": "[169]"
} | 0.482337 | Docs: Pytorch_22150 | I | [
"matrix_multiplication",
"optimize_and_benchmark"
] | 2 | [
[
"optimize_and_benchmark",
"matrix_multiplication"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | b8a0a20cb5d0e70cfa8007602d437fb0fad2cd77 | 1c1ef0513071eaa35139eb803b41771668fa8578 | |||
v1.0 | instruct | Docs | Docs: Python310_22162_I | ### Python Asyncio Coding Assessment
#### Objective
Implement a command-line asynchronous task manager using asyncio. The manager should be able to:
1. Spawn a number of asynchronous tasks to complete a particular job.
2. Use an asyncio queue to distribute work among these tasks.
3. Handle task timeouts and cancellati... | import asyncio
from typing import List
import random
async def worker(task_id: int, queue: asyncio.Queue, result: List[str]):
while True:
try:
input_string = await queue.get()
await asyncio.sleep(random.randint(1, 5)) # Simulate processing time
result.append(f"Task {tas... | import asyncio
from solution import run_task_manager
async def test_run_task_manager_all_tasks_complete():
result = await run_task_manager(5, 10)
assert len(result) == 10
assert all("Task " in r and "completed: data_" in r for r in result)
async def test_run_task_manager_timeout():
result = await run_... | [] | [
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\nimport random\n\nasync def worker(task_id: int, queue: asyncio.Queue, result: List[str]):\n while True:\n try:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00022162",
"row_id": 22162,
"seed_ids": "[360]"
} | 0.656211 | Docs: Python310_22162 | I | [
"worker",
"run_task_manager"
] | 2 | [
[
"run_task_manager",
"worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c465ac6ac0787cca528e202543634b3807b043db | eee58efbe8e6f6152e60680d93141f8600accf07 | |||
v1.0 | instruct | Docs | Docs: Python310_22182_I | ### Objective
The task is to implement a Python program that utilizes both the `threading` and `multiprocessing` modules to perform concurrent execution of CPU-bound and I/O-bound tasks. This will assess your understanding of how to effectively use threads and processes for different types of tasks and how to synchroni... | import threading
import multiprocessing
import queue
from multiprocessing import Process, Queue
def is_prime(num):
""" Return True if num is a prime number. """
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i... | import pytest
import tempfile
import os
from solution import is_prime, cpu_bound_task, io_bound_task
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 not is_prime(0)
assert is_prime(23)
def test_cpu_bound_tas... | [
{
"docstring": "Return True if num is a prime number. ",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Calculate the sum of the first n prime numbers. ",
"function_declaration": "def cpu_bound_task(n, output_queue)... | [
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 threading\nimport multiprocessing\nfrom multiprocessing import Queue\nimport queue\n\n\ndef cpu_bound_task(n):\n \"\"\"\n Calculates the sum of the first n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022182",
"row_id": 22182,
"seed_ids": "[206]"
} | 0.535104 | Docs: Python310_22182 | I | [
"is_prime",
"cpu_bound_task",
"io_bound_task",
"main"
] | 4 | [
[
"cpu_bound_task",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 907323f93d4cfd59423e12bcbf12a4d70a7e454c | 9c11efd8ae0f848682c94f92d721ea5d3e7b075e | |||
v1.0 | instruct | Docs | Docs: Python310_22241_I | ### Asyncio Task Management
You have been asked to develop a Python program that performs multiple asynchronous tasks concurrently, handles task timeouts, and ensures that resources are cleaned up properly even if some tasks fail or are cancelled.
#### Requirements and Constraints:
1. **Function Implementation**: Im... | import asyncio
from typing import List, Tuple, Optional, Coroutine
async def task(name: str, duration: float) -> float:
"""
Simulate an asynchronous task that does some work for `duration` seconds.
"""
await asyncio.sleep(duration)
return duration
async def wait_task_with_timeout(task_coro: Corout... | import asyncio
import pytest
from solution import task, wait_task_with_timeout, perform_tasks_concurrently
@pytest.mark.asyncio
async def test_task():
assert await task('test_task', 1.0) == 1.0
@pytest.mark.asyncio
async def test_wait_task_with_timeout_success():
assert await wait_task_with_timeout(task('test... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple, Optional, Coroutine\n\nasync def task(name: str, duration: float) -> float:\n \"\"\"\n Simulates an asynchronous t... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022241",
"row_id": 22241,
"seed_ids": "[317]"
} | 0.657628 | Docs: Python310_22241 | I | [
"task",
"wait_task_with_timeout",
"perform_tasks_concurrently"
] | 3 | [
[
"perform_tasks_concurrently",
"task"
],
[
"perform_tasks_concurrently",
"wait_task_with_timeout"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3bb5642cfe069f40e27cdc70b414597c68a78c0c | 576b02efce7b6228fb2f4c35a56a6e17eff05953 | |||
v1.0 | instruct | Docs | Docs: Python310_22350_I | ### HMAC Authentication System
You are tasked to develop an HMAC-based session authentication system for a secure web application. This system will allow you to authenticate user sessions by verifying message integrity and authenticity using the HMAC algorithm.
#### Requirements
1. **Session Token Generation**:
-... | import hmac
import hashlib
def generate_token(user_id: str, secret_key: bytes, digestmod: str) -> str:
"""
Generate an HMAC session token for the given user ID.
Parameters:
- user_id (str): Unique identifier for the user.
- secret_key (bytes): Secret key used for HMAC.
- digestmod (str): H... | from solution import generate_token, verify_token
def test_generate_token():
user_id = "user123"
secret_key = b'supersecretkey'
digestmod = 'sha256'
token = generate_token(user_id, secret_key, digestmod)
assert isinstance(token, str)
assert len(token) == 64 # Length of sha256 hash in hexadecim... | [
{
"docstring": "Generate an HMAC session token for the given user ID.\n\nParameters:\n- user_id (str): Unique identifier for the user.\n- secret_key (bytes): Secret key used for HMAC.\n- digestmod (str): Hashing algorithm to use (e.g., 'sha256').\n\nReturns:\n- str: The generated HMAC session token in hexadecim... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hmac\nimport hashlib\n\ndef generate_token(user_id: str, secret_key: bytes, digestmod: str) -> str:\n \"\"\"\n Generate an HMAC session token for the given... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022350",
"row_id": 22350,
"seed_ids": "[298]"
} | 0.777027 | Docs: Python310_22350 | I | [
"generate_token",
"verify_token"
] | 2 | [
[
"verify_token",
"generate_token"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e8fc2847bc17477b40943e9481b2cab268882f37 | c69b83213cbd6bdf66c67fdfff6aaebd37651448 | |||
v1.0 | instruct | Docs | Docs: Python310_22356_I | ### Coding Assessment: Asynchronous Web Scraper
#### Objective:
Design and implement an asynchronous web scraper using Python's `asyncio` library. The scraper should be able to fetch and process multiple web pages concurrently while managing potential timeouts and cancellations effectively.
#### Problem Statement:
Yo... | import asyncio
import aiohttp
from bs4 import BeautifulSoup
async def fetch_page(session, url):
"""
Fetches the HTML content of a page given a URL using the provided aiohttp session.
"""
try:
async with session.get(url) as response:
if response.status == 200:
return ... | import asyncio
import pytest
from solution import scrape_pages
@pytest.mark.asyncio
async def test_scrape_pages_valid_urls():
urls = [
"https://www.example.com",
"https://www.python.org",
]
timeout = 10
results = await scrape_pages(urls, timeout)
assert "https://www.example.com... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport aiohttp\nfrom bs4 import BeautifulSoup\n\nasync def fetch_page(session, url, timeout):\n try:\n async with session.get(url, timeout=tim... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022356",
"row_id": 22356,
"seed_ids": "[317]"
} | 0.734104 | Docs: Python310_22356 | I | [
"fetch_page",
"process_page",
"scrape_page",
"scrape_pages"
] | 4 | [
[
"scrape_page",
"fetch_page"
],
[
"scrape_page",
"process_page"
],
[
"scrape_pages",
"scrape_page"
]
] | 3 | [] | false | [] | false | pytest | true | [
"aiohttp",
"bs4"
] | false | ed5fe24e41a854e781de1cdf47de261def8ef86a | 4470acef24727e5a1936727e509f477e2cff3486 | |||
v1.0 | instruct | Docs | Docs: Python310_22420_I | ### Custom Audit Hook Implementation
**Objective**: Implement a custom audit hook handler that monitors specific audit events and logs them to a specified log file.
**Description**:
Python's `sys.audit()` and `PySys_AddAuditHook()` functions allow the monitoring of various events raised during the execution of the Py... | import sys
import os
import shutil
import socket
from datetime import datetime
import threading
# Lock for thread-safe file operations
log_lock = threading.Lock()
def audit_event_handler(event, args):
events_to_monitor = ['os.system', 'socket.connect', 'shutil.copyfile']
if event in events_to_monitor:
... | import sys
import os
import shutil
import socket
import threading
from datetime import datetime
# Ensure the solution module is imported correctly
from solution import monitor_audit_events, audit_event_handler
def setup_module(module):
# Cleanup the previous log file if it exists
if os.path.exists('audit.log'... | [
{
"docstring": null,
"function_declaration": "def audit_event_handler(event, args):",
"function_name": "audit_event_handler",
"parameter_list": "(event, args)"
},
{
"docstring": null,
"function_declaration": "def monitor_audit_events():",
"function_name": "monitor_audit_events",
... | [
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 sys\nimport os\nimport shutil\nimport socket\nfrom datetime import datetime\nimport threading\n\nlog_file_lock = threading.Lock()\n\ndef audit_event_handler(even... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022420",
"row_id": 22420,
"seed_ids": "[167]"
} | 0.506074 | Docs: Python310_22420 | I | [
"audit_event_handler",
"monitor_audit_events"
] | 2 | [
[
"monitor_audit_events",
"audit_event_handler"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ec47d1c6c4c3a30ce03da425f0d07db2549a8b88 | 5b237632bd73e4bdfe1925b04970f72ce02f8616 | |||
v1.0 | instruct | Docs | Docs: Python310_22466_I | ### Advanced Python Coding Question: Coroutines
#### Objective
Design a coroutine-based function in Python that reads data from multiple asynchronous data sources concurrently and returns the aggregated results as a list. This problem will test your understanding of coroutines and their integration into asynchronous w... | import asyncio
import random
from typing import List, Any
async def fetch_data_source_1() -> Any:
# Simulate fetching data from source 1
await asyncio.sleep(random.uniform(0, 2))
return "data from source 1"
async def fetch_data_source_2() -> Any:
# Simulate fetching data from source 2
await asynci... | import pytest
import asyncio
from solution import aggregate_data
@pytest.mark.asyncio
async def test_aggregate_data():
result = await aggregate_data()
assert len(result) == 3
assert "data from source 1" in result
assert "data from source 2" in result
assert "data from source 3" in result
@pytest.m... | [] | [
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\nfrom typing import List, Any\n\nasync def fetch_data_source_1() -> Any:\n # Simulate fetching data from source 1\n await asyncio.sl... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00022466",
"row_id": 22466,
"seed_ids": "[8]"
} | 0.49227 | Docs: Python310_22466 | I | [
"fetch_data_source_1",
"fetch_data_source_2",
"fetch_data_source_3",
"aggregate_data"
] | 4 | [
[
"aggregate_data",
"fetch_data_source_1"
],
[
"aggregate_data",
"fetch_data_source_2"
],
[
"aggregate_data",
"fetch_data_source_3"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 111e828ebd61e35cdc9e374a6f5bdd720802584e | 95773d743d32d9886af0d86166d865d5245d2bf5 | |||
v1.0 | instruct | Docs | Docs: Python310_22552_I | ### Question: Cross-Platform AsyncIO Event Loop Management
The `asyncio` module in Python provides a framework for writing applications that incorporate asynchronous I/O operations. However, the functionality and support for different methods in `asyncio` can vary significantly across different operating systems such ... | import asyncio
import platform
async def handle_echo(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message} from {addr}")
print(f"Send: {message}")
writer.write(data)
await writer.drain()
print("C... | import asyncio
import socket
import pytest
from solution import run_echo_server
@pytest.fixture
async def start_server():
server_host = '127.0.0.1'
server_port = 8888
server_task = asyncio.create_task(run_echo_server(server_host, server_port))
# Give a moment to ensure the server starts
await... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport platform\n\nasync def handle_echo(reader, writer):\n data = await reader.read(100)\n message = data.decode()\n addr = writer.get_extra_i... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00022552",
"row_id": 22552,
"seed_ids": "[370]"
} | 0.55916 | Docs: Python310_22552 | I | [
"handle_echo",
"run_echo_server"
] | 2 | [
[
"run_echo_server",
"handle_echo"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1bfa8849c65fcf1f840e382147e227cffa6f9016 | 0f3601099193fcc4306fbfe8995061075b864cb7 | |||
v1.0 | instruct | Docs | Docs: Python310_22570_I | ### Part 1: Concurrent Execution with Threading and Multiprocessing
**Objective:** Implement a program demonstrating both thread-based and process-based parallelism to count prime numbers in a given range.
#### Task
Write a Python program that does the following:
1. **Define a function `is_prime(n: int) -> bool`** th... | import threading
import multiprocessing
import math
def is_prime(n: int) -> bool:
"""
Returns True if n is a prime number, otherwise False.
"""
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:
... | from solution import is_prime, count_primes_in_range, count_primes_with_threads, count_primes_with_processes
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(1) == False
assert is_prime(0) == False
... | [
{
"docstring": "Returns True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the count of prime numbers in the given range [start, end).",
"function_declaration": "def c... | [
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 threading\nimport multiprocessing\nfrom math import isqrt\nfrom time import time \n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Check if a number is a prime ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022570",
"row_id": 22570,
"seed_ids": "[206]"
} | 0.580904 | Docs: Python310_22570 | I | [
"is_prime",
"count_primes_in_range",
"count_primes_with_threads",
"count_primes_with_processes"
] | 4 | [
[
"count_primes_in_range",
"is_prime"
],
[
"count_primes_with_processes",
"count_primes_in_range"
],
[
"count_primes_with_threads",
"count_primes_in_range"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 4cda0c6f61110831f14b99675e861ea427095bdb | fa047dfb6ef42fe64705e4d65c7ab55a25090112 | |||
v1.0 | instruct | Docs | Docs: Seaborn_22578_I | ### Question
You are a data analyst working on visualizing data for a marketing team. They have specifically requested that all visualizations contain color schemes with specific characteristics for brand consistency. You have decided to use the `seaborn` library to create these color palettes. Given the following task... | import seaborn as sns
import matplotlib.pyplot as plt
def create_light_palette(color, n_colors=6):
"""
Generate a light color palette from light gray to the specified color.
Args:
- color (str or tuple): The target color as a named color, hex code, or HUSL coordinates.
- n_colors (int): Number... | from solution import create_light_palette, create_continuous_cmap, test_palette_inputs
def test_create_light_palette_named_color():
palette = create_light_palette("seagreen", 8)
assert len(palette) == 8
assert isinstance(palette[0], tuple)
def test_create_light_palette_hex_color():
palette = create_li... | [
{
"docstring": "Generate a light color palette from light gray to the specified color.\n\nArgs:\n- color (str or tuple): The target color as a named color, hex code, or HUSL coordinates.\n- n_colors (int): Number of colors in the palette (default is 6).\n\nReturns:\n- palette (list): List of colors in the gener... | [
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\nimport numpy as np\n\ndef create_light_palette(color, n_colors=6):\n \"\"\"\n Generate a light color palet... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00022578",
"row_id": 22578,
"seed_ids": "[44]"
} | 0.631315 | Docs: Seaborn_22578 | I | [
"create_light_palette",
"create_continuous_cmap",
"test_palette_inputs"
] | 3 | [
[
"test_palette_inputs",
"create_light_palette"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"seaborn"
] | false | 7e8acf1b0290d774bd11b1e0d8b83ac878b70ab8 | 185df6a3c5a07906d0057c8f3d16b7318b4d4705 | |||
v1.0 | instruct | Docs | Docs: Python310_22617_I | #### Problem Statement
You have been tasked with implementing a context-aware logging system that uses the `contextvars` package to manage context-local state.
You need to implement the following functions:
1. `log_message`:
- **Input**: A string `message`.
- **Output**: None.
- **Description**: Logs the me... | import contextvars
import asyncio
# Define a ContextVar to hold the context identifier
context_id_var = contextvars.ContextVar('context_id', default='default')
def log_message(message):
"""
Logs the message along with the current context identifier.
If no context identifier is set, it uses 'default'.
... | from solution import log_message, set_context_identifier, get_context_identifier, reset_context_identifier, async_log_simulation
import asyncio
def test_log_message(capfd):
log_message("Hello, World!")
captured = capfd.readouterr()
assert captured.out.strip() == "Context[default]: Hello, World!"
def test_... | [
{
"docstring": "Logs the message along with the current context identifier.\nIf no context identifier is set, it uses 'default'.",
"function_declaration": "def log_message(message):",
"function_name": "log_message",
"parameter_list": "(message)"
},
{
"docstring": "Sets the context identifier... | [
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 contextvars\nimport asyncio\n\n# Define a ContextVar to hold the context identifier\ncontext_id_var = contextvars.ContextVar('context_id', default='default')\n\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00022617",
"row_id": 22617,
"seed_ids": "[392]"
} | 0.435483 | Docs: Python310_22617 | I | [
"log_message",
"set_context_identifier",
"get_context_identifier",
"reset_context_identifier",
"async_log_simulation",
"log_with_context"
] | 6 | [
[
"async_log_simulation",
"log_with_context"
],
[
"log_with_context",
"log_message"
],
[
"log_with_context",
"set_context_identifier"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 82b461a8ee1d13f0915c069e3d4c5709bd517c59 | b6c5a97b2cc795e03a9d528fa73ef77c2f22b111 | |||
v1.0 | instruct | Docs | Docs: Pytorch_22636_I | **Objective:** Implement a utility function to manage MPS-related PyTorch environment variables and demonstrate its effect on a PyTorch computation using the MPS backend.
#### Background
PyTorch supports running models on Apple devices using Metal Performance Shaders (MPS). Various environment variables can be set to... | import os
def set_mps_environment_variable(env_vars):
"""
Sets environment variables for the MPS backend in PyTorch.
Args:
env_vars (dict): Dictionary where keys are environment variable names
and values are the corresponding settings.
Returns:
None
"""
f... | import os
import pytest
from solution import set_mps_environment_variable
def test_set_mps_environment_variable():
test_env_vars = {
"PYTORCH_MPS_FAST_MATH": "1",
"PYTORCH_MPS_DEBUG": "2"
}
# Setting the environment variables
set_mps_environment_variable(test_env_vars)
# A... | [
{
"docstring": "Sets environment variables for the MPS backend in PyTorch.\n\nArgs:\nenv_vars (dict): Dictionary where keys are environment variable names \n and values are the corresponding settings.\n\nReturns:\nNone",
"function_declaration": "def set_mps_environment_variable(env_vars):",
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport torch\nimport time\n\ndef set_mps_environment_variable(env_vars):\n \"\"\"\n Sets the given environment variables for the PyTorch MPS backend.\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00022636",
"row_id": 22636,
"seed_ids": "[64]"
} | 0.428246 | Docs: Pytorch_22636 | I | [
"set_mps_environment_variable",
"mps_matrix_multiplication_demo"
] | 2 | [
[
"mps_matrix_multiplication_demo",
"set_mps_environment_variable"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | e39b25af2a67dbe616b14ce607445f258940ffaf | c75ea917a58895315d4647ed1cf975ce54c3de7e | |||
v1.0 | instruct | Docs | Docs: Python310_22661_I | ### Question: Implement an Asynchronous Echo Server and Client
**Objective:**
Create an asynchronous echo server and client using Python's asyncio streams. The server should be able to handle multiple clients concurrently, receive messages from them, and echo the messages back to the respective clients. The client sho... | import asyncio
async def handle_client(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} from {addr!r}")
print(f"Send: {message!r}")
writer.write(data)
await writer.drain()
print("C... | import asyncio
import pytest
import subprocess
import time
from solution import start_server, tcp_client
@pytest.fixture
def run_event_loop():
loop = asyncio.get_event_loop()
yield loop
loop.close()
@pytest.fixture
def server_process():
# Start the server process
process = subprocess.Popen(['pyth... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n data = await reader.read(100)\n message = data.decode()\n addr = writer.get_extra_info('peername')... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00022661",
"row_id": 22661,
"seed_ids": "[182]"
} | 0.675437 | Docs: Python310_22661 | I | [
"handle_client",
"start_server",
"tcp_client"
] | 3 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 414213ea5412e3c9d026548e714b9e07f998e1c4 | fba7371f989623e5dabbb8c24dc325a46e1768fc | |||
v1.0 | instruct | Docs | Docs: Python310_22674_I | **Question**: Implement and manage an asynchronous operation using `asyncio.Future`
**Objective**:
You are required to implement an asynchronous function that performs a sequence of operations using `asyncio.Future`. This will test your understanding of futures, awaiting results, and scheduling tasks.
**Problem**:
A ... | import asyncio
async def delayed_addition(fut: asyncio.Future, delay: int, a: int, b: int) -> None:
"""
Waits for `delay` seconds and sets the result of `fut` to be the sum of `a` and `b`.
"""
await asyncio.sleep(delay)
fut.set_result(a + b)
async def delayed_multiplication(fut: asyncio.Future, de... | import asyncio
import pytest
from solution import delayed_addition, delayed_multiplication, async_pipeline
@pytest.mark.asyncio
async def test_delayed_addition():
fut = asyncio.Future()
await delayed_addition(fut, 1, 2, 3)
assert fut.result() == 5
@pytest.mark.asyncio
async def test_delayed_multiplication... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def delayed_addition(fut: asyncio.Future, delay: int, a: int, b: int) -> None:\n \"\"\"\n Waits for `delay` seconds and sets the result of... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00022674",
"row_id": 22674,
"seed_ids": "[113]"
} | 0.524862 | Docs: Python310_22674 | I | [
"delayed_addition",
"delayed_multiplication",
"async_pipeline"
] | 3 | [
[
"async_pipeline",
"delayed_addition"
],
[
"async_pipeline",
"delayed_multiplication"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 522c38285f1d4a63e59ec84bb819d6224d783dbd | 9c02b4930afb1809fab15aedde3a1c47281f26c5 | |||
v1.0 | instruct | Docs | Docs: Python310_22690_I | **Python Coding Assessment: Custom Configuration Loader**
### Objective:
Create a custom configuration loader for a Python application by leveraging the functionalities of `warnings`, `dataclasses`, and `contextlib`. This loader should provide the ability to define configuration data structures using data classes, man... | import warnings
import json
from dataclasses import dataclass
from contextlib import contextmanager
@dataclass
class AppConfig:
host: str
port: int
use_ssl: bool
timeout: int # Deprecated field
def check_deprecations(config: AppConfig):
if hasattr(config, 'timeout'):
warnings.warn("The 't... | import pytest
import warnings
import os
import json
from contextlib import contextmanager
from solution import AppConfig, check_deprecations, configuration_loader
def test_app_config_initialization():
config = AppConfig(host="localhost", port=8080, use_ssl=True, timeout=30)
assert config.host == "localhost"
... | [] | [
0,
0,
0,
1,
0,
0,
1,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import warnings\nimport json\nfrom dataclasses import dataclass\nfrom contextlib import contextmanager\n\n# Step 1: Define the configuration data class\n@dataclass\ncla... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00022690",
"row_id": 22690,
"seed_ids": "[146]"
} | 0.547568 | Docs: Python310_22690 | I | [
"check_deprecations",
"configuration_loader"
] | 2 | [
[
"configuration_loader",
"check_deprecations"
]
] | 1 | [] | false | [
"AppConfig"
] | true | pytest | true | [] | true | 9b9ccf45982e372d5fd68cb3563689f7c38b24e7 | 5547ad12fd75f204917cf20f98b68ec6325e092b | |||
v1.0 | instruct | Docs | Docs: Python310_22741_I | ### UUID Generation and Validation
#### Problem Statement
You are tasked with creating a utility function that generates and validates various UUIDs using Python's `uuid` module. Specifically, you need to implement a function that:
1. Generates a UUID of each specified version (1, 3, 4, 5).
2. Validates whether a gi... | import uuid
def generate_uuids() -> dict:
"""
Generates and returns a dictionary with UUIDs of versions 1, 3, 4, and 5.
"""
return {
1: uuid.uuid1(),
3: uuid.uuid3(uuid.NAMESPACE_DNS, 'example.com'),
4: uuid.uuid4(),
5: uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com')
}... | from solution import generate_uuids, is_valid_uuid, parse_uuid
import uuid
def test_generate_uuids():
uuids = generate_uuids()
assert isinstance(uuids, dict)
assert len(uuids) == 4
assert 1 in uuids and uuids[1].version == 1
assert 3 in uuids and uuids[3].version == 3
assert 4 in uuids and uuid... | [
{
"docstring": "Generates and returns a dictionary with UUIDs of versions 1, 3, 4, and 5.",
"function_declaration": "def generate_uuids():",
"function_name": "generate_uuids",
"parameter_list": "()"
},
{
"docstring": "Takes a string and returns True if the string is a valid UUID, otherwise r... | [
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_uuids() -> dict:\n \"\"\"\n Generates and returns a dictionary with UUIDs of versions 1, 3, 4, and 5.\n For versions 3 and 5, use t... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022741",
"row_id": 22741,
"seed_ids": "[295]"
} | 0.538678 | Docs: Python310_22741 | I | [
"generate_uuids",
"is_valid_uuid",
"parse_uuid"
] | 3 | [
[
"parse_uuid",
"is_valid_uuid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5f24e2c61e9bd90100cebc1f88e1b97e0a8ec98e | a4e6eb393729f2045775828956b3876b954d7eac | |||
v1.0 | instruct | Docs | Docs: Python310_22765_I | #### Objective
Implement a function that takes a list of IP addresses and a subnet mask, then returns a new list categorizing the IP addresses into 'private' or 'public' based on the subnet mask.
#### Description
Write a function `categorize_ip_addresses(ip_addresses: List[str], subnet_mask: str) -> Dict[str, List[str... | from typing import List, Dict
import ipaddress
def is_private_ip(ip: str) -> bool:
"""
Determine if the given IP address is private.
"""
ip_addr = ipaddress.ip_address(ip)
return ip_addr.is_private
def categorize_ip_addresses(ip_addresses: List[str], subnet_mask: str) -> Dict[str, List[str]]:
... | from solution import categorize_ip_addresses
def test_basic_categorization():
ip_addresses = [
"192.168.1.10", "192.168.1.20", "10.0.0.1",
"8.8.8.8", "2001:db8::1", "fc00::1"
]
subnet_mask = "192.168.1.0/24"
result = categorize_ip_addresses(ip_addresses, subnet_mask)
assert result =... | [
{
"docstring": "Determine if the given IP address is private.",
"function_declaration": "def is_private_ip(ip):",
"function_name": "is_private_ip",
"parameter_list": "(ip)"
},
{
"docstring": "Categorize IP addresses into 'private' or 'public' based on the subnet mask.",
"function_declara... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict\nimport ipaddress\n\ndef categorize_ip_addresses(ip_addresses: List[str], subnet_mask: str) -> Dict[str, List[str]]:\n categorized_ips ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022765",
"row_id": 22765,
"seed_ids": "[408]"
} | 0.632725 | Docs: Python310_22765 | I | [
"is_private_ip",
"categorize_ip_addresses"
] | 2 | [
[
"categorize_ip_addresses",
"is_private_ip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6d7a7264ab3430bbf3f8289dd881f270743ad959 | 95c9f1b1f1a330a64b31110894fe7e3b0fe4385a | |||
v1.0 | instruct | Docs | Docs: Python310_22768_I | ### Asyncio Streams: Create a Key-Value Store
Create an asynchronous TCP server and client using the `asyncio` streams module in Python. The server will act as a simple in-memory key-value store that supports basic commands (SET, GET, DELETE). The client will communicate with the server to perform these commands.
**R... | import asyncio
# In-memory key-value store
kv_store = {}
async def handle_client(reader, writer):
while True:
data = await reader.read(100)
if not data:
break
message = data.decode().strip()
response = process_command(message)
writer.write(response.encode())
... | import pytest
import asyncio
from asyncio import StreamReader, StreamWriter
async def mock_client(server, command):
reader, writer = await asyncio.open_connection('127.0.0.1', 9999)
writer.write(command.encode())
await writer.drain()
data = await reader.read(100)
writer.close()
await writer.wai... | [
{
"docstring": null,
"function_declaration": "def process_command(command):",
"function_name": "process_command",
"parameter_list": "(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": "# server.py\n\nimport asyncio\n\nclass KeyValueStore:\n def __init__(self):\n self.store = {}\n\n def process_command(self, command):\n parts = comm... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022768",
"row_id": 22768,
"seed_ids": "[182]"
} | 0.549808 | Docs: Python310_22768 | I | [
"handle_client",
"process_command",
"main"
] | 3 | [
[
"handle_client",
"process_command"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 97e17592b26506297bf03e897be9061a185f9236 | 141ca10f75c7ccb0ae2f03b829832613d7b2a14a | |||
v1.0 | instruct | Docs | Docs: Python310_22780_I | ### Warning Management and Custom Filters
In this exercise, you will demonstrate your understanding of Python's warnings module. Your task is to create a custom warning, issue that warning appropriately in a function, and manipulate how this warning is handled by using warning filters. Specifically, you will perform t... | import warnings
class MyCustomWarning(Warning):
pass
def sensitive_operation():
warnings.warn("This is a custom warning", MyCustomWarning)
def manage_warnings():
with warnings.catch_warnings(record=True) as w:
# Ignore MyCustomWarning
warnings.filterwarnings("ignore", category=MyCustomWar... | import warnings
from solution import MyCustomWarning, sensitive_operation, manage_warnings
def test_sensitive_operation_warning_issued():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("ignore", category=RuntimeWarning) # Ignore other warnings to focus on custom warning
sens... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import warnings\n\nclass MyCustomWarning(Warning):\n pass\n\ndef sensitive_operation():\n warnings.warn(\"This is a custom warning\", MyCustomWarning)\n\ndef mana... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00022780",
"row_id": 22780,
"seed_ids": "[125]"
} | 0.531539 | Docs: Python310_22780 | I | [
"sensitive_operation",
"manage_warnings"
] | 2 | [
[
"manage_warnings",
"sensitive_operation"
]
] | 1 | [] | false | [
"MyCustomWarning"
] | true | pytest | true | [] | true | 843dc2883df0fd0a31c2f2c1e530db1416999fb5 | 2f43dce568763f45ceabe9d938060de2b1a7f746 | |||
v1.0 | instruct | Docs | Docs: Python310_22848_I | #### Objective
Design and implement an asynchronous network echo server using asyncio's event loop that handles multiple simultaneous client connections.
#### Description
You are required to implement an echo server that listens on a specified host and port, handles multiple concurrent client connections, and echoes b... | import asyncio
async def handle_client(reader, writer):
try:
while True:
data = await reader.read(100)
if not data:
break
writer.write(data)
await writer.drain()
except Exception as e:
print(f'Error: {e}')
finally:
writ... | import asyncio
import pytest
@pytest.fixture(scope="module")
def event_loop():
loop = asyncio.get_event_loop()
yield loop
loop.close()
@pytest.mark.asyncio
async def test_echo_server(event_loop):
host = 'localhost'
port = 8889
server_task = event_loop.create_task(start_echo_server(host, port)... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n try:\n while True:\n data = await reader.read(100)\n if not data:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022848",
"row_id": 22848,
"seed_ids": "[267]"
} | 0.64545 | Docs: Python310_22848 | I | [
"handle_client",
"start_echo_server"
] | 2 | [
[
"start_echo_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 63c75942d1b2bb78f331238a935e41b329fd1f37 | 40fbe34161d5c847e9f8c667d2388bcbe3a57f96 | |||
v1.0 | instruct | Docs | Docs: Python310_22965_I | **Coding Question: Data Compression and Archiving**
### Objective:
Implement a Python function that can compress a given set of files using multiple compression algorithms and then archive all compressed files into a single ZIP file.
### Function Signature:
```python
def compress_and_archive(files: list[str], archive... | import gzip
import bz2
import lzma
import os
import shutil
from zipfile import ZipFile
def compress_file(file_path: str, algorithm: str) -> str:
"""
Compress a file using the specified algorithm and return the path to the compressed file.
"""
extension = {
'gzip': '.gz',
'bz2': '.bz2',
... | import os
import pytest
from zipfile import ZipFile
from solution import compress_and_archive
TEST_FILE_CONTENT = "This is a test file content."
@pytest.fixture
def setup_files(tmp_path):
file1 = tmp_path / "file1.txt"
file2 = tmp_path / "file2.txt"
file1.write_text(TEST_FILE_CONTENT)
file2.write_text... | [
{
"docstring": "Compress a file using the specified algorithm and return the path to the compressed file.",
"function_declaration": "def compress_file(file_path, algorithm):",
"function_name": "compress_file",
"parameter_list": "(file_path, algorithm)"
},
{
"docstring": null,
"function_d... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import gzip\nimport bz2\nimport lzma\nimport os\nimport shutil\nfrom zipfile import ZipFile\n\ndef compress_file(file_path: str, algorithm: str) -> str:\n \"\"\"\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00022965",
"row_id": 22965,
"seed_ids": "[310]"
} | 0.730884 | Docs: Python310_22965 | I | [
"compress_file",
"compress_and_archive"
] | 2 | [
[
"compress_and_archive",
"compress_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 11f4b97cb38a654e77927d7f7ca82b348f0977e6 | 06e168fc67041007e167d1ad24db202de8528b01 | |||
v1.0 | instruct | Docs | Docs: Pytorch_23046_I | ### PyTorch Custom Operator Implementation and Testing
In this problem, you are required to implement a custom PyTorch operator and test its functionality, including gradient checking. We'll guide you through the steps to ensure that your implementation covers the required aspects.
#### Steps:
1. **Define a New Cust... | import torch
from torch import autograd
# Step 1: Define the custom operator
def custom_square(tensor):
return tensor * tensor
# Step 2: Register the custom operator
def register_custom_op():
my_lib = torch.library.Library("my_custom_lib", "DEF")
# Register our custom_square operator
my_lib.define("cu... | from solution import custom_square, register_custom_op, test_custom_op
import pytest
import torch
from torch import autograd
def test_custom_square_values():
# Test custom_square on a known tensor
tensor = torch.tensor([1.0, 2.0, -3.0], requires_grad=True)
result = custom_square(tensor)
expected_result... | [
{
"docstring": null,
"function_declaration": "def custom_square(tensor):",
"function_name": "custom_square",
"parameter_list": "(tensor)"
},
{
"docstring": null,
"function_declaration": "def register_custom_op():",
"function_name": "register_custom_op",
"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 torch\nfrom torch import autograd\n\n# Step 1: Define the custom operator\ndef custom_square(tensor):\n return tensor * tensor\n\n# Step 2: Register the custo... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023046",
"row_id": 23046,
"seed_ids": "[51]"
} | 0.464683 | Docs: Pytorch_23046 | I | [
"custom_square",
"register_custom_op",
"test_custom_op"
] | 3 | [
[
"register_custom_op",
"custom_square"
],
[
"test_custom_op",
"custom_square"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 09ade2147640a3b47a289d0ddc466970d5b6b59b | 5c5e67341b6d03f70ad1a8580f469e6f21815e4f | |||
v1.0 | instruct | Docs | Docs: Python310_23134_I | #### **File System and Process Management in Python**
**Objective**: Implement a Python script that performs the following tasks leveraging the `os` module.
1. **File Creation and Writing**:
- Create a new directory named `test_dir`.
- Inside `test_dir`, create a file named `ProcessInfo.txt`.
- Write info... | import os
import sys
def create_directory(directory_name):
try:
os.mkdir(directory_name)
except FileExistsError:
pass
def write_process_info(file_path):
with open(file_path, 'w') as file:
pid = os.getpid()
ppid = os.getppid()
env_vars = os.environ
file.writ... | import os
import pytest
from solution import main, create_directory, write_process_info, append_new_var_to_file, child_process
def test_create_directory():
dir_name = "test_dir"
create_directory(dir_name)
assert os.path.isdir(dir_name) == True
os.rmdir(dir_name)
def test_write_process_info(tmp_pat... | [
{
"docstring": null,
"function_declaration": "def create_directory(directory_name):",
"function_name": "create_directory",
"parameter_list": "(directory_name)"
},
{
"docstring": null,
"function_declaration": "def write_process_info(file_path):",
"function_name": "write_process_info",... | [
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 sys\n\ndef create_directory(directory_name):\n if not os.path.exists(directory_name):\n os.mkdir(directory_name)\n\ndef write_process_info(f... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023134",
"row_id": 23134,
"seed_ids": "[106]"
} | 0.63413 | Docs: Python310_23134 | I | [
"create_directory",
"write_process_info",
"append_new_var_to_file",
"child_process",
"main"
] | 5 | [
[
"child_process",
"append_new_var_to_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d4e6240fbddc6b05af1d89fc88644ec95ee4c66f | efe3d5956722d2209fb7d4250274c2f5aa9ceca2 | |||
v1.0 | instruct | Docs | Docs: Python310_23156_I | ### Advanced Coding Assessment: Custom Iterator and Generator
#### Objective:
Design and implement custom iterators and generators using Python's functional programming features.
#### Task:
You are provided with a list of tuples where each tuple represents a range (inclusive).
For example:
```python
ranges = [(1, 4)... | import itertools
from typing import List, Tuple, Iterator
class RangeIterator:
def __init__(self, ranges: List[Tuple[int, int]]):
self.ranges = ranges
self.current_range = None
self.current = None
self.index = 0
self._prepare_next_range()
def _prepare_next_range... | from solution import RangeIterator, even_numbers, combine_even_numbers
def test_RangeIterator_normal_case():
ranges = [(1, 4), (10, 13)]
iterator = RangeIterator(ranges)
output = list(iterator)
assert output == [1, 2, 3, 4, 10, 11, 12, 13]
def test_RangeIterator_single_range():
ranges = [(5, 7)]
... | [] | [
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 itertools\nfrom typing import List, Tuple, Iterator\n\nclass RangeIterator:\n def __init__(self, ranges: List[Tuple[int, int]]):\n self.ranges = ranges... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023156",
"row_id": 23156,
"seed_ids": "[78]"
} | 0.62791 | Docs: Python310_23156 | I | [
"even_numbers",
"combine_even_numbers"
] | 2 | [
[
"combine_even_numbers",
"even_numbers"
]
] | 1 | [] | false | [
"RangeIterator"
] | true | pytest | true | [] | true | 0094a09bb6c999aec2a226affd2b64f19d8070e3 | d15a990ae48388eed313c2d33f0ae7d2e2671f0d | |||
v1.0 | instruct | Docs | Docs: Python310_23227_I | Create a function `safe_file_operation` that safely performs reading from or writing to a file based on given parameters, ensuring that the file is properly closed after the operation, even if an error occurs. To implement this function, you must utilize the `contextlib` module's `contextmanager` decorator.
### Requir... | import contextlib
@contextlib.contextmanager
def open_file(file_path, mode):
"""
Context manager to safely open and close a file.
Args:
- file_path: Path to the file.
- mode: Mode in which to open the file.
Yields:
- file object
"""
file = None
try:
file = open... | import os
import pytest
from solution import safe_file_operation
def test_safe_file_operation_write(tmpdir):
test_file = os.path.join(tmpdir, "test.txt")
content = "Hello, world!"
result = safe_file_operation(test_file, "write", content)
assert result == f"Content written to {test_file}"
... | [
{
"docstring": "Context manager to safely open and close a file.\n\nArgs:\n- file_path: Path to the file.\n- mode: Mode in which to open the file.\n\nYields:\n- file object",
"function_declaration": "def open_file(file_path, mode):",
"function_name": "open_file",
"parameter_list": "(file_path, mode)... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from contextlib import contextmanager\n\n@contextmanager\ndef open_file_safe(file_path, mode):\n file = None\n try:\n file = open(file_path, mode)\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023227",
"row_id": 23227,
"seed_ids": "[177]"
} | 0.501585 | Docs: Python310_23227 | I | [
"open_file",
"safe_file_operation"
] | 2 | [
[
"safe_file_operation",
"open_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e65b6f2ccfa012ceb5a9ff4cbf98bf1e2d63ad2c | c1103daba2b7e9a0388f9dd28b65e1a4d2cfce24 | |||
v1.0 | instruct | Docs | Docs: Python310_23279_I | ### Advanced Python Tracing with SystemTap
#### Objective
Create a Python script that can be monitored using SystemTap. You will utilize the pre-defined static markers available in CPython to trace function calls and garbage collection cycles in your script.
#### Task
1. Write a Python script based on the following r... | import gc
def function_1():
function_2()
function_3()
def function_2():
result = 1 + 1
print(f"function_2 result: {result}")
def function_3():
try:
raise ValueError("An error occurred in function_3")
except ValueError as e:
print(e)
if __name__ == "__main__":
function_1()... | from solution import function_1, function_2, function_3
def test_function_1_calls_functions():
try:
function_1()
assert True # If no exception, test passes
except Exception:
assert False # If an exception occurs, test fails
def test_function_2_arithmetic_operation():
result = fun... | [
{
"docstring": null,
"function_declaration": "def function_1():",
"function_name": "function_1",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def function_2():",
"function_name": "function_2",
"parameter_list": "()"
},
{
"docstring": null,
"... | [
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 gc\n\ndef function_1():\n function_2()\n function_3()\n\ndef function_2():\n result = 42 / 2 # Perform a basic arithmetic operation\n print(f\"The r... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023279",
"row_id": 23279,
"seed_ids": "[79]"
} | 0.561631 | Docs: Python310_23279 | I | [
"function_1",
"function_2",
"function_3"
] | 3 | [
[
"function_1",
"function_2"
],
[
"function_1",
"function_3"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2b56efe6d133789e7f83440aa6118e25b70abc46 | 20d16785fdedff583156c752b45c2660ea862104 | |||
v1.0 | instruct | Docs | Docs: Python310_23373_I | ### Advanced Python Multiprocessing Task
#### **Objective:**
To assess the understanding of Python's `multiprocessing` package, including advanced concepts like process synchronization, inter-process communication, and use of shared memory.
#### **Problem Statement:**
You are required to build a multiprocessing-based... | import multiprocessing
import time
from typing import List
def compute_task(x: int) -> int:
"""
Computes the square of x after a delay of 1 second.
"""
time.sleep(1)
return x ** 2
def logger_task(queue: multiprocessing.Queue, log_lock: multiprocessing.Lock):
"""
Logs the results from the q... | import multiprocessing
import time
from solution import compute_task, logger_task, worker, create_workers, main
def test_compute_task():
assert compute_task(2) == 4
assert compute_task(3) == 9
def test_logger_task(capfd):
queue = multiprocessing.Queue()
log_lock = multiprocessing.Lock()
process = ... | [
{
"docstring": "Computes the square of x after a delay of 1 second.",
"function_declaration": "def compute_task(x):",
"function_name": "compute_task",
"parameter_list": "(x)"
},
{
"docstring": "Logs the results from the queue. Uses lock to synchronize access.",
"function_declaration": "d... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import multiprocessing\nimport time\nfrom typing import List\n\ndef compute_task(x: int) -> int:\n \"\"\"\n Computes the square of x after a delay of 1 second.\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023373",
"row_id": 23373,
"seed_ids": "[338]"
} | 0.639385 | Docs: Python310_23373 | I | [
"compute_task",
"logger_task",
"worker",
"create_workers",
"main"
] | 5 | [
[
"worker",
"compute_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bda8970469c89b116c34086125808275bc62a9f9 | 57f57b2124139aa42698147da43f2bbebdeef706 | |||
v1.0 | instruct | Docs | Docs: Python310_23392_I | ### Advanced File Management and Processing Task
You are tasked with developing a Python script that manages a file processing system. The script will read a list of filenames from the command line, check the creation dates of these files and generate a report that categorizes the files into different age groups. The ... | import os
import sys
import argparse
from datetime import datetime, timedelta
def get_file_creation_date(file_path):
"""
Returns the creation date of the file in datetime format.
"""
return datetime.fromtimestamp(os.path.getctime(file_path))
def categorize_files(files, days):
"""
Categorizes t... | import pytest
from datetime import datetime, timedelta
from solution import get_file_creation_date, categorize_files
# Mocking os.path.getctime to simulate file creation dates
def mock_getctime(file_path):
creation_dates = {
"file1.txt": (datetime.now() - timedelta(days=90)).timestamp(),
"file2.txt... | [
{
"docstring": "Returns the creation date of the file in datetime format.",
"function_declaration": "def get_file_creation_date(file_path):",
"function_name": "get_file_creation_date",
"parameter_list": "(file_path)"
},
{
"docstring": "Categorizes the given list of files based on their creat... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport argparse\nfrom datetime import datetime, timedelta\n\ndef categorize_files(filenames, days):\n \"\"\"\n Categorize files based on their creation... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023392",
"row_id": 23392,
"seed_ids": "[422]"
} | 0.618753 | Docs: Python310_23392 | I | [
"get_file_creation_date",
"categorize_files",
"generate_report"
] | 3 | [
[
"categorize_files",
"get_file_creation_date"
],
[
"generate_report",
"categorize_files"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 933434cf7e47d336eb38acc26cd44334ac2b439d | f7f9c1cad793404d902d2fe5b122aa1daa5404cd | |||
v1.0 | instruct | Docs | Docs: Python310_23397_I | #### Objective:
Your task is to create a Python program that demonstrates the ability to serialize complex data structures, store them persistently in a database, and retrieve and deserialize them efficiently.
#### Problem Statement:
You are required to implement a library management system where book records need to ... | import pickle
import sqlite3
from typing import List
# Define the Book class with necessary attributes
class Book:
def __init__(self, title: str, author: str, isbn: str, year: int, genre: str):
self.title = title
self.author = author
self.isbn = isbn
self.year = year
self.ge... | from solution import Book, serialize_book, deserialize_book, store_book, retrieve_books
def test_book_serialization():
book = Book(title="Test Book", author="John Doe", isbn="1234567890", year=2023, genre="Test")
serialized = serialize_book(book)
deserialized = deserialize_book(serialized)
assert ... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sqlite3\nimport pickle\nfrom typing import List\n\nclass Book:\n def __init__(self, title: str, author: str, isbn: str, year: int, genre: str):\n self.... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023397",
"row_id": 23397,
"seed_ids": "[140]"
} | 0.4753 | Docs: Python310_23397 | I | [
"serialize_book",
"deserialize_book",
"store_book",
"retrieve_books"
] | 4 | [
[
"retrieve_books",
"deserialize_book"
],
[
"store_book",
"serialize_book"
]
] | 2 | [] | false | [
"Book"
] | true | pytest | true | [] | true | e706db7851cd4900145dfc9425849fdee41be313 | d1877ada2d00f3cca171546748939cb0104111de | |||
v1.0 | instruct | Docs | Docs: Python310_23425_I | As a file operations specialist, you need to process several file descriptors provided to you. Your task is to create a Python module encapsulating the following functionality:
1. **Read from a File Descriptor**:
- Implement a function `read_from_fd(fd: int, n: int) -> str` that reads up to `n` characters (or byte... | import os
def read_from_fd(fd: int, n: int) -> str:
try:
if n == 0:
return ""
elif n == -1:
return os.read(fd, os.fstat(fd).st_size).decode()
else:
return os.read(fd, n).decode()
except Exception as e:
raise IOError(f"Error reading from file d... | import os
import tempfile
import pytest
from solution import read_from_fd, write_to_fd, dup_fd, close_fd, process_file
def test_read_from_fd():
temp_file = tempfile.TemporaryFile()
fd = temp_file.fileno()
os.write(fd, b"Hello, World!")
os.lseek(fd, 0, os.SEEK_SET)
assert read_from_fd(fd, 5) == "He... | [
{
"docstring": null,
"function_declaration": "def read_from_fd(fd, n):",
"function_name": "read_from_fd",
"parameter_list": "(fd, n)"
},
{
"docstring": null,
"function_declaration": "def write_to_fd(fd, data):",
"function_name": "write_to_fd",
"parameter_list": "(fd, data)"
},
... | [
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 os\n\ndef read_from_fd(fd: int, n: int) -> str:\n \"\"\"\n Reads up to n characters or bytes from the file descriptor fd.\n \n If n is -1, reads an e... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00023425",
"row_id": 23425,
"seed_ids": "[37]"
} | 0.509744 | Docs: Python310_23425 | I | [
"read_from_fd",
"write_to_fd",
"dup_fd",
"close_fd",
"process_file"
] | 5 | [
[
"process_file",
"close_fd"
],
[
"process_file",
"read_from_fd"
],
[
"process_file",
"write_to_fd"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 782e24715d0121f38e59d257bb053d7f47aa5043 | f279dff3695b7c2d2be5c49debb358876f879818 | |||
v1.0 | instruct | Docs | Docs: Python310_23451_I | #### Objective
Create a Python script that simulates some of the initialization and configuration behavior of an embedded Python interpreter. Specifically, you will write a series of functions that will manage the configuration, preinitialization, and initialization of a mock Python environment using the principles des... | class MockWideStringList:
def __init__(self):
self.items = []
def append(self, item):
self.items.append(item)
def __repr__(self):
return f"MockWideStringList({self.items})"
class MockStatus:
def __init__(self, status, message=''):
self.status = status
self.mes... | import pytest
from solution import MockWideStringList, MockStatus, initialize_mock_config, apply_command_line_args, preinitialize, initialize, run_mock_environment
def test_initialize_mock_config():
config = initialize_mock_config()
assert config == {'home': '', 'utf8_mode': True, 'log_to_file': False}
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": "class MockWideStringList:\n def __init__(self):\n self.items = []\n\n def append(self, item):\n self.items.append(item)\n\n def __repr__(self):\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023451",
"row_id": 23451,
"seed_ids": "[15]"
} | 0.497549 | Docs: Python310_23451 | I | [
"initialize_mock_config",
"apply_command_line_args",
"preinitialize",
"initialize",
"run_mock_environment"
] | 5 | [
[
"initialize",
"preinitialize"
],
[
"run_mock_environment",
"apply_command_line_args"
],
[
"run_mock_environment",
"initialize"
],
[
"run_mock_environment",
"initialize_mock_config"
]
] | 4 | [] | false | [
"MockWideStringList",
"MockStatus"
] | true | pytest | true | [] | true | 581b83a50effa0d070aedfff35efe676f5592207 | c5d489b93395479160dbae8c7a055eff384520bd | |||
v1.0 | instruct | Docs | Docs: Seaborn_23511_I | Advanced Data Visualization with Seaborn
#### Problem Statement
You are provided with a dataset containing information about customers' purchases and their satisfaction levels at a retail store. You need to use the seaborn library to create several visualizations that will help in understanding the relationships betw... | import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
sns.set_theme(style="ticks")
def create_facetgrid_histogram(df):
g = sns.FacetGrid(df, col="age_group", height=4, aspect=1.5)
g.map(sns.histplot, "purchase_amount", kde=False)
g.add_legend()
plt.show()
def cr... | from solution import create_facetgrid_histogram, create_pairgrid_relationship, create_custom_facetgrid
import pandas as pd
def test_create_facetgrid_histogram():
data = {
"customer_id": [1, 2, 3, 4],
"purchase_amount": [100, 150, 200, 250],
"satisfaction_level": [2, 3, 4, 5],
"age_g... | [
{
"docstring": null,
"function_declaration": "def create_facetgrid_histogram(df):",
"function_name": "create_facetgrid_histogram",
"parameter_list": "(df)"
},
{
"docstring": null,
"function_declaration": "def create_pairgrid_relationship(df):",
"function_name": "create_pairgrid_relat... | [
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 pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Set the theme for seaborn\nsns.set_theme(style=\"ticks\")\n\ndef cr... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023511",
"row_id": 23511,
"seed_ids": "[3]"
} | 0.675889 | Docs: Seaborn_23511 | I | [
"create_facetgrid_histogram",
"create_pairgrid_relationship",
"custom_plot",
"create_custom_facetgrid"
] | 4 | [
[
"create_custom_facetgrid",
"custom_plot"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"pandas",
"seaborn"
] | false | 06e7dfd4142e3011566e5ec308befcf3b216227b | ec600f99fffc6da4b9eaa6f9c338f506a3df00fa | |||
v1.0 | instruct | Docs | Docs: Pandas_23520_I | You are tasked with analyzing business date offsets for a company that operates on a global scale. The company has different working calendars for different regions, which include varying business days and holidays. Your task is to implement a function that computes the next 10 business days considering region-specific... | import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar
from pandas.tseries.offsets import CustomBusinessDay
from datetime import datetime
# Function to get specific holidays for regions
def get_region_holidays(region):
if region == 'US':
holidays = [
pd.Timestamp('2023-... | from solution import next_ten_business_days
def test_next_ten_business_days_us_case():
result = next_ten_business_days('2023-11-22', 'US')
expected = ['2023-11-22', '2023-11-24', '2023-11-27', '2023-11-28', '2023-11-29', '2023-11-30', '2023-12-01', '2023-12-04', '2023-12-05', '2023-12-06']
assert result ==... | [
{
"docstring": null,
"function_declaration": "def get_region_holidays(region):",
"function_name": "get_region_holidays",
"parameter_list": "(region)"
},
{
"docstring": null,
"function_declaration": "def next_ten_business_days(start_date, region):",
"function_name": "next_ten_business... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom pandas.tseries.holiday import (\n AbstractHolidayCalendar, Holiday,\n USFederalHolidayCalendar, nearest_workday,\n)\nfrom pandas.tseries... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00023520",
"row_id": 23520,
"seed_ids": "[32]"
} | 0.793211 | Docs: Pandas_23520 | I | [
"get_region_holidays",
"next_ten_business_days"
] | 2 | [
[
"next_ten_business_days",
"get_region_holidays"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | f9ff79669ab504c531de9b9350b3b0a3118489be | ea2d9c7088426529631b70db90229b2a4d970fc9 | |||
v1.0 | instruct | Docs | Docs: Python310_23531_I | ## Coding Assessment Question
### Background:
The `asyncio` library in Python allows for writing concurrent programs using the `async/await` syntax. This capability is particularly useful for IO-bound operations where you can avoid blocking the main thread while awaiting results (such as reading from a file, network r... | import asyncio
import aiohttp
from bs4 import BeautifulSoup
from typing import List, Dict
async def fetch_content(session: aiohttp.ClientSession, url: str) -> str:
"""
Fetches the content of a URL.
"""
try:
async with session.get(url) as response:
return await response.text()
ex... | import pytest
import asyncio
from solution import fetch_urls
@pytest.mark.asyncio
async def test_fetch_urls_single_page():
urls = ["https://example.com"]
result = await fetch_urls(urls)
assert "https://example.com" in result
assert isinstance(result["https://example.com"], list)
@pytest.mark.asyncio
a... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom aiohttp import ClientSession\nfrom typing import List, Dict\nfrom bs4 import BeautifulSoup\n\nasync def fetch_content(url: str, session: ClientSess... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023531",
"row_id": 23531,
"seed_ids": "[270]"
} | 0.647131 | Docs: Python310_23531 | I | [
"fetch_content",
"parse_links",
"fetch_and_parse",
"fetch_urls"
] | 4 | [
[
"fetch_and_parse",
"fetch_content"
],
[
"fetch_and_parse",
"parse_links"
],
[
"fetch_urls",
"fetch_and_parse"
]
] | 3 | [] | false | [] | false | pytest | true | [
"aiohttp",
"bs4"
] | false | a745cb89923115a46854bb2cc442f1d6e8e9a6ac | 4e00538eddfbd18cb14f66c4fc2dbf0c0ba9f94a | |||
v1.0 | instruct | Docs | Docs: Seaborn_23596_I | ### Seaborn Coding Assessment
#### Objective
Demonstrate your understanding and proficiency in using the seaborn library for data visualization by implementing and customizing a plot based on given specifications.
#### Problem Statement
Implement a Python function using seaborn that:
1. Loads the `healthexp` dataset.... | import seaborn as sns
import matplotlib.pyplot as plt
def load_healthexp_dataset():
"""
Loads the healthexp dataset from seaborn.
"""
healthexp = sns.load_dataset('healthexp')
return healthexp
def visualize_health_expenditure(year_start: int, year_end: int) -> None:
"""
Visualizes health e... | import pytest
def test_load_healthexp_dataset():
data = load_healthexp_dataset()
assert not data.empty, "Dataset should not be empty"
assert 'Year' in data.columns, "Dataset should contain 'Year' column"
assert 'Spending_USD' in data.columns, "Dataset should contain 'Spending_USD' column"
assert 'L... | [
{
"docstring": "Loads the healthexp dataset from seaborn.",
"function_declaration": "def load_healthexp_dataset():",
"function_name": "load_healthexp_dataset",
"parameter_list": "()"
},
{
"docstring": "Visualizes health expenditure and life expectancy from healthexp dataset within given year... | [
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 seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef load_healthexp_dataset():\n \"\"\"\n Loads the healthexp dataset from seaborn.\n \"\"\"\n heal... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023596",
"row_id": 23596,
"seed_ids": "[57]"
} | 0.643079 | Docs: Seaborn_23596 | I | [
"load_healthexp_dataset",
"visualize_health_expenditure"
] | 2 | [
[
"visualize_health_expenditure",
"load_healthexp_dataset"
]
] | 1 | [] | false | [] | false | pytest | false | [
"matplotlib",
"seaborn"
] | false | 2959f8ff4ffff733d3cce52b9dd308230e421c0d | 7904ab1020c0132229c33bd6a20e258e113ea3e7 | |||
v1.0 | instruct | Docs | Docs: Python310_23605_I | You are tasked with creating a multi-threaded Python program using the `_thread` module. Your program will simulate a banking system where multiple threads represent different bank tellers handling transactions simultaneously. Each teller will process a list of transactions that include deposits and withdrawals.
### R... | import _thread
import time
class BankAccount:
def __init__(self, balance: int):
self.balance = balance
self.lock = _thread.allocate_lock()
def deposit(self, amount: int):
with self.lock:
self.balance += amount
def withdraw(self, amount: int):
... | from solution import BankAccount, process_transactions, simulate_bank_tellers
def test_bank_account_operations():
account = BankAccount(1000)
# Test deposit
account.deposit(200)
assert account.get_balance() == 1200
# Test withdraw with sufficient balance
account.withdraw(600)
asse... | [] | [
0,
0,
0,
1,
1,
1,
1,
0,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import _thread\nimport time\n\nclass BankAccount:\n def __init__(self, balance: int):\n self.balance = balance\n self.lock = _thread.allocate_lock()\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00023605",
"row_id": 23605,
"seed_ids": "[223]"
} | 0.492396 | Docs: Python310_23605 | I | [
"process_transactions",
"simulate_bank_tellers"
] | 2 | [
[
"simulate_bank_tellers",
"process_transactions"
]
] | 1 | [] | false | [
"BankAccount"
] | true | pytest | true | [] | true | 23c44764d744b3f42a1bbb62541fd9f2822c9329 | 27282c1193a7bb27f484bfa745e4e8bcbc44a11d | |||
v1.0 | instruct | Docs | Docs: Pytorch_23666_I | ### Question: Implement and Vectorize a Function with `torch.func.vmap`
You are required to implement a function using the `torch.func` module that performs a specific computation on a batch of input tensors. The function should be written in a manner compatible with `vmap` and must adhere to all the limitations and c... | import torch
from torch.func import vmap
def squared_difference(x, y):
return ((x - y) ** 2).sum()
def vectorized_squared_difference(a, b):
return vmap(squared_difference)(a, b)
# Example usage
a = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
b = torch.tensor([[1.0, 2.1], [2.9, 4.0], [5.1, 6.1]])
resul... | import torch
from solution import vectorized_squared_difference
def test_vectorized_squared_difference_same_tensors():
a = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
b = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
result = vectorized_squared_difference(a, b)
expected = torch.tensor([0.0,... | [
{
"docstring": null,
"function_declaration": "def squared_difference(x, y):",
"function_name": "squared_difference",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def vectorized_squared_difference(a, b):",
"function_name": "vectorized_squared_difference"... | [
0,
0,
1,
0,
1,
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 torch\nfrom torch.func import vmap\n\ndef squared_difference(x, y):\n return ((x - y) ** 2).sum()\n\ndef vectorized_squared_difference(a, b):\n return vmap... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00023666",
"row_id": 23666,
"seed_ids": "[136]"
} | 0.572096 | Docs: Pytorch_23666 | I | [
"squared_difference",
"vectorized_squared_difference"
] | 2 | [
[
"vectorized_squared_difference",
"squared_difference"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 6b8ca2ed08edd5c347e0a6ca001a7faebfa5f5b8 | d64d8c5eb476a42d971729b3d95bbfd29f3bde1b | |||
v1.0 | instruct | Docs | Docs: Python310_23688_I | ### Understanding and Implementing Coroutines in Python
#### Objective:
To assess the understanding and implementation of coroutines in Python using both high-level `async` and `await` syntax and the lower-level functions provided in the Python C API for creating and managing coroutine objects.
#### Problem Statement... | import asyncio
from typing import List
# Task 1 - Coroutine using async and await
async def fetch_data(n: int) -> int:
"""
Coroutine that simulates data fetching operation which takes n seconds
to complete and then returns n.
"""
await asyncio.sleep(n)
return n
# Task 2 - Coroutine using PyCor... | import pytest
import asyncio
from solution import fetch_data, process_data, is_coroutine
@pytest.mark.asyncio
async def test_fetch_data():
result = await fetch_data(1)
assert result == 1
@pytest.mark.asyncio
async def test_process_data():
result = await process_data([1, 2, 3])
assert result == 6
def ... | [
{
"docstring": "Function that would use PyCoro_New to create a new coroutine object.\nPlaceholder for actual implementation.",
"function_declaration": "def fetch_data_new(frame, name, qualname):",
"function_name": "fetch_data_new",
"parameter_list": "(frame, name, qualname)"
},
{
"docstring"... | [
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 asyncio\nfrom typing import List\n\n# Task 1 - Coroutine using async and await\nasync def fetch_data(n: int) -> int:\n \"\"\"\n Coroutine that simulates da... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023688",
"row_id": 23688,
"seed_ids": "[8]"
} | 0.494259 | Docs: Python310_23688 | I | [
"fetch_data",
"fetch_data_new",
"process_data",
"is_coroutine"
] | 4 | [
[
"process_data",
"fetch_data"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 17f9ae4d7053e0469610ae63e061b5400bbc8adf | f21df01f284681cc9052eddeab95e9edcb7d542d | |||
v1.0 | instruct | Docs | Docs: Python310_23743_I | ### Question: Implement an Asynchronous Task Scheduler
#### Objective:
Your task is to implement a simple asynchronous task scheduler in Python that can run multiple async tasks and gather their results once they are completed.
#### Task Details:
1. Implement an `async` function named `delayed_result`:
- This func... | import asyncio
from typing import List, Tuple
async def delayed_result(value: int, delay_time: int) -> int:
"""
Asynchronously waits for delay_time seconds and then returns the given value.
:param value: The value to return after the delay.
:param delay_time: The time (in seconds) to wait before r... | import asyncio
from solution import delayed_result, run_tasks
async def test_delayed_result():
result = await delayed_result(5, 1)
assert result == 5
result = await delayed_result(10, 2)
assert result == 10
async def test_run_tasks():
input_tasks = [(10, 2), (20, 1), (30, 3)]
results = await ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def delayed_result(value: int, delay_time: int) -> int:\n \"\"\"\n Asynchronously wait for delay_time seco... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023743",
"row_id": 23743,
"seed_ids": "[8]"
} | 0.720205 | Docs: Python310_23743 | I | [
"delayed_result",
"run_tasks"
] | 2 | [
[
"run_tasks",
"delayed_result"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ac2f08701a7cb8d9d02b16c2ff74962456d01d0e | 1eb279736890bc1844c80568fef2fafc5fc58520 | |||
v1.0 | instruct | Docs | Docs: Seaborn_23751_I | #### Objective
Assess students' proficiency in using seaborn's `cubehelix_palette` function to generate and customize color palettes for data visualization.
#### Problem Statement
You are given a dataset of car specifications, and you need to visualize various aspects of this data using bar plots with customized color... | import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
def load_sample_data():
"""
Load the built-in mpg dataset from seaborn.
Returns:
DataFrame: The mpg dataset.
"""
return sns.load_dataset("mpg")
def generate_palette(num_colors, start=0, rot=0.5, gamma=1.0, hue=1... | import pytest
from solution import load_sample_data, generate_palette, visualize_data, main_visualization
def test_load_sample_data():
data = load_sample_data()
assert isinstance(data, pd.DataFrame)
assert not data.empty
expected_columns = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'a... | [
{
"docstring": "Load the built-in mpg dataset from seaborn.\n\nReturns:\n DataFrame: The mpg dataset.",
"function_declaration": "def load_sample_data():",
"function_name": "load_sample_data",
"parameter_list": "()"
},
{
"docstring": "Generate a cubehelix palette based on the provided para... | [
0,
0,
0,
0,
1,
1,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef load_sample_data():\n \"\"\"\n Load the built-in 'mpg' dataset from seaborn.\n \n Returns:\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00023751",
"row_id": 23751,
"seed_ids": "[88]"
} | 0.56378 | Docs: Seaborn_23751 | I | [
"load_sample_data",
"generate_palette",
"visualize_data",
"main_visualization"
] | 4 | [
[
"main_visualization",
"generate_palette"
],
[
"main_visualization",
"load_sample_data"
],
[
"main_visualization",
"visualize_data"
]
] | 3 | [] | false | [] | false | pytest | true | [
"matplotlib",
"pandas",
"seaborn"
] | false | f93e832896265c53eefd8145adabd3752e8d9cee | 59a37158a49ee9a1e4021eb9d8086aececd47b23 | |||
v1.0 | instruct | Docs | Docs: Python310_23755_I | ### Question: Profiling and Memory Management in Python
You are given a Python script that performs some data processing operations. Your task is to analyze the script to identify any performance bottlenecks and excessive memory usage. You need to use the `cProfile` and `tracemalloc` modules to generate detailed repor... | import cProfile
import pstats
import tracemalloc
import random
import time
def slow_function():
time.sleep(2)
numbers = [random.randint(1, 100) for _ in range(10000)]
squared_numbers = [n ** 2 for n in numbers]
return sum(squared_numbers)
def fast_function():
numbers = range(1, 10001)
squared_... | from solution import slow_function, fast_function
def test_slow_function():
result = slow_function()
assert isinstance(result, int)
assert result > 0
def test_fast_function():
result = fast_function()
assert isinstance(result, int)
assert result > 0
def test_profile_execution():
import cP... | [
{
"docstring": null,
"function_declaration": "def slow_function():",
"function_name": "slow_function",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def fast_function():",
"function_name": "fast_function",
"parameter_list": "()"
},
{
"docstring":... | [
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 cProfile\nimport pstats\nimport tracemalloc\nimport random\nimport time\n\ndef slow_function():\n time.sleep(2)\n numbers = [random.randint(1, 100) for _ i... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023755",
"row_id": 23755,
"seed_ids": "[364]"
} | 0.559436 | Docs: Python310_23755 | I | [
"slow_function",
"fast_function",
"profile_execution",
"analyze_memory"
] | 4 | [
[
"analyze_memory",
"fast_function"
],
[
"analyze_memory",
"slow_function"
],
[
"profile_execution",
"fast_function"
],
[
"profile_execution",
"slow_function"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 187d0d966943255031c7cc774d588c4afa848e18 | f90abf68a9b29799be56c6365472386a6b31e2bb | |||
v1.0 | instruct | Docs | Docs: Pytorch_23841_I | ### Question
You are given a PyTorch model that performs matrix multiplication with large tensors. To optimize performance, you need to implement a function that:
1. Performs matrix multiplication in parallel using TorchScript.
2. Tunes the number of intra-op threads to find the optimal runtime.
Implement the functio... | import torch
import timeit
from torch import Tensor
from typing import List, Tuple
@torch.jit.script
def compute_y(x: Tensor) -> Tensor:
w_y = torch.randn(x.size(1), x.size(1))
return torch.mm(x, w_y)
@torch.jit.script
def compute_z(x: Tensor) -> Tensor:
w_z = torch.randn(x.size(1), x.size(1))
ret... | import torch
import pytest
from solution import optimized_matrix_multiplication
def test_optimized_matrix_multiplication():
x = torch.randn(512, 512)
max_threads = 4
results = optimized_matrix_multiplication(x, max_threads)
# Verify the structure of results
assert isinstance(results, list)
ass... | [
{
"docstring": null,
"function_declaration": "def compute_y(x):",
"function_name": "compute_y",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def compute_z(x):",
"function_name": "compute_z",
"parameter_list": "(x)"
},
{
"docstring": null,
"... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport timeit\nfrom torch import Tensor\nfrom typing import List, Tuple\n\n@torch.jit.script\ndef compute_y(x: Tensor) -> Tensor:\n # assuming x is a s... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00023841",
"row_id": 23841,
"seed_ids": "[169]"
} | 0.467557 | Docs: Pytorch_23841 | I | [
"compute_y",
"compute_z",
"optimized_matrix_multiplication"
] | 3 | [
[
"optimized_matrix_multiplication",
"compute_y"
],
[
"optimized_matrix_multiplication",
"compute_z"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | c53ed142d8ca402cf382d8ec45865de593672e5e | 3c27465503b4d227d597c1440d74033cefe34d7d | |||
v1.0 | instruct | Docs | Docs: Python310_23843_I | #### Objective:
This question aims to assess your understanding of the Python `warnings` module and your ability to manage and control warnings in a specific scenario while ensuring thread safety.
#### Problem Statement:
You are required to create a Python program that simulates a utility that performs several operati... | import warnings
import threading
# Custom warning definition
class CustomWarning(Warning):
pass
# Function to process data and issue warnings
def process_data(data):
for value in data:
if value < 0:
warnings.warn(f"Negative value found: {value} in data: {data}", CustomWarning)
# Function ... | from solution import CustomWarning, process_data, handle_warnings, ThreadSafeProcessor
def test_process_data_no_warnings():
data = [1, 2, 3]
with warnings.catch_warnings(record=True) as caught_warnings:
warnings.simplefilter("always", CustomWarning)
process_data(data)
assert len(caught_... | [] | [
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 warnings\nimport threading\n\n# Custom warning definition\nclass CustomWarning(Warning):\n pass\n\n# Function to process data and issue warnings\ndef process_... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023843",
"row_id": 23843,
"seed_ids": "[125]"
} | 0.5024 | Docs: Python310_23843 | I | [
"process_data",
"handle_warnings"
] | 2 | [
[
"handle_warnings",
"process_data"
]
] | 1 | [
"process_data"
] | false | [
"CustomWarning",
"ThreadSafeProcessor"
] | true | pytest | true | [] | true | 53aec86d9a730ca72fe94dfa85f6750fece5ec77 | 2b97c5e255be48eb476c3a2ec18538c3eff973c4 | |||
v1.0 | instruct | Docs | Docs: Python310_23846_I | ### XML-RPC Server and Client Setup
In this exercise, you'll create a simple XML-RPC server that performs basic arithmetic operations and a client to interact with the server.
#### Objectives:
1. Create an XML-RPC server that provides three arithmetic operations: addition, subtraction, and multiplication.
2. Register... | from xmlrpc.server import SimpleXMLRPCServer
import threading
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def run_server():
server = SimpleXMLRPCServer(('localhost', 9000))
server.register_function(add, 'add')
server.register_function(subtrac... | import xmlrpc.client
import pytest
from solution import add, subtract, multiply, client_interaction, server_thread
def test_add():
assert add(5, 3) == 8
def test_subtract():
assert subtract(5, 3) == 2
def test_multiply():
assert multiply(5, 3) == 15
def test_client_interaction():
# Ensure the server... | [
{
"docstring": null,
"function_declaration": "def add(x, y):",
"function_name": "add",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def subtract(x, y):",
"function_name": "subtract",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"fu... | [
0,
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": "# xmlrpc_server.py\n\nfrom xmlrpc.server import SimpleXMLRPCServer\nimport threading\n\ndef add(x, y):\n return x + y\n\ndef subtract(x, y):\n return x - y\n\ndef... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00023846",
"row_id": 23846,
"seed_ids": "[297]"
} | 0.409353 | Docs: Python310_23846 | I | [
"add",
"subtract",
"multiply",
"run_server",
"client_interaction"
] | 5 | [
[
"run_server",
"add"
],
[
"run_server",
"multiply"
],
[
"run_server",
"subtract"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 8e9a499bc101bfdb91920f9a08fe04d11bbe1b6f | f206ec5e9b43c614b630a3f9944aaed977db3cd8 | |||
v1.0 | instruct | Docs | Docs: Scikit_23894_I | Profiling and Optimization with scikit-learn
#### Objective
Demonstrate your understanding of profiling Python code, identifying performance bottlenecks, and optimizing code using Cython or multi-core parallelism.
#### Problem Statement
You are given a dataset and a scikit-learn model fitting task. Your goal is to:
1... | from sklearn.decomposition import NMF
from sklearn.datasets import load_digits
from joblib import Parallel, delayed
import timeit
# Original function to be optimized
def original_nmf():
X, _ = load_digits(return_X_y=True)
model = NMF(n_components=16, tol=1e-2)
model.fit(X)
# Function to perform NMF fittin... | from solution import optimize_nmf
def test_optimize_nmf():
# Testing this function involves checking the printed output
# Asserting the print output for verification
# We might mock the print statement and timeit to capture the output for verification
import io
import sys
# Capture the output
... | [
{
"docstring": null,
"function_declaration": "def original_nmf():",
"function_name": "original_nmf",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def parallel_nmf(X, n_components, tol, n_jobs=-1):",
"function_name": "parallel_nmf",
"parameter_list": "(X... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimize_nmf():\n # Import necessary libraries\n from sklearn.decomposition import NMF\n from sklearn.datasets import load_digits\n import timeit\n f... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023894",
"row_id": 23894,
"seed_ids": "[11]"
} | 0.523769 | Docs: Scikit_23894 | I | [
"original_nmf",
"parallel_nmf",
"optimize_nmf"
] | 3 | [
[
"optimize_nmf",
"parallel_nmf"
]
] | 1 | [] | false | [] | false | pytest | true | [
"joblib",
"sklearn"
] | false | 2ab60231bbb8c9df028b3707803060f22a9a8cb6 | 867015156549f20a53353fc6c3a229f7f7c0d4c4 | |||
v1.0 | instruct | Docs | Docs: Python310_23899_I | You are required to use the `wave` module to perform the following tasks:
1. **Read a WAV file**: Open a provided WAV file and extract its parameters.
2. **Manipulate the WAV file**: Perform some operations on the audio data.
3. **Write a new WAV file**: Save the manipulated audio data into a new WAV file.
**Detailed... | import wave
def read_wav_file(file_path):
"""
Reads a WAV file and extracts its parameters.
Args:
- file_path (str): Path to the input WAV file.
Returns:
- tuple: (number of channels, sample width, frame rate, total number of frames)
"""
with wave.open(file_path, 'rb') as wav_... | from solution import read_wav_file, manipulate_audio_data, write_wav_file
import wave
import os
import pytest
@pytest.fixture
def setup_wav():
"""
Create a sample WAV file for testing.
"""
file_path = "test.wav"
with wave.open(file_path, 'wb') as wav_file:
wav_file.setnchannels(1) # mono
... | [
{
"docstring": "Reads a WAV file and extracts its parameters.\n\nArgs:\n- file_path (str): Path to the input WAV file.\n\nReturns:\n- tuple: (number of channels, sample width, frame rate, total number of frames)",
"function_declaration": "def read_wav_file(file_path):",
"function_name": "read_wav_file",... | [
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 wave\n\ndef read_wav_file(file_path):\n \"\"\"\n Reads a WAV file and extracts its parameters.\n \n Args:\n - file_path (str): The path to the WAV... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023899",
"row_id": 23899,
"seed_ids": "[150]"
} | 0.493444 | Docs: Python310_23899 | I | [
"read_wav_file",
"manipulate_audio_data",
"write_wav_file"
] | 3 | [
[
"write_wav_file",
"manipulate_audio_data"
],
[
"write_wav_file",
"read_wav_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 35f1b7fd89f8c3ffb00f41e5c691c730247387e3 | 22d468cdad02bc63b660fbeed84c267aada7d405 | |||
v1.0 | instruct | Docs | Docs: Python310_23904_I | ### Python Coding Assessment Question
#### Context:
You are working on a text processing task that involves analyzing and processing a large dataset stored in a text file. The file contains multiple records, where each record is a line formatted as follows:
```
ID, Name, Age, Score
```
Here's an example of a few lin... | import os
import logging
from typing import List, Tuple
def parse_line(line: str) -> Tuple[int, str, int, int]:
"""
Parse a line of input file into a tuple of (ID, Name, Age, Score).
"""
try:
parts = line.strip().split(", ")
return (int(parts[0]), parts[1], int(parts[2]), int(parts[3]))... | import os
from solution import process_records
def create_test_file(filepath: str, content: str) -> None:
with open(filepath, 'w') as f:
f.write(content)
def test_process_records():
test_file = 'test_records.txt'
test_content = """1, Alice, 30, 88
2, Bob, 24, 95
3, Charlie, 29, 79
"""
create_t... | [
{
"docstring": "Parse a line of input file into a tuple of (ID, Name, Age, Score).",
"function_declaration": "def parse_line(line):",
"function_name": "parse_line",
"parameter_list": "(line)"
},
{
"docstring": "Processes the records in the input file, sorts them, writes to a new file,\nand r... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport logging\nfrom typing import List, Tuple\n\ndef parse_line(line: str) -> Tuple[int, str, int, int]:\n \"\"\"\n Parse a line of input file into a ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023904",
"row_id": 23904,
"seed_ids": "[418]"
} | 0.599182 | Docs: Python310_23904 | I | [
"parse_line",
"process_records"
] | 2 | [
[
"process_records",
"parse_line"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 044d7d20618bc00721a1e00b71719d2a32e9ae20 | e8882a4087effff615381c0ab0b20346ed50bd2c | |||
v1.0 | instruct | Docs | Docs: Python310_23910_I | ### Bytecode Analysis and Modification Task
In this task, you will explore Python bytecode using the "dis" module. You will be given a function, and you will need to analyze its bytecode, modify the bytecode to change the function's behavior, and then verify the changes. This will test your understanding of bytecode m... | import dis
import types
def square_and_add(x, y):
"""
Squares the first number and adds it to the second number.
"""
result = (x * x) + y
return result
def analyze_bytecode(func):
"""
Analyze the bytecode of the given function.
Args:
func (function): The function to disassemble.
... | from solution import analyze_bytecode, modify_bytecode, square_and_add
def test_analyze_bytecode():
bytecode = analyze_bytecode(square_and_add)
assert len(bytecode) > 0
assert isinstance(bytecode, list)
assert isinstance(bytecode[0], dis.Instruction)
def test_modify_bytecode():
modified_func = mod... | [
{
"docstring": "Squares the first number and adds it to the second number.",
"function_declaration": "def square_and_add(x, y):",
"function_name": "square_and_add",
"parameter_list": "(x, y)"
},
{
"docstring": "Analyze the bytecode of the given function.\n\nArgs:\nfunc (function): The functi... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import dis\nimport types\n\ndef analyze_bytecode(func):\n \"\"\"\n Analyze the bytecode of the given function.\n\n Args:\n func (function): The function to ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023910",
"row_id": 23910,
"seed_ids": "[382]"
} | 0.579761 | Docs: Python310_23910 | I | [
"square_and_add",
"analyze_bytecode",
"modify_bytecode",
"verify_modification"
] | 4 | [
[
"verify_modification",
"modify_bytecode"
],
[
"verify_modification",
"square_and_add"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 53d745cb343cce895c6ed879be917681ac61410c | 5f63dfa8d8902608990536560a6f46d391c71321 | |||
v1.0 | instruct | Docs | Docs: Python310_23922_I | #### Title: Implementing a Multi-threaded Counter with Synchronization
#### Objective:
Demonstrate your understanding of creating, managing, and synchronizing multiple threads using the `_thread` module in Python.
#### Problem Statement:
You are required to implement a multi-threaded counter that increments a global... | import _thread
import time
def thread_worker(counter_lock, increments, counter_list, index):
"""
Worker function for each thread. Increments the value in the counter_list by 1 for
the specified number of increments in a thread-safe manner using the provided lock.
"""
for _ in range(increments):
... | from solution import main_threaded_counter
def test_main_threaded_counter_single_thread():
assert main_threaded_counter(1, 500) == 500
def test_main_threaded_counter_multiple_threads():
assert main_threaded_counter(5, 1000) == 5000
def test_main_threaded_counter_large_number_threads():
assert main_thread... | [
{
"docstring": "Worker function for each thread. Increments the value in the counter_list by 1 for \nthe specified number of increments in a thread-safe manner using the provided lock.",
"function_declaration": "def thread_worker(counter_lock, increments, counter_list, index):",
"function_name": "thread... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import _thread\nfrom time import sleep\n\ndef thread_worker(counter_lock, increments, counter_list, index):\n \"\"\"\n Increments the value in counter_list[index]... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023922",
"row_id": 23922,
"seed_ids": "[223]"
} | 0.549018 | Docs: Python310_23922 | I | [
"thread_worker",
"main_threaded_counter"
] | 2 | [
[
"main_threaded_counter",
"thread_worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2b4648f1175e32f963f0c58641f6f8b01de44382 | 01e3136d6ca353350053854aa7bb9ac1dcd3720f | |||
v1.0 | instruct | Docs | Docs: Python310_23953_I | **Question: Implement a Debugging Tool Using `linecache`**
You are asked to implement a lightweight debugging tool in Python that inspects source files and retrieves specific lines of code. The tool should use the `linecache` module for efficient line retrieval and should provide the following functionalities:
1. **R... | import linecache
def retrieve_line(filename: str, lineno: int) -> str:
"""
Retrieve a specific line from a file.
Parameters:
- filename: The path to the source file.
- lineno: The line number to retrieve.
Returns:
- The content of the line including newline character, or an empty ... | import os
import pytest
from solution import retrieve_line, retrieve_multiple_lines, reset_cache, validate_cache
test_filename = "test_file.py"
def setup_module(module):
# Create a test file
lines = [
"import os\n",
"import sys\n",
"\n",
"def foo():\n",
" return 'foo... | [
{
"docstring": "Retrieve a specific line from a file.\n\nParameters:\n- filename: The path to the source file.\n- lineno: The line number to retrieve.\n\nReturns:\n- The content of the line including newline character, or an empty string if the line or file doesn't exist.",
"function_declaration": "def retr... | [
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 linecache\n\ndef retrieve_line(filename: str, lineno: int) -> str:\n \"\"\"\n Retrieves the specific line from the file.\n\n Parameters:\n filename (... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023953",
"row_id": 23953,
"seed_ids": "[110]"
} | 0.457866 | Docs: Python310_23953 | I | [
"retrieve_line",
"retrieve_multiple_lines",
"reset_cache",
"validate_cache"
] | 4 | [
[
"retrieve_multiple_lines",
"retrieve_line"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 373d0e5c403807f23d75eff6b546e98683320741 | 927db632da6ed8c4e88446cfcdcde68464558e42 | |||
v1.0 | instruct | Docs | Docs: Python310_23959_I | **Objective:** Demonstrate your understanding of creating and managing threads using the `_thread` module in Python.
You are required to write a Python program that creates multiple threads to compute the sum of integers in a list. Each thread should handle a portion of the list. Use locks to ensure that the summing o... | import _thread
import time
# Define a function to compute the partial sum of a list segment
def partial_sum(data, lock, result_holder):
# Compute sum of data
partial_sum_result = sum(data)
# Acquire lock and update the result_holder
lock.acquire()
try:
result_holder[0] += partial_sum_r... | from solution import partial_sum, compute_sum
import _thread
import time
# Test the functionality of partial_sum
def test_partial_sum():
lock = _thread.allocate_lock()
result_holder = [0]
data = [1, 2, 3, 4, 5]
partial_sum(data, lock, result_holder)
assert result_holder[0] == 15
# Test comput... | [
{
"docstring": null,
"function_declaration": "def partial_sum(data, lock, result_holder):",
"function_name": "partial_sum",
"parameter_list": "(data, lock, result_holder)"
},
{
"docstring": null,
"function_declaration": "def compute_sum(data, num_threads):",
"function_name": "compute... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import _thread\n\n# This variable will hold the partial sums computed by each thread\nresult_holder = []\n\ndef partial_sum(data, lock, result_holder):\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023959",
"row_id": 23959,
"seed_ids": "[223]"
} | 0.555213 | Docs: Python310_23959 | I | [
"partial_sum",
"compute_sum"
] | 2 | [
[
"compute_sum",
"partial_sum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3722cd6fb928735e9c954831744b367d2ef1686d | 3d1510b9ccb62e3ac79b7d71c13c2c606c6f77d5 | |||
v1.0 | instruct | Docs | Docs: Python310_24013_I | You are tasked with implementing a type-safe system that utilizes multiple advanced features provided by the `typing` module. The goal is to design a small library for an e-commerce platform that includes handling users, orders, and generic functions. This assessment will test your knowledge of type variables, generics... | from typing import NewType, Generic, TypeVar, List, Dict, overload
# Step 1: Define User class
UserId = NewType('UserId', int)
class User:
user_id: UserId
name: str
def __init__(self, user_id: UserId, name: str) -> None:
self.user_id = user_id
self.name = name
# Step 2: Define Order clas... | def test_container_operations():
container = Container[int]()
container.add(1)
container.add(2)
assert container.get_all() == [1, 2]
assert container.remove(1) == True
assert container.get_all() == [2]
assert container.remove(3) == False
def test_create_user_and_order():
user_id = UserI... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import NewType, Generic, TypeVar, List, Dict, overload\n\n# Step 1: Define User class\nUserId = NewType('UserId', int)\n\nclass User:\n user_id: UserId\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00024013",
"row_id": 24013,
"seed_ids": "[198]"
} | 0.404326 | Docs: Python310_24013 | I | [
"calculate_discount",
"calculate_discount",
"process_orders"
] | 3 | [
[
"process_orders",
"calculate_discount"
]
] | 1 | [] | false | [
"User",
"Order",
"Container"
] | true | pytest | false | [] | true | 8a4a56fa2dadf166f7f481c8e8fd406c5e9826b2 | 33ca82f29474c545fa8b37f61b706cb7119e10bf | |||
v1.0 | instruct | Docs | Docs: Pytorch_24016_I | ### Distributed Training with PyTorch
This assessment tests your understanding of PyTorch's `torch.distributed` module, specifically its `torchrun` elastic launch utility used to facilitate distributed training across multiple nodes.
#### Problem Statement
You are provided with a machine learning model and a dataset... | import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, Dataset
# Dummy dataset for illustration
class DummyDataset(Dataset):
def __init__... | import torch
from torch.utils.data import Dataset, DataLoader
from solution import SimpleModel, DummyDataset, train, setup, cleanup
import torch.distributed as dist
import torch.multiprocessing as mp
import time
def test_dummy_dataset():
dataset = DummyDataset(size=100)
data, target = dataset[0]
assert dat... | [] | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.multiprocessing as mp\nfrom torch.nn.parallel import Di... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00024016",
"row_id": 24016,
"seed_ids": "[145]"
} | 0.467153 | Docs: Pytorch_24016 | I | [
"setup",
"cleanup",
"train",
"main"
] | 4 | [
[
"train",
"cleanup"
],
[
"train",
"setup"
]
] | 2 | [] | false | [
"DummyDataset",
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | d8c4c6ebd93b64bb1116b168609c21d3ce2ae989 | 9ce987a9fcf445f497150d5e389e3fe37f147973 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.