version
stringclasses
1 value
style
stringclasses
2 values
subset
stringclasses
12 values
question_id
stringlengths
9
23
question
stringlengths
27
8.13k
solution
stringlengths
99
5.97k
test
stringlengths
105
4.45k
test_info
listlengths
0
13
gpt_pass_sequence
listlengths
1
10
gpt_pass_trial_num
int64
1
10
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
trials
dict
chosen_trial
stringclasses
10 values
metadata
dict
benchmark_similarity
float64
0.16
0.93
benchmark_instruction
stringclasses
1 value
benchmark_task_id
stringclasses
1 value
filter_reason
stringclasses
1 value
base_id
stringlengths
7
21
variant
stringclasses
2 values
top_function_names
listlengths
2
13
n_top_functions
int64
2
13
helper_call_edges
listlengths
1
16
n_helper_call_edges
int64
1
16
harness_functions
listlengths
0
3
structural_wrapper
bool
1 class
class_names
listlengths
0
5
has_class
bool
2 classes
test_kind
stringclasses
1 value
test_has_solution_import
bool
2 classes
third_party_imports
listlengths
0
5
stdlib_only
bool
2 classes
question_norm_sha1
stringlengths
40
40
solution_ast_sha1
stringlengths
40
40
v1.0
complete
Docs
Docs: Python310_3554_C
import contextvars import asyncio from typing import List # Step 1: Define the ContextVar for request_id request_id = contextvars.ContextVar('request_id') # Step 2: Implement the initialize_request function def initialize_request(request_id_value: str): """Initialize the context variable with the given request ID...
import contextvars import asyncio from typing import List # Step 1: Define the ContextVar for request_id request_id = contextvars.ContextVar('request_id') # Step 2: Implement the initialize_request function def initialize_request(request_id_value: str): request_id.set(request_id_value) # Step 3: Implement the pr...
import asyncio from solution import initialize_request, process_request, handle_requests def test_process_request_single(): async def run_test(): result = await process_request("req_123") assert result == "Processed request ID: req_123" asyncio.run(run_test()) def test_handle_requests...
[ { "docstring": null, "function_declaration": "def initialize_request(request_id_value):", "function_name": "initialize_request", "parameter_list": "(request_id_value)" } ]
[ 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 contextvars\nimport asyncio\nfrom typing import List\n\n# Step 1: Define the ContextVar for request_id\nrequest_id = contextvars.ContextVar('request_id')\n\n# St...
trial_gpt4o_1
{ "original_instruction": "### Python Coding Assessment\n\n#### Objective\n\nYour task is to implement a system that utilizes `contextvars` to manage state during asynchronous operations. You will create context variables, manage their state, and use them in an asynchronous function.\n\n#### Problem Statement\n\n1. *...
0.563439
Docs: Python310_3554
C
[ "initialize_request", "process_request", "handle_requests" ]
3
[ [ "handle_requests", "process_request" ], [ "process_request", "initialize_request" ] ]
2
[]
false
[]
false
pytest
true
[]
true
dd2d93f795d99122d005faf6292d119678f1bfc9
d04c288a1402c5e9d4c2056ed7b71b3e2f1816f2
v1.0
complete
Docs
Docs: Python310_4068_C
import asyncio import logging import threading # Configure logging logging.basicConfig(level=logging.DEBUG) async def simulate_download(file_id: int, download_time: int) -> None: """Asynchronously simulates a file download. Logs the start and completion of the download. Args: file_id (int): ID of ...
import asyncio import logging import threading # Configure logging logging.basicConfig(level=logging.DEBUG) async def simulate_download(file_id: int, download_time: int) -> None: # Log the start of the download logging.debug(f'Starting download: file_id={file_id}, download_time={download_time}s') # Simula...
import asyncio import threading import time import logging from contextlib import redirect_stdout import io import pytest from solution import simulate_download, schedule_download, main @pytest.mark.asyncio async def test_simulate_download(): f = io.StringIO() with redirect_stdout(f): await simulate_d...
[ { "docstring": null, "function_declaration": "def schedule_download(loop, file_id, download_time):", "function_name": "schedule_download", "parameter_list": "(loop, file_id, download_time)" } ]
[ 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 asyncio\nimport logging\nimport threading\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG)\n\nasync def simulate_download(file_id: int, download_...
trial_gpt4o_2
{ "original_instruction": "In this exercise, you are expected to write a Python script using asyncio to simulate a real-world scenario where multiple asynchronous tasks need to be managed and coordinated.\n\n### Task Description\nYou are to implement a simulation of a simple download manager that manages multiple dow...
0.50008
Docs: Python310_4068
C
[ "simulate_download", "schedule_download", "main" ]
3
[ [ "schedule_download", "simulate_download" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b454fa521d3229d5edf9fde5926a7e63ac077b92
21590a80a85a3f7bb66b348862a6e01974ef15cd
v1.0
complete
Docs
Docs: Python310_4384_C
from typing import List, Tuple def fetch_urls_concurrently(urls: List[str], max_workers: int) -> List[Tuple[str, str]]: """ Fetches the content of multiple URLs concurrently. Args: urls (List[str]): List of URLs to fetch. max_workers (int): Maximum number of worker threads to use. ...
import concurrent.futures import requests from typing import List, Tuple def fetch_url(url: str) -> Tuple[str, str]: """ Fetches the content of the URL and returns a tuple (URL, content/exception message). """ try: response = requests.get(url) response.raise_for_status() return ...
from solution import fetch_urls_concurrently import requests from requests.exceptions import RequestException from unittest.mock import patch, Mock def mock_requests_get(url): mock_resp = Mock() if 'example' in url: mock_resp.status_code = 200 mock_resp.text = "<html>Example Content</html>" ...
[ { "docstring": "Fetches the content of the URL and returns a tuple (URL, content/exception message).", "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_list": "(url)" }, { "docstring": "Fetches contents of the given URLs concurrently and returns a list ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nimport requests\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef fetch_url(url: str) -> Tuple[str, str]:\n try...
trial_gpt4o_2
{ "original_instruction": "## Coding Assessment Question\n\n### Objective:\nImplement a function that processes a list of URLs concurrently to fetch their HTML content. The function should use `concurrent.futures` to handle multiple URL fetching tasks in parallel, ensuring efficient and robust execution.\n\n### Descr...
0.636174
Docs: Python310_4384
C
[ "fetch_url", "fetch_urls_concurrently" ]
2
[ [ "fetch_urls_concurrently", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
50330be2d753f3cce34fc94f90afe45ccfb13c2b
8fecb459dade2b91cc9599fd54e3dbe92be85c1e
v1.0
complete
Docs
Docs: Python310_3691_C
from typing import Dict, Any, List, Optional def parse_mailcap_entry(entry: str) -> Dict[str, Any]: """ Parse a single mailcap entry into a dictionary. >>> parse_mailcap_entry("video/mpeg; xmpeg %s") {'video/mpeg': {'view': 'xmpeg %s'}} >>> parse_mailcap_entry("image/jpeg; display %s; compose=editjpeg ...
import os from typing import Dict, Any, List, Optional def parse_mailcap_entry(entry: str) -> Dict[str, Any]: fields = entry.split(';') if len(fields) < 2: # Invalid entry, should at least contain mime type and command return {} mime_type = fields[0].strip() entries = { 'view': ...
import pytest from solution import parse_mailcap_entry, load_mailcap, generate_command def test_parse_mailcap_entry(): entry = "video/mpeg; xmpeg %s" expected_output = { "video/mpeg": { "view": "xmpeg %s" } } assert parse_mailcap_entry(entry) == expected_output entry = ...
[ { "docstring": null, "function_declaration": "def parse_mailcap_entry(entry):", "function_name": "parse_mailcap_entry", "parameter_list": "(entry)" }, { "docstring": null, "function_declaration": "def load_mailcap(filepath):", "function_name": "load_mailcap", "parameter_list": "(...
[ 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": "def parse_mailcap_entry(entry):\n \"\"\"\n Parses a single mailcap entry into a dictionary.\n \n Parameters:\n entry (str): A single line from a mailcap ...
trial_gpt4o_6
{ "original_instruction": "### Problem Description\n\nYou are required to create a utility that configures and retrieves MIME type handling commands based on a user's custom mailcap file configuration.\n\n#### Task\n\n1. **Create a function `parse_mailcap_entry(entry: str) -> Dict[str, Any]`**:\n - Input: A string...
0.489939
Docs: Python310_3691
C
[ "parse_mailcap_entry", "load_mailcap", "generate_command" ]
3
[ [ "generate_command", "load_mailcap" ], [ "load_mailcap", "parse_mailcap_entry" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f03fbeef21abd1b0d61fec07314cc33d810d43f9
b017e491ef37e03867d3cec54b2edf5c5540c1fb
v1.0
complete
Docs
Docs: Python310_4530_C
import asyncio import logging from concurrent.futures import ThreadPoolExecutor async def fetch_data(delay: int): """ Simulates fetching data by sleeping for the given delay. """ # Your implementation here def process_data(data: int): """ Simulates processing data by squaring the given data. ...
import asyncio import logging from concurrent.futures import ThreadPoolExecutor async def fetch_data(delay: int): """ Simulates fetching data by sleeping for the given delay. """ await asyncio.sleep(delay) return delay def process_data(data: int): """ Simulates processing data by squaring ...
import asyncio from solution import fetch_data, process_data, run_async_tasks def test_fetch_data(): loop = asyncio.get_event_loop() result = loop.run_until_complete(fetch_data(3)) assert result == 3 def test_process_data(): assert process_data(3) == 9 assert process_data(4) == 16 def test_run_as...
[ { "docstring": "Simulates processing data by squaring the given data.", "function_declaration": "def process_data(data):", "function_name": "process_data", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def main():", "function_name": "main", "paramete...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport logging\nfrom concurrent.futures import ThreadPoolExecutor\n\nasync def fetch_data(delay: int):\n \"\"\"\n Simulates fetching data by sleep...
trial_gpt4o_0
{ "original_instruction": "### AsyncIO Task Management and Debugging\n\n**Objective**: Your task is to implement a small program using the `asyncio` framework that demonstrates handling asynchronous tasks, managing concurrency, and enabling debugging to identify common pitfalls.\n\n**Problem Statement**:\nImplement a...
0.511762
Docs: Python310_4530
C
[ "fetch_data", "process_data", "run_async_tasks", "main" ]
4
[ [ "run_async_tasks", "fetch_data" ], [ "run_async_tasks", "process_data" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
3d24a00edb2168a95bbacc97a102b9ca56e9ecca
b997a7dd39c06a20ddb9d015d22db19c18e125fb
v1.0
complete
Docs
Docs: Python310_3456_C
from xmlrpc.server import SimpleXMLRPCServer def add(x, y): """Returns the sum of x and y.""" pass def subtract(x, y): """Returns the difference when y is subtracted from x.""" pass def multiply(x, y): """Returns the product of x and y.""" pass def divide(x, y): """Returns the quotient w...
from xmlrpc.server import SimpleXMLRPCServer def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): if y == 0: raise ZeroDivisionError("Cannot divide by zero.") return x / y def start_server(): server = SimpleXMLRPCServer(("lo...
from solution import add, subtract, multiply, divide import pytest def test_add(): assert add(10, 5) == 15 assert add(-1, 1) == 0 assert add(0, 0) == 0 def test_subtract(): assert subtract(10, 5) == 5 assert subtract(5, 10) == -5 assert subtract(0, 0) == 0 def test_multiply(): assert mult...
[ { "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...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from xmlrpc.server import SimpleXMLRPCServer\n\ndef add(x, y):\n return x + y\n\ndef subtract(x, y):\n return x - y\n\ndef multiply(x, y):\n return x * y\n\nde...
trial_gpt4o_0
{ "original_instruction": "### Remote Task Execution with XML-RPC\n\n**Objective**: Implement an XML-RPC server and a client that can communicate with each other to perform a series of mathematical operations on remote data.\n\n**Task**: You need to create an XML-RPC server that offers methods to perform basic mathem...
0.41854
Docs: Python310_3456
C
[ "add", "subtract", "multiply", "divide", "start_server" ]
5
[ [ "start_server", "add" ], [ "start_server", "divide" ], [ "start_server", "multiply" ], [ "start_server", "subtract" ] ]
4
[]
false
[]
false
pytest
true
[]
true
ff9233248f9ca3eca0f3a53a91755bc106cedc37
ee8400304514be5de2ac7555fa3ede03e44ec90c
v1.0
complete
Docs
Docs: Python310_4043_C
import crypt import hmac def generate_hashed_password(password, method=None, rounds=None): """ Generates a hashed password with the given method and number of rounds. Args: password (str): The plain-text password. method (crypt.METHOD_* object, optional): The hashing method to use. Def...
import crypt import hmac def generate_hashed_password(password, method=None, rounds=None): """ Generates a hashed password with the given method and number of rounds. Args: password (str): The plain-text password. method (crypt.METHOD_* object, optional): The hashing method to use. Def...
from solution import generate_hashed_password, register_user, verify_login def test_generate_hashed_password(): plain_password = "securepassword123" hashed_password = generate_hashed_password(plain_password) assert hashed_password.startswith("$"), "Hashed password should start with '$'" assert has...
[ { "docstring": "Generates a hashed password with the given method and number of rounds.\n\nArgs:\n password (str): The plain-text password.\n method (crypt.METHOD_* object, optional): The hashing method to use. Defaults to None.\n rounds (int, optional): The number of rounds if applicable.\n \nRetur...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import crypt\nimport hmac\n\ndef generate_hashed_password(password, method=None, rounds=None):\n \"\"\"\n Generates a hashed password using the specified method a...
trial_gpt4o_2
{ "original_instruction": "You are tasked with creating a secure login system. Using the `crypt` module, you need to implement functions for password hashing, user registration, and login verification. Your solution should consider different hashing methods and ensure secure password storage and verification.\n\n### ...
0.693354
Docs: Python310_4043
C
[ "generate_hashed_password", "register_user", "verify_login" ]
3
[ [ "register_user", "generate_hashed_password" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f5ee4855ea422b2a7a69b675844a24e321f48b28
4cfdb810df846e989e82d644d3379ec62a7b5df6
v1.0
complete
Docs
Docs: Python310_4729_C
import asyncio from typing import List async def fetch_data_and_process(urls: List[str]) -> List[str]: """Fetch data from a list of URLs and process them concurrently using asyncio. >>> import asyncio >>> urls = ["http://example.com/1", "http://example.com/2"] >>> asyncio.run(fetch_data_and_process(ur...
import asyncio from typing import List async def fetch_data(url: str) -> str: await asyncio.sleep(1) return f"Data from {url}" async def process_data(data: str) -> str: await asyncio.sleep(1) return f"Processed {data}" async def fetch_data_and_process(urls: List[str]) -> List[str]: # Fetch data c...
import pytest import asyncio from solution import fetch_data_and_process @pytest.mark.asyncio async def test_fetch_data_and_process_single_url(): urls = ["http://example.com/1"] result = await fetch_data_and_process(urls) assert result == ["Processed Data from http://example.com/1"] @pytest.mark.asyncio a...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List\n\nasync def fetch_data(url: str) -> str:\n await asyncio.sleep(1)\n return f\"Data from {url}\"\n\nasync def process_data...
trial_gpt4o_0
{ "original_instruction": "#### Objective:\nTo test your understanding of the `asyncio` library for writing concurrent code in Python.\n\n#### Task:\nImplement an asynchronous function `fetch_data_and_process` that simulates network data fetching and processing using `asyncio` library functions. \n\n1. **Function Sig...
0.520135
Docs: Python310_4729
C
[ "fetch_data", "process_data", "fetch_data_and_process" ]
3
[ [ "fetch_data_and_process", "fetch_data" ], [ "fetch_data_and_process", "process_data" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
899b7c801230355b89adad1b8a5924141f8f08e7
85fc0689c1c6db5d7b15f3cc7fd6778b3d4483d6
v1.0
complete
Docs
Docs: Python310_3570_C
def filter_records(records, category): """ Filters the transaction records by the given category. >>> transactions = [ ... ("T1", 100.0, "credit", "food"), ... ("T2", 50.0, "debit", "food"), ... ("T3", 200.0, "credit", "utility"), ... ("T4", 150.0, "debit", "utility"), ... ...
from functools import reduce def filter_records(records, category): """ Filters the transaction records by the given category. """ return list(filter(lambda record: record[3] == category, records)) def calculate_total_amount(records, transaction_type): """ Calculates the total amount for the g...
from solution import filter_records, calculate_total_amount, generate_summary def test_filter_records(): transactions = [ ("T1", 100.0, "credit", "food"), ("T2", 50.0, "debit", "food"), ("T3", 200.0, "credit", "utility"), ("T4", 150.0, "debit", "utility"), ("T5", 300.0, "cre...
[ { "docstring": "Filters the transaction records by the given category.", "function_declaration": "def filter_records(records, category):", "function_name": "filter_records", "parameter_list": "(records, category)" }, { "docstring": "Calculates the total amount for the given transaction type....
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from functools import reduce\n\ndef filter_records(records, category):\n \"\"\"\n Filters the transaction records based on the given category.\n\n :param recor...
trial_gpt4o_2
{ "original_instruction": "#### Objective\nImplement a Python function that processes transaction records using functional programming concepts such as iterators, generators, and higher-order functions.\n\n#### Problem Statement\nYou are given a list of transaction records, where each record is a tuple containing the...
0.604725
Docs: Python310_3570
C
[ "filter_records", "calculate_total_amount", "generate_summary" ]
3
[ [ "generate_summary", "calculate_total_amount" ], [ "generate_summary", "filter_records" ] ]
2
[]
false
[]
false
pytest
true
[]
true
60c4b9a1310dfa1568ed5e1c212f57aa7150e10c
e884d811d67775767602be45b8cef0188577dfb8
v1.0
complete
Docs
Docs: Scikit_3894_C
import numpy as np from sklearn.metrics import make_scorer def mean_log_transformed_absolute_percentage_error(y_true, y_pred): """ Compute the Mean Log-Transformed Absolute Percentage Error (MLAPE). Parameters: y_true (array-like): True values. y_pred (array-like): Predicted values. Returns: ...
import numpy as np from sklearn.metrics import make_scorer def mean_log_transformed_absolute_percentage_error(y_true, y_pred): """ Compute the Mean Log-Transformed Absolute Percentage Error (MLAPE). Parameters: y_true (array-like): True values. y_pred (array-like): Predicted values. Returns: ...
import numpy as np from solution import mean_log_transformed_absolute_percentage_error, evaluate_model_with_custom_metric from sklearn.datasets import load_diabetes def test_mean_log_transformed_absolute_percentage_error(): y_true = np.array([1, 2, 3, 4, 5]) y_pred = np.array([1.2, 1.9, 2.8, 4.1, 5.2]) ...
[ { "docstring": "Compute the Mean Log-Transformed Absolute Percentage Error (MLAPE).\n\nParameters:\ny_true (array-like): True values.\ny_pred (array-like): Predicted values.\n\nReturns:\nfloat: MLAPE score.", "function_declaration": "def mean_log_transformed_absolute_percentage_error(y_true, y_pred):", ...
[ 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 sklearn.metrics import make_scorer\nimport numpy as np\n\ndef mean_log_transformed_absolute_percentage_error(y_true, y_pred):\n \"\"\"\n Compute the Mean Log...
trial_gpt4o_2
{ "original_instruction": "In this task, you are required to implement a custom metric function for evaluating a machine learning model using scikit-learn. The custom metric will be an adaptation of the provided mean absolute percentage error (MAPE) but will include a log transformation to handle a wide range of targ...
0.625064
Docs: Scikit_3894
C
[ "mean_log_transformed_absolute_percentage_error", "evaluate_model_with_custom_metric" ]
2
[ [ "evaluate_model_with_custom_metric", "mean_log_transformed_absolute_percentage_error" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
dc2c28426aae68f5efcdc9d5d7ceead9d3aa3572
87800301afda8cbe1e71590ec4b22f455a48a2d4
v1.0
complete
Docs
Docs: Pytorch_4020_C
import torch from typing import Tuple def real_to_complex(S: torch.Tensor) -> torch.Tensor: """ Convert the real tensor S to a complex tensor. Args: S (torch.Tensor): A real tensor of shape (N, 2). Returns: torch.Tensor: A complex tensor of shape (N,). """ pass def compute_magnit...
import torch def real_to_complex(S: torch.Tensor) -> torch.Tensor: """ Convert the real tensor S to a complex tensor. """ return torch.view_as_complex(S) def compute_magnitude_phase(C: torch.Tensor): """ Compute the magnitude and phase angle (in radians) of each complex number in the tensor. ...
import torch from solution import real_to_complex, compute_magnitude_phase, apply_linear_transformation, compute_gradient def test_real_to_complex(): S = torch.tensor([[3.0, 4.0], [1.0, 2.0]], dtype=torch.float32) C = real_to_complex(S) assert C.shape == (2,) assert torch.allclose(C, torch.tensor([3 + ...
[ { "docstring": "Convert the real tensor S to a complex tensor.", "function_declaration": "def real_to_complex(S):", "function_name": "real_to_complex", "parameter_list": "(S)" }, { "docstring": "Compute the magnitude and phase angle (in radians) of each complex number in the tensor.", "f...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef real_to_complex(S: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert a real tensor of shape (N, 2) to a complex tensor.\n \"\"\"\n retur...
trial_gpt4o_8
{ "original_instruction": "### Complex Tensor Operations and Autograd in PyTorch\n\n#### Problem Statement\n\nYou are given a dataset that represents signals captured from some sensors. These signals are stored in a tensor `S` of size `(N, 2)`, where `N` is the number of signals. Each row in this tensor represents a ...
0.558267
Docs: Pytorch_4020
C
[ "real_to_complex", "compute_magnitude_phase", "apply_linear_transformation", "compute_gradient" ]
4
[ [ "compute_gradient", "apply_linear_transformation" ], [ "compute_gradient", "real_to_complex" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
f20f3a2ca2d57fe6dc52cdeeb506918c978d5bcf
5fc58ad5899341bebcb4ca9669c47f7c7e3c90bb
v1.0
complete
Docs
Docs: Python310_4533_C
def is_iterator(obj): """ Check if the obj is a valid iterator. >>> is_iterator(iter([1, 2, 3])) == True >>> is_iterator([1, 2, 3]) == False >>> is_iterator({'key': 'value'}) == False >>> is_iterator(iter('abc')) == True """ def iterate_all(obj): """ Returns a list of all elements i...
def is_iterator(obj): """ Check if the obj is a valid iterator. """ return hasattr(obj, '__iter__') and hasattr(obj, '__next__') def iterate_all(obj): """ Returns a list of all elements in the iterator obj. """ if not is_iterator(obj): raise TypeError("Object is not an iterator"...
import pytest from solution import is_iterator, iterate_all, is_async_iterator, async_iterate_all def test_is_iterator(): assert is_iterator(iter([1, 2, 3])) == True assert is_iterator([1, 2, 3]) == False assert is_iterator({'key': 'value'}) == False assert is_iterator(iter('abc')) == True def test_it...
[ { "docstring": "Check if the obj is a valid iterator.", "function_declaration": "def is_iterator(obj):", "function_name": "is_iterator", "parameter_list": "(obj)" }, { "docstring": "Returns a list of all elements in the iterator obj.", "function_declaration": "def iterate_all(obj):", ...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_iterator(obj):\n \"\"\"\n Checks if the object is a valid iterator.\n \"\"\"\n try:\n iter(obj)\n return True\n except TypeError:\n ...
trial_gpt4o_2
{ "original_instruction": "### Python Iterator Protocol Assessment\n\nYou are tasked with implementing functions that utilize the Python iterator protocol to handle both synchronous and asynchronous iterators. The goal is to create reliable tools that interact with iterators effectively, using the functions provided ...
0.435297
Docs: Python310_4533
C
[ "is_iterator", "iterate_all", "is_async_iterator", "async_iterate_all" ]
4
[ [ "async_iterate_all", "is_async_iterator" ], [ "iterate_all", "is_iterator" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9d83b0d7622970925f7dcf2a966e88d0fcd8cea8
39eba9b15eaa211bd670ff836c5c04f13b110a67
v1.0
complete
Docs
Docs: Python310_4017_C
import argparse import json import os TASKS_FILE = 'tasks.json' def load_tasks(): if os.path.exists(TASKS_FILE): with open(TASKS_FILE, 'r') as file: return json.load(file) else: return [] def save_tasks(tasks): with open(TASKS_FILE, 'w') as file: json.dump(tasks, file)...
import argparse import json import os TASKS_FILE = 'tasks.json' def load_tasks(): if os.path.exists(TASKS_FILE): with open(TASKS_FILE, 'r') as file: return json.load(file) else: return [] def save_tasks(tasks): with open(TASKS_FILE, 'w') as file: json.dump(tasks, file)...
import pytest import json import os from solution import add_task, list_tasks, remove_task, clear_tasks, TASKS_FILE @pytest.fixture(autouse=True) def setup_and_teardown(): # Setup: Clear the tasks file before each test clear_tasks() yield # Teardown: Remove the tasks file after each test if os.path...
[ { "docstring": null, "function_declaration": "def load_tasks():", "function_name": "load_tasks", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def save_tasks(tasks):", "function_name": "save_tasks", "parameter_list": "(tasks)" }, { "docstring": 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 argparse\nimport json\nimport os\n\nTASK_FILE = 'tasks.json'\n\ndef read_tasks():\n if os.path.exists(TASK_FILE):\n with open(TASK_FILE, 'r') as file:\...
trial_gpt4o_1
{ "original_instruction": "**Command Line Task Manager**\n\nCreate a Python script named `task_manager.py` that uses the `argparse` module to manage a simple task list. The script should support the following sub-commands:\n1. `add` - Add a new task to the list.\n2. `list` - List all tasks.\n3. `remove` - Remove a ta...
0.575535
Docs: Python310_4017
C
[ "load_tasks", "save_tasks", "add_task", "list_tasks", "remove_task", "clear_tasks", "main" ]
7
[ [ "add_task", "load_tasks" ], [ "add_task", "save_tasks" ], [ "clear_tasks", "save_tasks" ], [ "list_tasks", "load_tasks" ], [ "remove_task", "load_tasks" ], [ "remove_task", "save_tasks" ] ]
6
[]
false
[]
false
pytest
true
[]
true
f54de6c5db1b168118f63ec8d1ae7d649d3a2a1c
89e190c415587942915604826941365b9f4637b1
v1.0
complete
Docs
Docs: Python310_3449_C
import hmac import hashlib def generate_hmac(key: bytes, msg: bytes, digest_name: str) -> hmac.HMAC: """ Creates an HMAC object using the provided key, message, and digest algorithm. """ pass def update_hmac(hmac_obj: hmac.HMAC, msg: bytes) -> None: """ Updates the HMAC object with the additio...
import hmac import hashlib def generate_hmac(key: bytes, msg: bytes, digest_name: str) -> hmac.HMAC: """ Creates an HMAC object using the provided key, message, and digest algorithm. """ return hmac.new(key, msg, getattr(hashlib, digest_name)) def update_hmac(hmac_obj: hmac.HMAC, msg: bytes) -> None: ...
import pytest from solution import generate_hmac, update_hmac, get_hex_digest, verify_message def test_generate_hmac(): key = b'secret' msg = b'Test message' digest_name = 'sha256' hmac_obj = generate_hmac(key, msg, digest_name) assert isinstance(hmac_obj, hmac.HMAC) def test_update_hmac(): ke...
[ { "docstring": "Creates an HMAC object using the provided key, message, and digest algorithm.", "function_declaration": "def generate_hmac(key, msg, digest_name):", "function_name": "generate_hmac", "parameter_list": "(key, msg, digest_name)" }, { "docstring": "Updates the HMAC object with t...
[ 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_hmac(key: bytes, msg: bytes, digest_name: str) -> hmac.HMAC:\n \"\"\"\n Generates an HMAC object for the given message...
trial_gpt4o_2
{ "original_instruction": "### HMAC Coding Challenge\n\n#### Objective\nImplement a secure messaging system that uses HMAC for message authentication and integrity checking. You are required to write functions to generate an HMAC for a message, update the HMAC with an additional message, retrieve the hexadecimal dige...
0.823601
Docs: Python310_3449
C
[ "generate_hmac", "update_hmac", "get_hex_digest", "verify_message" ]
4
[ [ "verify_message", "generate_hmac" ], [ "verify_message", "get_hex_digest" ] ]
2
[]
false
[]
false
pytest
true
[]
true
56063258c588835d9452e0f2b1c32c48abec7104
5b92cf89ee388799ddf1729048d289dfd5e3732a
v1.0
complete
Docs
Docs: Python310_4385_C
import asyncio from typing import List async def fetch_headline(url: str) -> str: """Simulates fetching a headline from a given URL.""" pass async def fetch_all_headlines(urls: List[str]) -> List[str]: """Fetches headlines from multiple URLs concurrently.""" pass # Example usage """ import asyncio u...
import asyncio from typing import List import random async def fetch_headline(url: str) -> str: """Simulates fetching a headline from a given URL.""" await asyncio.sleep(random.randint(1, 3)) # Simulate network latency return f'Headline from {url}' async def fetch_all_headlines(urls: List[str]) -> List[s...
import pytest import asyncio from solution import fetch_headline, fetch_all_headlines @pytest.mark.asyncio async def test_fetch_headline(): url = 'https://newsapi.org/article' headline = await fetch_headline(url) assert headline == f'Headline from {url}' @pytest.mark.asyncio async def test_fetch_all_headl...
[]
[ 1, 1 ]
2
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 fetch_headline(url: str) -> str:\n \"\"\"Simulates fetching a headline from a given URL.\"\"\"\n ...
trial_gpt4o_0
{ "original_instruction": "### Asynchronous News Fetcher\n\nIn this task, you will build an asynchronous news fetcher that fetches headlines from multiple mock news APIs concurrently. You'll need to use the `asyncio` module to run coroutines in parallel and efficiently manage network I/O.\n\n**Your task is to:**\n1. ...
0.527546
Docs: Python310_4385
C
[ "fetch_headline", "fetch_all_headlines" ]
2
[ [ "fetch_all_headlines", "fetch_headline" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a06ee48d078ba4dad37711e328062bf116de59c4
284ba23831ae37cef8a8e1683858e2c72b3f9d7d
v1.0
complete
Docs
Docs: Python310_3837_C
import os import time import logging from logging.handlers import RotatingFileHandler def configure_logger(): """ Configure logger to log messages to 'activity.log' with a rotating file handler. """ logger = logging.getLogger() logger.setLevel(logging.INFO) handler = RotatingFileHandler('a...
import os import time import logging from logging.handlers import RotatingFileHandler def configure_logger(): # Configure logger settings logger = logging.getLogger() logger.setLevel(logging.INFO) handler = RotatingFileHandler('activity.log', maxBytes=1*1024*1024, backupCount=3) formatter = lo...
import os import time import logging def setup_function(): """ Setup operations before each test runs. """ # Remove sample_data directory if exists if os.path.exists('sample_data'): for file in os.listdir('sample_data'): os.remove(os.path.join('sample_data', file)) os.rm...
[ { "docstring": null, "function_declaration": "def configure_logger():", "function_name": "configure_logger", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def manage_files():", "function_name": "manage_files", "parameter_list": "()" }, { "docstri...
[ 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 time\nimport logging\nfrom logging.handlers import RotatingFileHandler\n\n# Configure logger\ndef setup_logger():\n logger = logging.getLogger()\n ...
trial_gpt4o_1
{ "original_instruction": "**Objective:**\nDemonstrate competence in utilizing Python's system-level modules to create a complex utility.\n\n### Problem Statement:\nYou are required to create a Python script that performs the following system-level tasks using the `os`, `time`, and `logging` modules:\n\n1. **Create a...
0.616705
Docs: Python310_3837
C
[ "configure_logger", "manage_files", "log_timestamps" ]
3
[ [ "manage_files", "configure_logger" ] ]
1
[]
false
[]
false
pytest
false
[]
true
0dc2b995a3d3c8ccae6d0c1cb0e307040a275334
3b440b5f75660b71024801d82146c956e1452c75
v1.0
complete
Docs
Docs: Python310_1749_C
import mailbox import email import os def create_maildir(path): """ Create a Maildir mailbox at the specified path. """ return mailbox.Maildir(path, create=True) def create_mbox(path): """ Create an mbox mailbox at the specified path. """ return mailbox.mbox(path, create=True) def add...
import mailbox import email def create_maildir(path): """ Create a Maildir mailbox at the specified path. """ return mailbox.Maildir(path, create=True) def create_mbox(path): """ Create an mbox mailbox at the specified path. """ return mailbox.mbox(path, create=True) def add_message_t...
import os import shutil import pytest from solution import ( create_maildir, create_mbox, add_message_to_mailbox, move_message, list_all_messages, remove_message ) def test_maildir_mailbox_creation(tmpdir): maildir_path = tmpdir.join("maildir") maildir_box = create_maildir(maildir_path) assert os....
[ { "docstring": "Create a Maildir mailbox at the specified path.", "function_declaration": "def create_maildir(path):", "function_name": "create_maildir", "parameter_list": "(path)" }, { "docstring": "Create an mbox mailbox at the specified path.", "function_declaration": "def create_mbox...
[ 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 mailbox\nimport os\n\ndef create_maildir(path):\n \"\"\"Create a Maildir mailbox at the specified path.\"\"\"\n return mailbox.Maildir(path, create=True)\n...
trial_gpt4o_3
{ "original_instruction": "Mailbox Management and Message Handling\n\nYou are tasked with creating a mailbox management utility that organizes emails into different mailboxes based on specific criteria. The utility will primarily work with the `Maildir` and `mbox` formats. Your program should demonstrate an understan...
0.551177
Docs: Python310_1749
C
[ "create_maildir", "create_mbox", "add_message_to_mailbox", "move_message", "list_all_messages", "remove_message" ]
6
[ [ "move_message", "remove_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a93a9da94ff3720427bdc910c6d23540f3e31f8c
6091e886f7bdaf55cdc2923d3e1b8d0f41269542
v1.0
complete
Docs
Docs: Scikit_4454_C
from sklearn.kernel_approximation import RBFSampler from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score from typing import List def kernel_approximation_and_classification(X_train: List[List[float]], y_train: List[int], X_test: List[List[float]], y_test: List[int]) -> float: "...
from sklearn.kernel_approximation import RBFSampler from sklearn.linear_model import SGDClassifier from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score def kernel_approximation_and_classification(X_train, y_train, X_test, y_tes...
import pytest from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from solution import kernel_approximation_and_classification def test_kernel_approximation_and_classification_with_dummy_data(): X, y = make_classification(n_samples=100, n_features=20, random_state=...
[ { "docstring": "Transforms the input features using RBFSampler and trains a SGDClassifier on the transformed data.\nCalculates and prints the accuracy of the classifier on the testing dataset.\n\nParameters:\n- X_train (2D list of floats): Training dataset features.\n- y_train (list of integers): Training datas...
[ 0, 0, 0, 1, 0, 1, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.kernel_approximation import RBFSampler\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\n\ndef kernel_approximat...
trial_gpt4o_6
{ "original_instruction": "### Task\nYou are given a dataset containing numerical features, and your goal is to transform these features using kernel approximations and then train a linear classifier on the transformed data. Specifically, you will need to:\n\n1. Use the `RBFSampler` to transform the input features.\n...
0.625037
Docs: Scikit_4454
C
[ "kernel_approximation_and_classification", "example_usage" ]
2
[ [ "example_usage", "kernel_approximation_and_classification" ] ]
1
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
0b54da433ca4be03e60b89c144714dd3bf611edc
e206be1c9cd5760a44dc858d968fa58be01e01cd
v1.0
complete
Docs
Docs: Python310_3978_C
import logging import threading from decimal import Decimal from pprint import pprint def initialize_logger(): """Initializes the logging system. The logging system logs various levels of messages (DEBUG, INFO, WARNING, ERROR, CRITICAL). Log messages are directed to both a file (transactions.log) and the ...
import logging import threading from decimal import Decimal from pprint import pprint # Setting up the logger def initialize_logger(): logger = logging.getLogger('FinancialAppLogger') logger.setLevel(logging.DEBUG) # Console handler console_handler = logging.StreamHandler() console_handler.set...
import os from solution import process_transactions, initialize_logger import logging def test_logger_file_creation(): # Clean up before test if os.path.exists('transactions.log'): os.remove('transactions.log') logger = initialize_logger() logger.info("Testing file creation") ...
[ { "docstring": null, "function_declaration": "def initialize_logger():", "function_name": "initialize_logger", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def log_transactions(transactions, logger):", "function_name": "log_transactions", "parameter_lis...
[ 0, 0, 0, 1, 0, 0, 1, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import logging\nimport threading\nfrom decimal import Decimal\nfrom pprint import pprint\nimport time\n\n# Function to initialize the logging system.\ndef initialize_lo...
trial_gpt4o_9
{ "original_instruction": "#### Objective\nYou are tasked to develop a customizable and efficient logging system for a financial application that handles various transaction records. The system will be required to format and display logs, manage performance through threading, and accurately process financial data.\n\...
0.470498
Docs: Python310_3978
C
[ "initialize_logger", "log_transactions", "process_transactions" ]
3
[ [ "process_transactions", "initialize_logger" ] ]
1
[]
false
[]
false
pytest
true
[]
true
62310121189eae63c6e65f0044fbd81dc6860acb
6a8122c1683d7bfd3c58749477ce598d0714e2bd
v1.0
complete
Docs
Docs: Pandas_3917_C
import pandas as pd def process_time_series_events(): """ Perform various time series operations on event logs. Returns: daily_events (pd.DataFrame): A DataFrame containing daily aggregated event counts. business_day_counts (pd.DataFrame): A DataFrame containing event counts for each valid...
import pandas as pd import numpy as np from pandas.tseries.holiday import USFederalHolidayCalendar from datetime import datetime, timedelta def process_time_series_events(): # Step 1: Generate Timestamps events = generate_timestamps() # Step 2: Timezone Conversion events = convert_timezone(events)...
import pytest from solution import process_time_series_events, generate_timestamps, convert_timezone, resample_aggregation, handle_ambiguous_nonexistent_times, custom_business_day_resampling def test_generate_timestamps(): events = generate_timestamps() assert not events.empty assert 'timestamp' in events....
[ { "docstring": null, "function_declaration": "def process_time_series_events():", "function_name": "process_time_series_events", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def generate_timestamps():", "function_name": "generate_timestamps", "parameter...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom pandas.tseries.holiday import USFederalHolidayCalendar\nfrom pandas.tseries.offsets import CustomBusinessDay\n\ndef process_time_series_events...
trial_gpt4o_3
{ "original_instruction": "<|Analysis Begin|>\n\nThe documentation provided offers an extensive look into time series and date functionalities within the pandas framework. It details various operations such as parsing, generating sequences, manipulating, resampling, and converting date times with timezone information...
0.706042
Docs: Pandas_3917
C
[ "process_time_series_events", "generate_timestamps", "convert_timezone", "resample_aggregation", "handle_ambiguous_nonexistent_times", "custom_business_day_resampling" ]
6
[ [ "process_time_series_events", "convert_timezone" ], [ "process_time_series_events", "custom_business_day_resampling" ], [ "process_time_series_events", "generate_timestamps" ], [ "process_time_series_events", "handle_ambiguous_nonexistent_times" ], [ "process_ti...
5
[]
false
[]
false
pytest
true
[ "numpy", "pandas" ]
false
5d8a8684f3514b32998b70246a5664b9573af442
ac89af061d72245f9893ab8ac9ee81c4cef78411
v1.0
complete
Docs
Docs: Python310_3730_C
import os import argparse def list_files(directory): """List all files in the specified directory.""" try: files = os.listdir(directory) files = [f for f in files if os.path.isfile(os.path.join(directory, f))] for file in files: print(file) except FileNotFoundError: ...
import os import argparse def list_files(directory): try: files = os.listdir(directory) files = [f for f in files if os.path.isfile(os.path.join(directory, f))] for file in files: print(file) except FileNotFoundError: print(f"Error: The directory '{directory}' does n...
import os import shutil import pytest from solution import list_files, create_file, delete_file @pytest.fixture def setup_directory(tmp_path): test_dir = tmp_path / "test_dir" test_dir.mkdir() (test_dir / "file1.txt").write_text("Hello world") (test_dir / "file2.txt").write_text("Hello again") ret...
[ { "docstring": null, "function_declaration": "def list_files(directory):", "function_name": "list_files", "parameter_list": "(directory)" }, { "docstring": null, "function_declaration": "def create_file(directory, filename):", "function_name": "create_file", "parameter_list": "(d...
[ 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 os\nimport argparse\n\ndef list_files(directory):\n try:\n files = os.listdir(directory)\n for file in files:\n print(file)\n exce...
trial_gpt4o_1
{ "original_instruction": "File Operations and Command-Line Parsing\n\n#### Objective:\nYou are tasked with implementing a Python script that performs specific file operations based on command-line arguments provided by the user. This will assess your understanding of the `os` and `argparse` modules.\n\n#### Problem ...
0.623749
Docs: Python310_3730
C
[ "list_files", "create_file", "delete_file", "file_manager" ]
4
[ [ "file_manager", "create_file" ], [ "file_manager", "delete_file" ], [ "file_manager", "list_files" ] ]
3
[]
false
[]
false
pytest
true
[]
true
dc95cac2add42c8ff1f2a33fc12d9d589a30924b
24cbbe982a6604f725c2d17544b2d8ca03ce1bf4
v1.0
complete
Docs
Docs: Python310_4927_C
import asyncio import sys from typing import List async def process_file_content(content: str) -> str: """ Simulate processing of file content. For simplicity, simulate processing by simply returning the reversed content after a short delay. Args: content (str): The content of the file. Return...
import asyncio import sys from typing import List async def process_file_content(content: str) -> str: await asyncio.sleep(1) # Simulating a delay in processing return content[::-1] # Reverse content for demonstration purposes def read_and_process_files(file_paths: List[str]) -> None: async def _interna...
import asyncio import os import pytest from solution import read_and_process_files, process_file_content @pytest.mark.asyncio async def test_process_file_content(): content = "Hello, World!" expected_result = "!dlroW ,olleH" result = await process_file_content(content) assert result == expected_result ...
[ { "docstring": null, "function_declaration": "def read_and_process_files(file_paths):", "function_name": "read_and_process_files", "parameter_list": "(file_paths)" } ]
[ 0, 0, 0, 0, 1, 1, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport sys\nfrom typing import List\n\nasync def process_file_content(content: str) -> str:\n \"\"\"\n Simulates processing on file content by rev...
trial_gpt4o_5
{ "original_instruction": "### Python Coding Assessment Question\n\n**Objective**: This assessment will test your understanding of Python's Development Mode and its debugging features. You will be required to write a program that handles file operations and asynchronous tasks, demonstrating your ability to manage res...
0.543716
Docs: Python310_4927
C
[ "process_file_content", "read_and_process_files" ]
2
[ [ "read_and_process_files", "process_file_content" ] ]
1
[]
false
[]
false
pytest
true
[]
true
04ae4a8208815cb0bb1509acad36196bdc92d37a
fc6eaf70ce946e74a4e8d46391ff918a83378036
v1.0
complete
Docs
Docs: Python310_4392_C
import asyncio import random async def fetch_data(url: str) -> str: """ An asynchronous function that takes a URL, simulates a network call by sleeping for a random amount of time, and returns a string indicating the content of the URL (for simplicity, concatenate "Data from " with the URL). """ pass ...
import asyncio import random async def fetch_data(url: str) -> str: await asyncio.sleep(random.randint(1, 5)) return f"Data from {url}" async def process_data(data: str) -> None: print(f"Length of data is {len(data)}") async def worker(name: str, queue: asyncio.Queue): while True: # Get the n...
import pytest from solution import fetch_data, process_data, main @pytest.mark.asyncio async def test_fetch_data(): url = "http://example.com/page1" data = await fetch_data(url) assert data == f"Data from {url}" @pytest.mark.asyncio async def test_process_data(capfd): data = "Data from http://example....
[]
[ 0, 0, 0, 1, 1, 0, 0, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\n\nasync def fetch_data(url: str) -> str:\n \"\"\"\n Simulates a network call by sleeping for a random amount of time \n (between...
trial_gpt4o_9
{ "original_instruction": "#### Concurrent Web Scraping and Data Processing with `asyncio`\n\nIn this exercise, you are required to develop an asynchronous Python application using the `asyncio` library. The goal is to concurrently scrape data from multiple web pages and then process that data. Your implementation sh...
0.57205
Docs: Python310_4392
C
[ "fetch_data", "process_data", "worker", "main" ]
4
[ [ "worker", "process_data" ] ]
1
[ "process_data" ]
false
[]
false
pytest
true
[]
true
cdc674742f0c17969b243b89c4b2a3daf2b8f4b5
03a620ed586f7e45e78cefe5bce01c25b2b68849
v1.0
complete
Docs
Docs: Python310_3648_C
class DatabaseError(Exception): """Base class for other database-related exceptions.""" pass class ConnectionError(DatabaseError): """Raised when there is a connection issue to the database.""" pass class QueryError(DatabaseError): """Raised when a query fails due to invalid syntax or execution is...
class DatabaseError(Exception): """Base class for other database-related exceptions.""" pass class ConnectionError(DatabaseError): """Raised when there is a connection issue to the database.""" pass class QueryError(DatabaseError): """Raised when a query fails due to invalid syntax or execution is...
import pytest from solution import DatabaseError, ConnectionError, QueryError, DataError, connect_to_database, execute_query, process_data, database_operation def test_valid_connection(): assert connect_to_database("valid_connection_string") is None def test_invalid_connection(): with pytest.raises(Connection...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class DatabaseError(Exception):\n \"\"\"Base class for other database-related exceptions.\"\"\"\n pass\n\nclass ConnectionError(DatabaseError):\n \"\"\"Raised ...
trial_gpt4o_2
{ "original_instruction": "### Custom Exception Handling in Python\n\n#### Objective:\nDesign and implement a custom exception hierarchy to handle specific error scenarios in a database interaction module. This will evaluate your ability to define custom exceptions, raise them appropriately, and ensure proper excepti...
0.461341
Docs: Python310_3648
C
[ "connect_to_database", "execute_query", "process_data", "database_operation" ]
4
[ [ "database_operation", "connect_to_database" ], [ "database_operation", "execute_query" ], [ "database_operation", "process_data" ] ]
3
[ "process_data" ]
false
[ "DatabaseError", "ConnectionError", "QueryError", "DataError" ]
true
pytest
true
[]
true
560a29d800eee08610797b623d7069de38c5bffd
96048517f4015db4d5dca2714d655c4514cdaa98
v1.0
complete
Docs
Docs: Python310_4921_C
import asyncio from typing import List, Coroutine async def async_fetch_data(url: str) -> Coroutine: """ Asynchronously fetch data from the given URL. Simulate network delay using asyncio.sleep. Example: >>> await async_fetch_data("https://example.com") Start fetching data from https://exa...
import asyncio from typing import List, Coroutine async def async_fetch_data(url: str) -> Coroutine: """ Asynchronously fetch data from the given URL. Simulate network delay using asyncio.sleep. """ print(f"Start fetching data from {url}") await asyncio.sleep(1) print(f"Fetching completed f...
import pytest import asyncio from solution import async_fetch_data, fetch_multiple_data @pytest.mark.asyncio async def test_async_fetch_data(capfd): url = "https://example.com" await async_fetch_data(url) captured = capfd.readouterr() assert "Start fetching data from https://example.com" in captured.ou...
[]
[ 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, Coroutine\n\nasync def async_fetch_data(url: str) -> Coroutine:\n \"\"\"\n Asynchronously fetch data from the given URL.\...
trial_gpt4o_0
{ "original_instruction": "### Asynchronous Programming with Coroutine Objects\n\nPython 3.5 introduced coroutine objects as a cornerstone of asynchronous programming. This exercise will guide you through understanding and implementing coroutines in Python by creating a function that utilizes these concepts.\n\n#### ...
0.553719
Docs: Python310_4921
C
[ "async_fetch_data", "fetch_multiple_data" ]
2
[ [ "fetch_multiple_data", "async_fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9653e6e2cf125dec078b1de4c9131c1bdf7650bf
6fe6c380d54c4640e96481c161d5ec7e29ca225b
v1.0
complete
Docs
Docs: Python310_3704_C
from pathlib import Path import shutil def synchronize_directories(src: str, dest: str) -> None: """ Synchronizes two directories such that the destination directory becomes an exact copy of the source directory. The function ensures that the destination directory is updated to match the source directory,...
from pathlib import Path import shutil def synchronize_directories(src: str, dest: str) -> None: src_path = Path(src) dest_path = Path(dest) # Ensure destination exists dest_path.mkdir(parents=True, exist_ok=True) for item in src_path.rglob('*'): rel_path = item.relative_to(src_pa...
import os from pathlib import Path import shutil import pytest from solution import synchronize_directories @pytest.fixture(autouse=True) def setup_and_teardown(tmp_path): src = tmp_path / "src" dest = tmp_path / "dest" src.mkdir() dest.mkdir() (src / "file1.txt").write_text("hello") ...
[ { "docstring": null, "function_declaration": "def synchronize_directories(src, dest):", "function_name": "synchronize_directories", "parameter_list": "(src, dest)" }, { "docstring": null, "function_declaration": "def file_contents_are_equal(file1, file2):", "function_name": "file_con...
[ 0, 0, 1, 0, 1, 1, 0, 0, 1 ]
4
medium
0.444
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from pathlib import Path\nimport shutil\n\ndef synchronize_directories(src: str, dest: str) -> None:\n \"\"\"\n Synchronizes the destination directory to make it ...
trial_gpt4o_6
{ "original_instruction": "**Question: File Synchronization Tool**\n\nYour task is to implement a function `synchronize_directories(src: str, dest: str) -> None` that synchronizes two directories. The function should ensure that the destination directory is an exact copy of the source directory. This includes creatin...
0.681475
Docs: Python310_3704
C
[ "synchronize_directories", "file_contents_are_equal" ]
2
[ [ "synchronize_directories", "file_contents_are_equal" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3dcb0bd44a090ff3d31fa07c2865a1f93662aa30
42562d8667dbf7b4ad519edc8adefbb8c750a9a0
v1.0
complete
Docs
Docs: Python310_4280_C
import os import stat def explore_directory(directory_path: str) -> dict: """ Explore a given directory recursively, gathers certain metadata about each file, and returns a summary. Args: directory_path (str): The path to the directory that needs to be explored. Returns: dict: A dictionary wi...
import os import stat def file_permissions(mode): """ Converts a file's mode to a string representation of its permissions, similar to `ls -l`. """ perms = ['-'] * 10 perm_mapping = { '0': '---', '1': '--x', '2': '-w-', '3': '-wx', '4': 'r--', '5': 'r...
from solution import explore_directory import os import pytest def create_test_files(): test_dir = "test_dir" sub_dirs = ["sub_dir_1", "sub_dir_2"] files = ["file_1.txt", "file_2.txt"] os.makedirs(test_dir, exist_ok=True) for sub_dir in sub_dirs: os.makedirs(os.path.join(test_dir, sub_dir)...
[ { "docstring": "Converts a file's mode to a string representation of its permissions, similar to `ls -l`.", "function_declaration": "def file_permissions(mode):", "function_name": "file_permissions", "parameter_list": "(mode)" }, { "docstring": null, "function_declaration": "def explore_...
[ 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 os\nimport stat\n\ndef explore_directory(directory_path: str) -> dict:\n summary = {\n \"total_files\": 0,\n \"total_directories\": 0,\n ...
trial_gpt4o_2
{ "original_instruction": "#### Title: File System Explorer Using `stat` Module\n\n#### Objective\nWrite a Python function that explores a given directory recursively, gathers certain metadata about each file, and returns a summary. This assessment will test your understanding of the `stat` module and your ability to...
0.665972
Docs: Python310_4280
C
[ "file_permissions", "explore_directory" ]
2
[ [ "explore_directory", "file_permissions" ] ]
1
[]
false
[]
false
pytest
true
[]
true
11edb5e3514c504fb097ac24a22c114ffd7c8281
fd0755f07ad0e2e5b26b395d9df40ce840f876ee
v1.0
complete
Docs
Docs: Python310_4795_C
import selectors import socket def accept(sock, mask): """ Accepts a connection from the client. """ pass def read(conn, mask): """ Reads data from the client and echoes it back. """ pass def run_echo_server(host: str, port: int): """ Run an echo server that handles multiple client connections. ...
import selectors import socket sel = selectors.DefaultSelector() def accept(sock, mask): conn, addr = sock.accept() # Should be ready print('Accepted', conn, 'from', addr) conn.setblocking(False) sel.register(conn, selectors.EVENT_READ, read) def read(conn, mask): data = conn.recv(1000) # Shoul...
import socket import threading import time def run_client(host, port, messages, responses): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect((host, port)) for message in messages: sock.sendall(message.encode('utf-8')) response = sock.recv(1024) ...
[ { "docstring": null, "function_declaration": "def accept(sock, mask):", "function_name": "accept", "parameter_list": "(sock, mask)" }, { "docstring": null, "function_declaration": "def read(conn, mask):", "function_name": "read", "parameter_list": "(conn, mask)" }, { "doc...
[ 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 selectors\nimport socket\n\ndef accept(sock, mask, sel):\n conn, addr = sock.accept() # Should be ready\n print(f'Accepted connection from {addr}')\n c...
trial_gpt4o_1
{ "original_instruction": "## Coding Assessment Question\n\n### Objective\nImplement a simple I/O server using the `selectors` module to handle multiple client connections simultaneously. The server should be able to accept connections, read data from clients, echo the data back to them, and handle client disconnecti...
0.742437
Docs: Python310_4795
C
[ "accept", "read", "run_echo_server" ]
3
[ [ "accept", "read" ], [ "run_echo_server", "accept" ] ]
2
[]
false
[]
false
pytest
false
[]
true
a733af69e48456a8dfe79a1fcd8d1621f60f70fe
245ed2b036cfbbb6c0266f7a20da3ee99097b7e9
v1.0
complete
Docs
Docs: Pytorch_4610_C
import torch from torch.autograd import Function def custom_relu(x: torch.Tensor, c: float) -> torch.Tensor: """ Define a custom ReLU operator that adds a constant value to the output. Args: x (torch.Tensor): Input tensor. c (float): Constant to add. Returns: torch.Tensor: Output tensor where ...
import torch from torch.autograd import Function class CustomReLU(Function): @staticmethod def forward(ctx, x, c): ctx.save_for_backward(x) ctx.constant = c return torch.relu(x) + c @staticmethod def backward(ctx, grad_output): x, = ctx.saved_tensors grad_x = gr...
import torch from solution import custom_relu def test_gradcheck_custom_relu(): x = torch.randn((5, 5), dtype=torch.float64, requires_grad=True) c = 0.5 assert torch.autograd.gradcheck(lambda x: custom_relu(x, c), (x,)), "gradcheck failed!" def test_output_custom_relu(): test_tensor = torch.tensor([[-...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.autograd import Function\nfrom torch.library import Library\n\n# Create a custom operator using PyTorch library\ncustom_lib = Library(\"custom_...
trial_gpt4o_2
{ "original_instruction": "#### Objective:\nCreate and test a custom operator in PyTorch using the `torch.library` module. The custom operator should perform a tailored mathematical operation and support gradient computations. You will also need to test the custom operator using provided utilities to ensure correctne...
0.514633
Docs: Pytorch_4610
C
[ "custom_relu", "test_custom_op" ]
2
[ [ "test_custom_op", "custom_relu" ] ]
1
[]
false
[ "CustomReLU" ]
true
pytest
true
[ "torch" ]
false
02bec7b1e44f0102ed567794db222df23c6f6778
71ef7d072fede91e21f68a17e3a9a95341b1a750
v1.0
complete
Docs
Docs: Python310_4077_C
import argparse def convert_temperature(value: float, input_unit: str, output_unit: str) -> float: """ Converts the temperature from one unit to another. Args: value (float): The temperature value to convert. input_unit (str): The unit of the input temperature value. (C, F, K) output_unit (str...
import argparse def celsius_to_fahrenheit(celsius): return (celsius * 9/5) + 32 def fahrenheit_to_celsius(fahrenheit): return (fahrenheit - 32) * 5/9 def celsius_to_kelvin(celsius): return celsius + 273.15 def kelvin_to_celsius(kelvin): return kelvin - 273.15 def fahrenheit_to_kelvin(fahrenheit): ...
def test_convert_temperature(): # Celsius to Fahrenheit assert convert_temperature(0, 'C', 'F') == 32.0 assert convert_temperature(100, 'C', 'F') == 212.0 # Fahrenheit to Celsius assert convert_temperature(32, 'F', 'C') == 0.0 assert convert_temperature(212, 'F', 'C') == 100.0 # Celsius to...
[ { "docstring": null, "function_declaration": "def celsius_to_fahrenheit(celsius):", "function_name": "celsius_to_fahrenheit", "parameter_list": "(celsius)" }, { "docstring": null, "function_declaration": "def fahrenheit_to_celsius(fahrenheit):", "function_name": "fahrenheit_to_celsiu...
[ 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 argparse\n\ndef convert_temperature(value: float, input_unit: str, output_unit: str) -> float:\n \"\"\"\n Converts the temperature from one unit to another...
trial_gpt4o_2
{ "original_instruction": "#### Problem Statement\n\nYou are required to create a Python script that acts as a converter for different temperature units. The script should take a temperature value and convert it between Celsius, Fahrenheit, and Kelvin based on the specified options using the `argparse` module for com...
0.554868
Docs: Python310_4077
C
[ "celsius_to_fahrenheit", "fahrenheit_to_celsius", "celsius_to_kelvin", "kelvin_to_celsius", "fahrenheit_to_kelvin", "kelvin_to_fahrenheit", "convert_temperature", "main" ]
8
[ [ "convert_temperature", "celsius_to_fahrenheit" ], [ "convert_temperature", "celsius_to_kelvin" ], [ "convert_temperature", "fahrenheit_to_celsius" ], [ "convert_temperature", "fahrenheit_to_kelvin" ], [ "convert_temperature", "kelvin_to_celsius" ], [ ...
10
[]
false
[]
false
pytest
false
[]
true
9093e8aeee06aa89c7181f6e8fb0008d9863e873
11abda5c548450723e13692303869e302d137e46
v1.0
complete
Docs
Docs: Python310_3942_C
import argparse import os TODO_FILE = 'todo.txt' def read_tasks(): if not os.path.exists(TODO_FILE): return [] with open(TODO_FILE, 'r') as file: lines = file.readlines() tasks = [] for line in lines: parts = line.strip().split(';', 2) task_id, status, description = par...
import argparse import os TODO_FILE = 'todo.txt' def read_tasks(): if not os.path.exists(TODO_FILE): return [] with open(TODO_FILE, 'r') as file: lines = file.readlines() tasks = [] for line in lines: parts = line.strip().split(';', 2) task_id, status, description = par...
import os import pytest from solution import add_task, list_tasks, delete_task, complete_task, read_tasks, write_tasks TEST_TODO_FILE = 'test_todo.txt' def setup_module(module): global TODO_FILE TODO_FILE = TEST_TODO_FILE if os.path.exists(TEST_TODO_FILE): os.remove(TEST_TODO_FILE) def teardown_m...
[ { "docstring": null, "function_declaration": "def read_tasks():", "function_name": "read_tasks", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def write_tasks(tasks):", "function_name": "write_tasks", "parameter_list": "(tasks)" }, { "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 argparse\nimport os\n\nTODO_FILE = 'todo.txt'\n\ndef read_tasks():\n if not os.path.exists(TODO_FILE):\n return []\n with open(TODO_FILE, 'r') as fi...
trial_gpt4o_0
{ "original_instruction": "**Command-Line Tool for To-Do List Management**\n\nYou have been assigned to create a simple command-line interface (CLI) for managing a to-do list. The program will support adding tasks, listing all tasks, deleting tasks, and marking tasks as completed. Your task is to implement the CLI us...
0.56147
Docs: Python310_3942
C
[ "read_tasks", "write_tasks", "add_task", "list_tasks", "delete_task", "complete_task", "main" ]
7
[ [ "add_task", "read_tasks" ], [ "add_task", "write_tasks" ], [ "complete_task", "read_tasks" ], [ "complete_task", "write_tasks" ], [ "delete_task", "read_tasks" ], [ "delete_task", "write_tasks" ], [ "list_tasks", "read_tasks" ] ]
7
[]
false
[]
false
pytest
true
[]
true
091e790f39fcfc6dd9b392f4ba24569f69e692fb
2cd9694c198ce283325f1c9cb01e222a41a4b517
v1.0
complete
Docs
Docs: Python310_3858_C
import requests import time from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Dict, List, Tuple def fetch_url(url: str) -> Tuple[str, float]: """ Fetches the URL and returns the time taken to load the page in seconds. Parameters: url (str): The URL to be fetched. ...
import requests import time from concurrent.futures import ThreadPoolExecutor, as_completed def fetch_url(url): """ Fetches the URL and returns the time taken to load the page in seconds. Parameters: url (str): The URL to be fetched. Returns: float: Time taken to fetch the...
import pytest from solution import fetch_url, fetch_all_urls def test_fetch_url_valid(): url = 'http://example.com' url, load_time = fetch_url(url) assert isinstance(load_time, float) assert load_time > 0 def test_fetch_url_invalid(): url = 'http://thisurldoesnotexist.tld' url, load_time = fet...
[ { "docstring": "Fetches the URL and returns the time taken to load the page in seconds.\n\nParameters:\n url (str): The URL to be fetched.\n \nReturns:\n float: Time taken to fetch the URL in seconds.", "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_...
[ 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 requests\nimport time\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef fetch_url(url):\n \"\"\"\n Fetches the URL and returns the ti...
trial_gpt4o_1
{ "original_instruction": "**Question: Analyzing Web Page Load Times with concurrent.futures**\n\nYou are tasked with analyzing the load times of multiple web pages to identify potential performance issues. You will read a list of URLs from a file and measure how long each one takes to load. You'll use the `concurren...
0.566386
Docs: Python310_3858
C
[ "fetch_url", "fetch_all_urls" ]
2
[ [ "fetch_all_urls", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
0c6857a0d78e19caaa7f3b858c7b96994746ad51
19f177d4a4330214bf6b3315a867152aa58be12c
v1.0
complete
Docs
Docs: Python310_4601_C
from fractions import Fraction from typing import List, Tuple, Dict def process_fractions(fractions_list: List[Tuple[int, int]]) -> Dict[str, List[Tuple[int, int]]]: """ Process a list of fractions and return a dictionary with normalized fractions, their sum, and the fraction closest to the average of the...
from fractions import Fraction from math import gcd def normalize_fraction(numerator, denominator): # Ensure the denominator is positive if denominator < 0: numerator, denominator = -numerator, -denominator common_divisor = gcd(numerator, denominator) return numerator // common_divisor, de...
from solution import process_fractions from fractions import Fraction def test_process_fractions(): fractions_list = [(1, 2), (3, 4), (-4, 5)] result = process_fractions(fractions_list) expected_normalized_fractions = [(1, 2), (3, 4), (-4, 5)] expected_sum = Fraction(1, 2) + Fraction(3, 4) + Fraction(...
[ { "docstring": null, "function_declaration": "def normalize_fraction(numerator, denominator):", "function_name": "normalize_fraction", "parameter_list": "(numerator, denominator)" }, { "docstring": null, "function_declaration": "def fraction_difference(f1, f2):", "function_name": "fr...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from fractions import Fraction\nimport math\n\ndef gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef normalize_fraction(numerator, denominator):\n ...
trial_gpt4o_3
{ "original_instruction": "**Advanced Fraction Manipulation and Arithmetic**\n\nYou are given a list of tuples where each tuple contains two integers representing the numerator and denominator of a fraction.\n\nYour task is to implement a function `process_fractions(fractions_list)` that takes this list, converts eac...
0.640235
Docs: Python310_4601
C
[ "normalize_fraction", "fraction_difference", "closest_fraction", "process_fractions" ]
4
[ [ "closest_fraction", "fraction_difference" ], [ "process_fractions", "closest_fraction" ], [ "process_fractions", "normalize_fraction" ] ]
3
[]
false
[]
false
pytest
true
[]
true
558ed736498fa6d25219e9808a609abc62a4d0ab
0df2f83be407ce8ff957cd4eb956dd7235a43caf
v1.0
complete
Docs
Docs: Pytorch_3812_C
import torch import torch.nn as nn class CustomMLP(nn.Module): """ Custom Neural Network Model using PyTorch built for classifying handwritten digits from the MNIST dataset. The model structure: - Input Linear layer with 784 input features and 128 output features - ReLU activation function - Dropou...
import torch import torch.nn as nn class CustomMLP(nn.Module): def __init__(self): super(CustomMLP, self).__init__() # Define layers self.fc1 = nn.Linear(784, 128) self.relu1 = nn.ReLU() self.dropout1 = nn.Dropout(p=0.5) self.fc2 = nn.Linear(128, 64) self.rel...
import pytest import torch import torch.nn as nn from solution import CustomMLP def test_custom_mlp_structure(): model = CustomMLP() # Check if the model has the correct layers assert isinstance(model.fc1, nn.Linear) assert model.fc1.in_features == 784 assert model.fc1.out_features == 128 ...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\n\nclass CustomMLP(nn.Module):\n def __init__(self):\n super(CustomMLP, self).__init__()\n # Define layers\n ...
trial_gpt4o_1
{ "original_instruction": "**Question:**\n\nYou are required to build a custom neural network model using PyTorch's `torch.nn` module. This custom model will be a multilayer perceptron (MLP) designed for the task of classifying handwritten digits from the MNIST dataset. Additionally, you will need to register forward...
0.679636
Docs: Pytorch_3812
C
[ "print_output_shape", "print_gradients", "train_model" ]
3
[ [ "train_model", "print_gradients" ], [ "train_model", "print_output_shape" ] ]
2
[]
false
[ "CustomMLP" ]
true
pytest
true
[ "torch", "torchvision" ]
false
8b791b2d19eede95f99aa7620528236e70ed1922
382aa87691112f1b31c3213c9b66c1118c80bf28
v1.0
complete
Docs
Docs: Python310_4638_C
import random def create_deck(): """ Returns a standard 52-card deck. >>> len(create_deck()) == 52 >>> ('2', 'hearts') in create_deck() >>> ('A', 'spades') in create_deck() """ def shuffle_deck(deck): """ Shuffles the deck of cards in place. >>> deck = create_deck() >>> shuffle...
import random def create_deck(): """ Returns a standard 52-card deck. """ ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] suits = ['hearts', 'diamonds', 'clubs', 'spades'] deck = [(rank, suit) for rank in ranks for suit in suits] return deck def shuffle_deck(deck...
import pytest from solution import create_deck, shuffle_deck, deal_cards, score_hand, determine_winner, simulate_game def test_create_deck(): deck = create_deck() assert len(deck) == 52 assert ('2', 'hearts') in deck assert ('A', 'spades') in deck def test_shuffle_deck(): deck = create_deck() ...
[ { "docstring": "Returns a standard 52-card deck.", "function_declaration": "def create_deck():", "function_name": "create_deck", "parameter_list": "()" }, { "docstring": "Shuffles the deck of cards in place.", "function_declaration": "def shuffle_deck(deck):", "function_name": "shuff...
[ 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 random\n\ndef create_deck():\n ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\n suits = ['hearts', 'diamonds', 'clubs', 'spades...
trial_gpt4o_1
{ "original_instruction": "#### Objective:\nTo test your understanding of the `random` module, particularly its ability to generate pseudo-random numbers for various distributions and manage the state of the random number generator.\n\n#### Problem Statement:\nYou are tasked with creating a mini-simulation of a card ...
0.668805
Docs: Python310_4638
C
[ "create_deck", "shuffle_deck", "deal_cards", "score_hand", "determine_winner", "simulate_game" ]
6
[ [ "determine_winner", "score_hand" ], [ "simulate_game", "create_deck" ], [ "simulate_game", "deal_cards" ], [ "simulate_game", "determine_winner" ], [ "simulate_game", "shuffle_deck" ] ]
5
[]
false
[]
false
pytest
true
[]
true
d7f3ac273f1a2ad4c27cf0ebde3ff309746cd6c5
b2517bb221a69f6f85561c087b76f8aa2587060c
v1.0
complete
Docs
Docs: Python310_5255_C
import asyncio import random async def simulate_task(task_name, duration): """ Simulates a task by sleeping for the given duration. Args: task_name (str): The name of the task. duration (int): The duration (in seconds) for which the task will run. Returns: str: A message indicatin...
import asyncio import random async def simulate_task(task_name, duration): """ Simulates a task by sleeping for the given duration. Args: task_name (str): The name of the task. duration (int): The duration (in seconds) for which the task will run. Returns: str: A message indicatin...
import pytest import asyncio from solution import simulate_task, run_tasks @pytest.mark.asyncio async def test_simulate_task(): result = await simulate_task("TestTask", 2) assert result == "Task TestTask completed in 2 seconds" @pytest.mark.asyncio async def test_run_tasks_all_complete(): task_names = ["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\nimport random\n\nasync def simulate_task(task_name, duration):\n \"\"\"\n Simulates a task by sleeping for the given duration.\n \n Args:\n ...
trial_gpt4o_0
{ "original_instruction": "### Asyncio Task Management & Concurrency Assessment\n\n**Objective**: Implement a Python function that demonstrates the use of `asyncio` for running multiple tasks concurrently, handling timeouts, and shielding tasks from cancellation.\n\n**Question**:\n\nYou are asked to develop an `async...
0.636476
Docs: Python310_5255
C
[ "simulate_task", "run_tasks", "main" ]
3
[ [ "run_tasks", "simulate_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5fe130f9840b5e20d2cef1ef90085316ea5b27f9
129ad55dd2ee7299689bb918e8f8c0b6e367783d
v1.0
complete
Docs
Docs: Python310_4381_C
import time import cProfile import pstats import io import tracemalloc from pdb import set_trace def complex_computation(arr): """ Perform a series of mathematical operations on a list of numbers. >>> complex_computation([1, 2, 3]) [value1, value2, value3] >>> complex_computation([]) [] """ ...
import time import cProfile import pstats import io import tracemalloc from pdb import set_trace def complex_computation(arr): result = [] for i in arr: time.sleep(0.1) # Simulate a time-consuming operation temp = i**2 for j in range(1000): temp = temp * 2 - temp // 3 ...
from solution import complex_computation, optimized_complex_computation, trace_memory def test_complex_computation(): assert complex_computation([1, 2, 3]) == optimized_complex_computation([1, 2, 3]) def test_empty_list(): assert complex_computation([]) == optimized_complex_computation([]) def test_large_num...
[ { "docstring": null, "function_declaration": "def complex_computation(arr):", "function_name": "complex_computation", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def profile_complex_computation(arr):", "function_name": "profile_complex_computation", ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cProfile\nimport pdb\nimport tracemalloc\nfrom typing import List\n\ndef complex_computation(arr: List[int]) -> List[int]:\n result = []\n for i in arr:\n ...
trial_gpt4o_8
{ "original_instruction": "#### Objective\nYou are tasked with writing a Python script that embodies the use of debugging and profiling tools to identify and resolve inefficiencies in a given function.\n\n#### Problem Statement\nYou are provided with a function, `complex_computation`, which performs a series of mathe...
0.489619
Docs: Python310_4381
C
[ "complex_computation", "profile_complex_computation", "optimized_complex_computation", "profile_optimized_computation", "debug_optimized_computation", "trace_memory" ]
6
[ [ "debug_optimized_computation", "optimized_complex_computation" ], [ "profile_complex_computation", "complex_computation" ], [ "profile_optimized_computation", "optimized_complex_computation" ] ]
3
[]
false
[]
false
pytest
true
[]
true
5db1df49cfe1def0ed7bf39813433e732cbefca0
c89cc2e26fa8fc5a340f53a5a2c13e03a9463645
v1.0
complete
Docs
Docs: Python310_5452_C
from itertools import filterfalse from functools import reduce from typing import List def process_primes(numbers: List[int]) -> int: """ Processes a list of integers to filter out prime numbers, square them, and return the sum of the squared prime numbers. >>> process_primes([1, 2, 3, 4, 5, 6, 7, 8, ...
from itertools import filterfalse from functools import reduce def is_prime(n): """ Returns True if n is a prime number, otherwise False. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False p = 3 while p * p <= n: if n % p == 0:...
from solution import process_primes def test_process_primes_with_example_input(): numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = process_primes(numbers) assert result == 87 def test_process_primes_with_no_primes(): numbers = [1, 4, 6, 8, 10] result = process_primes(numbers) assert result =...
[ { "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": "Processes a list of integers to filter out prime numbers, square them,\nand return the sum of the square...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import itertools\nimport functools\nimport math\n\ndef is_prime(n):\n \"\"\"\n Check if a number is a prime.\n \"\"\"\n if n <= 1:\n return False\n ...
trial_gpt4o_7
{ "original_instruction": "You are provided with a list of integers and tasked with performing the following operations using Python's functional programming modules (`itertools` and `functools`):\n\n1. Filter the list to include only prime numbers.\n2. Create a new list where each element is the square of the prime ...
0.651992
Docs: Python310_5452
C
[ "is_prime", "process_primes" ]
2
[ [ "process_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
959171de9670434818cd0f70fc1a50b8818fd103
6379c3578afb08e9e5c536795584622d270b0747
v1.0
complete
Docs
Docs: Python310_5367_C
def generate_function_signature(filename, function_name, line_number): """ Generate a function signature from provided details. >>> generate_function_signature("test_script.py", "func1", 4) 'test_script.py:func1:4' """ pass def format_entry_event(time, pid, event_type, filename, function_name, line...
def generate_function_signature(filename, function_name, line_number): return f"{filename}:{function_name}:{line_number}" def format_entry_event(time, pid, event_type, filename, function_name, line_number): timestamp = f"[{time}]" event_details = generate_function_signature(filename, function_name, line_nu...
def test_generate_function_signature(): signature = generate_function_signature("test_script.py", "func1", 4) assert signature == "test_script.py:func1:4" def test_format_entry_event(): formatted_event = format_entry_event("151080408", "12345", "function-entry", "test_script.py", "func1", 4) expected_o...
[ { "docstring": null, "function_declaration": "def generate_function_signature(filename, function_name, line_number):", "function_name": "generate_function_signature", "parameter_list": "(filename, function_name, line_number)" }, { "docstring": null, "function_declaration": "def format_en...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "systemtap\n# trace_functions.stp\nprobe process(\"python3.6\").mark(\"function__entry\") {\n printf(\"[%d] [%d] function-entry: %s %s %d\\n\",\n gettimeofday_...
trial_gpt4o_1
{ "original_instruction": "### Advanced Python Tracing with SystemTap\n\n**Objective:**\nYour task is to write a SystemTap script that traces the execution of a Python script's function calls and garbage collection activities. This problem will test your ability to understand and apply the given documentation on trac...
0.523812
Docs: Python310_5367
C
[ "generate_function_signature", "format_entry_event", "format_gc_event" ]
3
[ [ "format_entry_event", "generate_function_signature" ] ]
1
[]
false
[]
false
pytest
false
[]
true
63ad486709a720cb206acc068680932738a1d713
17415850136cacb71a64cfcb7999956dc84c4076
v1.0
complete
Docs
Docs: Python310_4829_C
from typing import List, Tuple def shuffle_deck(deck: List[str]) -> List[str]: """ Shuffles the deck of cards. Parameters: deck (List[str]): A list of card names. Returns: List[str]: A shuffled list of card names. >>> deck = ["5H", "2D", "KC", "9S", "AH", "7C"] >>> shuffl...
from typing import List, Tuple import random def shuffle_deck(deck: List[str]) -> List[str]: """ Shuffles the deck of cards. Parameters: deck (List[str]): A list of card names. Returns: List[str]: A shuffled list of card names. """ random.shuffle(deck) return deck def dra...
from solution import shuffle_deck, draw_card, simulate_game def test_shuffle_deck(): deck = ["5H", "2D", "KC", "9S", "AH", "7C"] shuffled_deck = shuffle_deck(deck.copy()) assert set(deck) == set(shuffled_deck) assert deck != shuffled_deck # Highly unlikely that shuffled deck would be the same def tes...
[ { "docstring": "Shuffles the deck of cards.\n\nParameters:\ndeck (List[str]): A list of card names.\n\nReturns:\nList[str]: A shuffled list of card names.", "function_declaration": "def shuffle_deck(deck):", "function_name": "shuffle_deck", "parameter_list": "(deck)" }, { "docstring": "Draws...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nimport random\n\ndef shuffle_deck(deck: List[str]) -> List[str]:\n \"\"\"\n Shuffles the deck of cards and returns it.\n \"\"\"...
trial_gpt4o_1
{ "original_instruction": "### Task\n\nYou are tasked with creating a simulation of a simplified card game where players draw cards until the deck is empty. Each player draws one card per turn from a shuffled deck and the game keeps track of the number of cards each player has drawn. At the end of the game, the playe...
0.687904
Docs: Python310_4829
C
[ "shuffle_deck", "draw_card", "simulate_game" ]
3
[ [ "simulate_game", "draw_card" ], [ "simulate_game", "shuffle_deck" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e2b3db97b67c9b62dbc74d5c006b94c776089db4
ad6ca80e387ebeefcaa5b0e306ccbbb78a27895d
v1.0
complete
Docs
Docs: Python310_4092_C
import time import sched # Create an instance of the scheduler scheduler = sched.scheduler(time.time, time.sleep) def schedule_event(event_time_or_delay: float, is_absolute: bool, priority: int, action: callable, args: tuple = (), kwargs: dict = {}) -> sched.Event: """ Schedule an event either at an absolute ...
import time import sched # Create an instance of the scheduler scheduler = sched.scheduler(time.time, time.sleep) def schedule_event(event_time_or_delay: float, is_absolute: bool, priority: int, action: callable, args: tuple = (), kwargs: dict = {}) -> sched.Event: """ Schedule an event either at an absolute ...
import time from solution import schedule_event, cancel_event, run_scheduler, schedule_recurring_event, scheduler def print_message(message): print(f"{time.time()}: {message}") def test_schedule_event(): # Clear any previous events while not scheduler.empty(): scheduler.run(False) event_time ...
[ { "docstring": "Schedule an event either at an absolute time or after a delay.\n\nParameters:\nevent_time_or_delay (float): The time at which the event should run (absolute if `is_absolute` is true or delay otherwise).\nis_absolute (bool): If true, the event_time_or_delay is treated as absolute time, otherwise ...
[ 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 sched\nimport time\n\n# Create scheduler instance\nscheduler = sched.scheduler(time.time, time.sleep)\n\ndef schedule_event(event_time_or_delay: float, is_absolu...
trial_gpt4o_1
{ "original_instruction": "<|Analysis Begin|>\n\nThe `sched` module in Python defines a `scheduler` class that provides a general-purpose event scheduler. This class allows scheduling of events to be executed at a specific time or after a delay. It requires two functions for operation: `timefunc` to get the current t...
0.612262
Docs: Python310_4092
C
[ "schedule_event", "cancel_event", "run_scheduler", "schedule_recurring_event" ]
4
[ [ "schedule_recurring_event", "schedule_event" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d842275b85ac2bc9768d8216f6a80a614e641493
4642e4306a98a34019bb66c17718e041c5453889
v1.0
complete
Docs
Docs: Python310_4499_C
import pickletools import pickle from typing import List def disassemble_pickle(pickle_data: bytes, annotate: int = 0) -> str: """ Disassembles the contents of pickle data and returns the symbolic disassembly. Args: pickle_data (bytes): A bytes object representing the pickled data. annotate (in...
import pickletools import pickle from typing import List def disassemble_pickle(pickle_data: bytes, annotate: int = 0) -> str: """ Disassembles the contents of pickle data and returns the symbolic disassembly. Args: pickle_data (bytes): A bytes object representing the pickled data. annotat...
from solution import disassemble_pickle, optimize_pickle, process_pickles import pytest def test_disassemble_pickle(): data = {'key': 'value'} pickle_data = pickle.dumps(data) disassembly = disassemble_pickle(pickle_data) assert "PROTO" in disassembly assert "STOP" in disassembly def test_optimize...
[ { "docstring": "Disassembles the contents of pickle data and returns the symbolic disassembly.\n\nArgs:\n pickle_data (bytes): A bytes object representing the pickled data.\n annotate (int): An optional integer specifying the annotation level (default is 0).\n\nReturns:\n str: A string containing the s...
[ 0, 0, 0, 1, 1, 0, 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 pickletools\nimport pickle\n\ndef disassemble_pickle(pickle_data: bytes, annotate: int = 0) -> str:\n \"\"\"\n Disassembles the pickle data and returns the...
trial_gpt4o_4
{ "original_instruction": "### Advanced Coding Assessment: Analyzing and Optimizing Pickle Files\n\n**Objective**: To assess your understanding of the `pickletools` module and your ability to manipulate and analyze pickled data programmatically.\n\n**Problem Statement**:\nYou are given the task of writing a Python sc...
0.617877
Docs: Python310_4499
C
[ "disassemble_pickle", "optimize_pickle", "process_pickles" ]
3
[ [ "process_pickles", "disassemble_pickle" ], [ "process_pickles", "optimize_pickle" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5131831672b04be461c44703dc6b57728d77b4b1
e1d1f87fb9c351c357bde1de12e56e5b2e969949
v1.0
complete
Docs
Docs: Seaborn_5026_C
import seaborn as sns import matplotlib.pyplot as plt def create_custom_palette(n_colors=6, start=0, rot=0.4, gamma=1.0, hue=0.8, dark=0.2, light=0.8, as_cmap=False): """ Generate a color palette using seaborn's cubehelix_palette function with the given parameters. Parameters: n_colors (int): ...
import seaborn as sns import matplotlib.pyplot as plt def create_custom_palette(n_colors=6, start=0, rot=0.4, gamma=1.0, hue=0.8, dark=0.2, light=0.8, as_cmap=False): """ Generates a color palette using seaborn's cubehelix_palette function with the given parameters. Parameters: n_colors (int):...
import pytest from solution import create_custom_palette def test_create_custom_palette_default(): palette = create_custom_palette() assert len(palette) == 6, "Default number of colors should be 6" def test_create_custom_palette_n_colors(): palette = create_custom_palette(n_colors=10) assert len(palet...
[ { "docstring": "Generates a color palette using seaborn's cubehelix_palette function with the given parameters.\n\nParameters:\n n_colors (int): Number of colors in the palette.\n start (float): Starting position in the cubehelix space.\n rot (float): Number of rotations around the hue wheel.\n gamm...
[ 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 seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef create_custom_palette(n_colors=6, start=0, rot=0.4, gamma=1.0, hue=0.8, dark=0.2, light=0.8, as_cmap=False...
trial_gpt4o_1
{ "original_instruction": "### Task\n\nYou are tasked with using seaborn’s `cubehelix_palette` function to generate customized color palettes and apply these palettes to visualizations. This task will test your understanding of the seaborn package, specifically around customized color map creation and applying these ...
0.676531
Docs: Seaborn_5026
C
[ "create_custom_palette", "create_plots" ]
2
[ [ "create_plots", "create_custom_palette" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "seaborn" ]
false
894b70543ecca6cad3cffa0242817d114deb6a8e
cddae02e95ac10db40901c4b9307a2a8f842b77f
v1.0
complete
Docs
Docs: Pytorch_5192_C
import torch import numpy as np import random def set_seeds(seed=42): """ Set seeds to ensure reproducibility across PyTorch, Python, and NumPy. """ torch.manual_seed(seed) random.seed(seed) np.random.seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) def configure_c...
import torch import torch.nn as nn import torch.optim as optim import numpy as np import random # 1. Set seeds to ensure reproducibility across PyTorch, Python, and NumPy. def set_seeds(seed=42): torch.manual_seed(seed) random.seed(seed) np.random.seed(seed) if torch.cuda.is_available(): torch....
from solution import train def test_reproducibility(): state_dict1, loss1 = train() state_dict2, loss2 = train() # Verify if the state dictionaries and losses are identical identical_parameters = all(torch.equal(state_dict1[key], state_dict2[key]) for key in state_dict1) identical_loss = loss1...
[]
[ 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, TensorDataset\nimport numpy as np\nimport random\n\n# Functio...
trial_gpt4o_6
{ "original_instruction": "**Question: Ensuring Reproducibility in PyTorch**\n\nYou have been provided with the task of developing a PyTorch script that ensures reproducible results across multiple runs of the script. Your script should utilize various methods to control sources of randomness and enforce deterministi...
0.645072
Docs: Pytorch_5192
C
[ "set_seeds", "configure_cuda", "train" ]
3
[ [ "train", "configure_cuda" ], [ "train", "set_seeds" ] ]
2
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "numpy", "torch" ]
false
727c343b4c66581ec180936b3a9cd996ca8f4369
3cd8b59655655c98253bb09bfb2f40f86e5be1d8
v1.0
complete
Docs
Docs: Python310_4736_C
import hashlib def compute_hash(message: bytes, algorithm: str, **kwargs) -> str: """ Computes and returns the hex digest of the provided message using the specified hash algorithm. Parameters: - message (bytes): The message to be hashed. - algorithm (str): The hash algorithm to use (e.g., 'sha256...
import hashlib def compute_hash(message: bytes, algorithm: str, **kwargs) -> str: """ Computes and returns the hex digest of the provided message using the specified hash algorithm. """ hash_func = hashlib.new(algorithm, **kwargs) hash_func.update(message) return hash_func.hexdigest() def sign...
import pytest from solution import compute_hash, sign_message, verify_message def test_compute_hash_sha256(): message = b"integrity check" expected_hash = hashlib.sha256(message).hexdigest() assert compute_hash(message, 'sha256') == expected_hash def test_sign_and_verify_valid_signature(): message = b...
[ { "docstring": "Computes and returns the hex digest of the provided message using the specified hash algorithm.", "function_declaration": "def compute_hash(message, algorithm, **kwargs):", "function_name": "compute_hash", "parameter_list": "(message, algorithm, **kwargs)" }, { "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 hashlib\n\ndef compute_hash(message: bytes, algorithm: str, **kwargs) -> str:\n \"\"\"\n Computes and returns the hex digest of the provided message using ...
trial_gpt4o_0
{ "original_instruction": "### Cryptographic Hashing and Verification System\n\nIn this task, you are required to implement a system that uses the `hashlib` library to compute and verify the integrity of messages using cryptographic hash functions. The system should support various hash algorithms, allow for keyed ha...
0.743834
Docs: Python310_4736
C
[ "compute_hash", "sign_message", "verify_message" ]
3
[ [ "verify_message", "sign_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8821e7aa8bf250fc446a2068087559fd0ba5a5a0
d450ddd1e7938d50d0d91aaa7187f1008da78845
v1.0
complete
Docs
Docs: Python310_4463_C
from typing import List, Dict import requests from concurrent.futures import ThreadPoolExecutor, as_completed def fetch_url(url: str) -> tuple: """ Fetches content from a URL. Args: url (str): The URL to fetch content from. Returns: tuple: A tuple containing the URL and th...
from typing import List, Dict import requests from concurrent.futures import ThreadPoolExecutor, as_completed def fetch_url(url: str) -> tuple: """ Fetches content from a URL. Args: url (str): The URL to fetch content from. Returns: tuple: A tuple containing the URL and th...
import pytest from unittest.mock import patch from solution import async_scrape, fetch_url def test_async_scrape_success(): urls = ["http://example.com", "http://example.org"] expected = { "http://example.com": "<html>Example Domain</html>", "http://example.org": "<html>Example Domain</html>" ...
[ { "docstring": "Fetches content from a URL.\n\nArgs:\n url (str): The URL to fetch content from.\n \nReturns:\n tuple: A tuple containing the URL and the response text or error message.", "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_list": "(url)" ...
[ 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 typing import List, Dict\nimport requests\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef fetch_url(url: str) -> (str, str):\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "### Asynchronous Web Scraping using `concurrent.futures`\n\n**Description:**\nYou need to implement a function `async_scrape(urls)` that accepts a list of URLs and asynchronously scrapes data from each URL. Use the `concurrent.futures.ThreadPoolExecutor` for this task. The function should r...
0.713027
Docs: Python310_4463
C
[ "fetch_url", "async_scrape" ]
2
[ [ "async_scrape", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
2be8b3d5e87201129510b4edf03d6fb534a1b01b
3ecd1038d625f2ccd0ea2b15725c0bc71d4b9fff
v1.0
complete
Docs
Docs: Python310_6171_C
def create_turtle_art(): """ Create a piece of turtle graphics art. This function sets up a screen, creates a turtle, and draws a series of colorful concentric shapes. It also implements an event listener to finish drawing when the 'q' key is pressed. Requirements: 1. The screen should be 800x6...
import turtle def draw_shape(t, sides, length): """ Draws a polygon with a specific number of sides and side length using the turtle object. """ angle = 360 / sides for _ in range(sides): t.forward(length) t.right(angle) def create_turtle_art(): screen = turtle.Screen() scr...
import pytest import turtle from solution import create_turtle_art def test_create_turtle_art_import(): """ Test if the create_turtle_art function can be imported without issues. """ assert create_turtle_art is not None @pytest.mark.skip(reason="Manual test required for graphical output and event hand...
[ { "docstring": "Draws a polygon with a specific number of sides and side length using the turtle object.", "function_declaration": "def draw_shape(t, sides, length):", "function_name": "draw_shape", "parameter_list": "(t, sides, length)" }, { "docstring": null, "function_declaration": "d...
[ 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 turtle\n\ndef create_turtle_art():\n # Set up the screen\n screen = turtle.Screen()\n screen.setup(width=800, height=600)\n screen.bgcolor('lightblue...
trial_gpt4o_4
{ "original_instruction": "### Turtle Graphics Art Creation\n\n#### Objective\nWrite a Python program using the `turtle` module to create a piece of turtle graphics art. The program should demonstrate your understanding of the following concepts:\n- Turtle motion and control\n- Pen settings and drawing\n- Screen sett...
0.779488
Docs: Python310_6171
C
[ "draw_shape", "create_turtle_art" ]
2
[ [ "create_turtle_art", "draw_shape" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bd311262c5134b9143fecb63289782745946d6c7
28bcf2a513b936b223420cebbf2fc0dd468812f3
v1.0
complete
Docs
Docs: Python310_6295_C
from typing import List, Dict def count_words_parallel(file_paths: List[str]) -> Dict[str, int]: """ Count the number of words in each file in parallel. :param file_paths: List of strings where each string is a path to a text file. :return: Dictionary with file paths as keys and word counts as val...
from typing import List, Dict import concurrent.futures def count_words_in_file(file_path: str) -> int: """ Helper function to count the number of words in a single file. """ try: with open(file_path, 'r', encoding='utf-8') as file: content = file.read() words = content....
from solution import count_words_parallel def test_count_words_parallel_single_file(): file_paths = ["test1.txt"] with open("test1.txt", "w") as file: file.write("Hello world") assert count_words_parallel(file_paths) == {"test1.txt": 2} def test_count_words_parallel_multiple_files(): file_path...
[ { "docstring": "Helper function to count the number of words in a single file.", "function_declaration": "def count_words_in_file(file_path):", "function_name": "count_words_in_file", "parameter_list": "(file_path)" }, { "docstring": "Count the number of words in each file in parallel.\n\n:p...
[ 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": "from concurrent.futures import ThreadPoolExecutor\nfrom typing import List, Dict\n\ndef count_words_in_file(file_path: str) -> int:\n \"\"\"\n Count the number of...
trial_gpt4o_4
{ "original_instruction": "### Question: Parallel File Processing with `concurrent.futures`\n\nYou are provided with a list of text file paths. Your task is to analyze each file to count the number of words it contains. Given the large number of files and their sizes, you should implement this word count using parall...
0.766819
Docs: Python310_6295
C
[ "count_words_in_file", "count_words_parallel" ]
2
[ [ "count_words_parallel", "count_words_in_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
89c5a7f5cc49f837ae398e993355317978d17949
255b8381314a1218e089fa90b1ac8c5a3ed27c1e
v1.0
complete
Docs
Docs: Python310_4647_C
from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List, Dict import requests def fetch_data_concurrently(urls: List[str], workers: int) -> Dict[str, str]: """ Fetch data from a list of URLs concurrently using the specified number of workers. Args: urls (List[str]):...
from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List, Dict import requests def fetch_content(url): try: response = requests.get(url) response.raise_for_status() # Raise an error for bad status codes return response.text except requests.RequestExceptio...
import pytest from unittest.mock import patch from solution import fetch_data_concurrently # Example URLs for mock testing example_urls = [ "http://example.com", "http://example.org", "http://example.net" ] example_content = [ "<html>Example Domain</html>", "<html>Example Organization</html>", ...
[ { "docstring": null, "function_declaration": "def fetch_content(url):", "function_name": "fetch_content", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def fetch_data_concurrently(urls, workers):", "function_name": "fetch_data_concurrently", "paramete...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List, Dict\nimport requests\n\ndef fetch_content(url):\n try:\n response =...
trial_gpt4o_0
{ "original_instruction": "**Title:** Concurrent Execution with concurrent.futures\n\n**Objective:** \nImplement a Python function that utilizes the concurrent.futures module to perform concurrent execution of tasks. This problem will test your understanding of managing parallel tasks using ThreadPoolExecutor or Proc...
0.66581
Docs: Python310_4647
C
[ "fetch_content", "fetch_data_concurrently" ]
2
[ [ "fetch_data_concurrently", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
59b4d86e7abc8812fb206ff0ab82d866c77932cb
60711dbeddc07d9cedd562579927206c027ba5e8
v1.0
complete
Docs
Docs: Pytorch_6109_C
import torch from typing import Callable def custom_relu(x: torch.Tensor, t: float) -> torch.Tensor: """ Apply a modified ReLU operation on the input tensor `x`. Parameters: - x (torch.Tensor): Input tensor on which the operation will be applied. - t (float): Threshold value. Values in the ten...
import torch from typing import Callable def custom_relu(x: torch.Tensor, t: float) -> torch.Tensor: """ Apply a modified ReLU operation on the input tensor `x`. Parameters: x (torch.Tensor): Input tensor on which the operation will be applied. t (float): Threshold value. Values in the tensor less...
from solution import custom_relu, convert_to_torchscript, test_custom_relu import torch def test_custom_relu_values(): x = torch.tensor([0.5, 2.0, -1.0, 3.5, 0.0, -0.5]) t = 1.0 expected = torch.tensor([0.0, 2.0, 0.0, 3.5, 0.0, 0.0]) result = custom_relu(x, t) assert torch.equal(expected, resu...
[ { "docstring": "Apply a modified ReLU operation on the input tensor `x`.\n\nParameters:\nx (torch.Tensor): Input tensor on which the operation will be applied.\nt (float): Threshold value. Values in the tensor less than t will be set to zero.\n\nReturns:\ntorch.Tensor: A tensor with the modified ReLU operation ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.jit\n\ndef custom_relu(x: torch.Tensor, t: float) -> torch.Tensor:\n \"\"\"\n Apply a modified ReLU operation on the input tensor `x`.\...
trial_gpt4o_2
{ "original_instruction": "### PyTorch and TorchScript Coding Assessment\n\n**Objective**: Write a function using PyTorch, convert it to TorchScript, and verify its correctness.\n\n**Problem Statement**:\n\nYou are given a task to implement a function in PyTorch that performs a specific operation on tensors and then ...
0.464293
Docs: Pytorch_6109
C
[ "custom_relu", "convert_to_torchscript", "test_custom_relu" ]
3
[ [ "test_custom_relu", "convert_to_torchscript" ], [ "test_custom_relu", "custom_relu" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
bd79ad09898ca6a018be7bfeaa984f5af344bdd4
1825a2832942fa7e382d6401525e3e2e0911602a
v1.0
complete
Docs
Docs: Python310_6223_C
import urllib.request import urllib.error def make_request(url: str) -> str: """Perform an HTTP GET request to the given URL and return the response content as a string. Handle errors as follows: - Raise a URLError and print "Failed to reach the server. Reason: [reason]" if the URL is incorrect or the...
import urllib.request import urllib.error def make_request(url: str) -> str: try: response = urllib.request.urlopen(url) content = response.read() return content.decode('utf-8') except urllib.error.HTTPError as e: print(f"HTTP Error {e.code}: {e.reason}") raise excep...
import pytest import urllib.error from solution import make_request, download_content def test_make_request_success(monkeypatch): class MockResponse: def read(self): return b"Example content" def decode(self, encoding): return "Example content" def mock_urlopen(url): ...
[ { "docstring": null, "function_declaration": "def make_request(url):", "function_name": "make_request", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def download_content(url, expected_length):", "function_name": "download_content", "parameter_list": ...
[ 0, 0, 0, 1, 0, 0, 1, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import urllib.request\nimport urllib.error\n\ndef make_request(url: str) -> str:\n try:\n response = urllib.request.urlopen(url)\n content = response.r...
trial_gpt4o_8
{ "original_instruction": "### **Problem Statement:**\n\nYou are tasked with writing a set of functions to handle HTTP requests and appropriately manage errors using the `urllib.error` module in Python.\n\n#### **Function 1: make_request**\n\nWrite a function `make_request(url: str) -> str` that performs an HTTP GET ...
0.681515
Docs: Python310_6223
C
[ "make_request", "download_content" ]
2
[ [ "download_content", "make_request" ] ]
1
[]
false
[]
false
pytest
true
[]
true
da1aa4833329dd8971f8e5aa3f7bb75415c182b5
08d2c7d5fafe6e48d7c390b795ce9d09ee4d482b
v1.0
complete
Docs
Docs: Python310_5057_C
import asyncio import platform import sys async def start_server_and_subprocess(): """Initialize the correct event loop and set up a server with appropriate sockets based on the platform, managing subprocesses effectively on both Windows and Unix-based systems. On Unix-based systems: - Use Unix D...
import asyncio import os import sys import platform async def handle_client(reader, writer): try: while True: data = await reader.read(100) if not data: break writer.write(data) await writer.drain() except asyncio.CancelledError: p...
import asyncio import os import platform import pytest import subprocess from solution import start_server_and_subprocess @pytest.mark.asyncio async def test_server_and_subprocess_unix(monkeypatch): if platform.system() == 'Windows': pytest.skip("Test is for Unix based systems") # Create a temporary U...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\nimport sys\nfrom asyncio.subprocess import create_subprocess_exec\n\nasync def handle_client(reader, writer):\n data = await reader....
trial_gpt4o_1
{ "original_instruction": "**Advanced Python Coding Assessment Question:**\n\n### Problem Statement\n\nYou are given the task of writing a networked application in Python, leveraging the `asyncio` module. Your application needs to function correctly across both Windows and macOS, taking into account specific limitati...
0.54449
Docs: Python310_5057
C
[ "handle_client", "start_server_and_subprocess" ]
2
[ [ "start_server_and_subprocess", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
00abf20e2f05fcd5efcaec52a57487ecf3a3ad2b
dc804085e47a13b3dd5df0a5b4c0a94309c3a2c9
v1.0
complete
Docs
Docs: Python310_5810_C
from typing import List, Dict import warnings def legacy_function(): # Example implementation generating warnings warnings.warn("This is a deprecation warning", DeprecationWarning) warnings.warn("This is a user warning", UserWarning) def manage_warnings(warning_conditions: List[Dict[str, str]], logging_li...
import warnings from typing import List, Dict def legacy_function(): # Example implementation generating warnings warnings.warn("This is a deprecation warning", DeprecationWarning) warnings.warn("This is a user warning", UserWarning) def manage_warnings(warning_conditions: List[Dict[str, str]], logging_li...
import warnings from solution import manage_warnings, legacy_function def test_manage_warnings(): warning_conditions = [ {"action": "error", "category": "DeprecationWarning", "message": "deprecation"} ] logging_list = [] try: manage_warnings(warning_conditions, logging_list) excep...
[ { "docstring": null, "function_declaration": "def legacy_function():", "function_name": "legacy_function", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def manage_warnings(warning_conditions, logging_list):", "function_name": "manage_warnings", "paramet...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import warnings\nfrom typing import List, Dict\n\ndef legacy_function():\n warnings.warn(\"This is a deprecation warning\", DeprecationWarning)\n warnings.warn(\"...
trial_gpt4o_8
{ "original_instruction": "**Objective:**\nThis coding challenge aims to assess your ability to work with Python's `warnings` module effectively. You are required to implement a function that manages and handles warnings for a given piece of legacy code.\n\n**Task:**\n\nYou are given a function `legacy_function()` in...
0.610914
Docs: Python310_5810
C
[ "legacy_function", "manage_warnings" ]
2
[ [ "manage_warnings", "legacy_function" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bb4e05a872e638cdfa72983c8165456c9124d1b4
877c6506f6299cbd4ee83e1580e265319bb3dda2
v1.0
complete
Docs
Docs: Pytorch_6032_C
import torch from torch import Tensor def custom_relu(x: Tensor) -> Tensor: """ Custom ReLU operation that replaces negative values with 0. >>> custom_relu(torch.tensor([-1.0, 0.0, 1.0, 2.0])) tensor([0.0, 0.0, 1.0, 2.0]) """ def test_custom_relu(): # Example input tensor x = torch.tensor(...
import torch from torch import Tensor # Step 1: Define the custom operation def custom_relu(x: Tensor) -> Tensor: return torch.maximum(x, torch.tensor(0., device=x.device)) # Step 2: Register the custom kernel (simplified for educational purposes, no OP Library used) # Normally, you might use torch.library.custom...
import pytest from torch import tensor, autograd from solution import custom_relu, test_custom_relu, test_custom_relu_grad def test_custom_relu_output(): x = tensor([-1.0, 0.0, 1.0, 2.0], requires_grad=True) y = custom_relu(x) expected = tensor([0.0, 0.0, 1.0, 2.0]) assert torch.equal(y, expected)...
[ { "docstring": null, "function_declaration": "def custom_relu(x):", "function_name": "custom_relu", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def test_custom_relu():", "function_name": "test_custom_relu", "parameter_list": "()" }, { "docstri...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.library\nfrom torch.autograd import Function, gradcheck\n\nclass CustomReLU(Function):\n @staticmethod\n def forward(ctx, x):\n ...
trial_gpt4o_8
{ "original_instruction": "### Question\n\n#### Objective:\nImplement a custom operation in PyTorch using the `torch.library.custom_op` function and test it using `torch.library.opcheck` and `torch.autograd.gradcheck` to ensure its correctness.\n\n#### Description:\nYou will create a custom operation `custom_relu` th...
0.518763
Docs: Pytorch_6032
C
[ "custom_relu", "test_custom_relu", "test_custom_relu_grad" ]
3
[ [ "test_custom_relu", "custom_relu" ], [ "test_custom_relu_grad", "custom_relu" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
cd7936791b332e60079a102bd596f24987063aaf
71c0b263f1474c0df5b705fa19b97d58de1872ab
v1.0
complete
Docs
Docs: Python310_5572_C
import contextvars import asyncio # Create the session_var ContextVar session_var = contextvars.ContextVar('session_var', default=None) def set_session(session_info): """ Set the session information in the context variable. Args: session_info (dict): A dictionary containing session information. ...
import contextvars import asyncio # Step 1: Create the session_var ContextVar session_var = contextvars.ContextVar('session_var', default=None) # Step 2: Implement session management functions def set_session(session_info): session_var.set(session_info) def get_session(): return session_var.get() # Step 3: ...
from solution import set_session, get_session, handle_session import pytest import asyncio async def mock_task(): session = get_session() return session def test_set_and_get_session(): session_info = {"user_id": 456, "token": "zxyabc"} set_session(session_info) assert get_session() == session_info...
[ { "docstring": null, "function_declaration": "def set_session(session_info):", "function_name": "set_session", "parameter_list": "(session_info)" }, { "docstring": null, "function_declaration": "def get_session():", "function_name": "get_session", "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 contextvars\nimport asyncio\n\n# Step 1: Create the session_var ContextVar\nsession_var = contextvars.ContextVar('session_var', default=None)\n\n# Step 2: Implem...
trial_gpt4o_0
{ "original_instruction": "### Question: Managing Context Variables in Asynchronous Python Code\n\nYou are tasked with developing a Python application that handles asynchronous tasks and manages context-local state using the `contextvars` module. Specifically, you need to create a context variable that tracks the cur...
0.466237
Docs: Python310_5572
C
[ "set_session", "get_session", "handle_session", "example_task", "main" ]
5
[ [ "example_task", "get_session" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cb8df7af8403c8441201ecd827f4aa04e6680b68
70ceb91c82ef52fb6b3cce095458a7dd818b864e
v1.0
complete
Docs
Docs: Python310_6420_C
import asyncio import time from typing import Callable, List, Tuple async def periodic_scheduler(tasks: List[Tuple[Callable, float]]) -> None: """ Implement an asynchronous job scheduler using asyncio. Tasks should be executed at their specific intervals and log their completion times. Args: ...
import asyncio import time from typing import Callable, List, Tuple async def log_execution(func: Callable): """ Log the execution of the function. """ await func() print(f"Task {func.__name__} executed at {time.time()}") async def periodic_task(func: Callable, interval: float): while True...
import asyncio import pytest from solution import periodic_scheduler log_data = [] async def mock_task1(): log_data.append(f"mock_task1 executed at {time.time()}") async def mock_task2(): log_data.append(f"mock_task2 executed at {time.time()}") @pytest.fixture def reset_log_data(): global log_data l...
[]
[ 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\nimport time\nfrom typing import Callable, List, Tuple\n\nasync def log_execution(func: Callable):\n \"\"\"\n Log the execution of the function.\n ...
trial_gpt4o_0
{ "original_instruction": "**Question:**\n\n### Implementing a Periodic Async Job Scheduler\n\nYou are required to create an asynchronous job scheduler in Python using `asyncio`, which will periodically execute a set of tasks and log their completion times. Each task should be executed at a specific interval, and th...
0.626083
Docs: Python310_6420
C
[ "log_execution", "periodic_task", "periodic_scheduler" ]
3
[ [ "periodic_scheduler", "periodic_task" ], [ "periodic_task", "log_execution" ] ]
2
[]
false
[]
false
pytest
true
[]
true
7c72c88fefbad5bc024d90c8825a8f18318f3baa
2c22c82418cae6ec9f1d6e161beb394b272b5ea4
v1.0
complete
Docs
Docs: Pytorch_5096_C
def basic_tensor_operations(): """ Perform basic tensor operations on an Intel GPU. The function checks if Intel GPU is available then creates a tensor, performs operations, and returns the result. If the Intel GPU is not available, it raises a runtime error. """ import torch # Implement bas...
import time import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms # Function for basic tensor operations on an Intel GPU def basic_tensor_operations(): if not torch.xpu.is_available(): raise RuntimeError("Intel GPU is not available") ...
import torch import pytest from solution import basic_tensor_operations, train_model, optimize_with_torch_compile, SimpleCNN @pytest.mark.skipif(not torch.xpu.is_available(), reason="Intel GPU is not available") def test_basic_tensor_operations(): result = basic_tensor_operations() assert result.device.type =...
[]
[ 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.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\n\ndef basic_tensor_operations():\n ...
trial_gpt4o_2
{ "original_instruction": "#### Objective\n\nThe objective of this task is to evaluate your understanding and proficiency with PyTorch, specifically using Intel GPUs. You are required to implement a training routine for a deep learning model and optimize its performance using `torch.compile`.\n\n#### Problem Statemen...
0.608951
Docs: Pytorch_5096
C
[ "basic_tensor_operations", "train_model", "optimize_with_torch_compile" ]
3
[ [ "optimize_with_torch_compile", "train_model" ] ]
1
[]
false
[ "SimpleCNN" ]
true
pytest
true
[ "torch", "torchvision" ]
false
0775d5926d08a66309288d774e9f83d8b8bf95b8
ef551b80e981f0a888dbc592b604b840ac407651
v1.0
complete
Docs
Docs: Python310_5890_C
def perform_calculation(num1, num2, operator): """ This function performs basic arithmetic operations. :param num1: First number (integer) :param num2: Second number (integer) :param operator: A string that can be one of '+', '-', '*', '/' :return: The result of the operation as a float ...
def perform_calculation(num1, num2, operator): """ This function performs basic arithmetic operations. :param num1: First number (integer) :param num2: Second number (integer) :param operator: A string that can be one of '+', '-', '*', '/' :return: The result of the operation as a float ...
from solution import perform_calculation def test_perform_calculation_addition(): assert perform_calculation(3, 4, '+') == 7.0 def test_perform_calculation_subtraction(): assert perform_calculation(10, 4, '-') == 6.0 def test_perform_calculation_multiplication(): assert perform_calculation(3, 5, '*') == ...
[ { "docstring": "This function performs basic arithmetic operations.\n\n:param num1: First number (integer)\n:param num2: Second number (integer)\n:param operator: A string that can be one of '+', '-', '*', '/'\n:return: The result of the operation as a float\n:raises ValueError: If operator is not one of the sp...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def perform_calculation(num1, num2, operator):\n \"\"\"\n This function performs basic arithmetic operations.\n \n :param num1: First number (integer)\n ...
trial_gpt4o_0
{ "original_instruction": "## Task\nYou are required to create an application that simulates a simple calculator. The calculator should take two numbers and an operator as input and perform the corresponding mathematical operation. You must handle potential errors such as invalid inputs and division by zero, and ensu...
0.707768
Docs: Python310_5890
C
[ "perform_calculation", "calculator" ]
2
[ [ "calculator", "perform_calculation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b27c6545aa51bba07e2598ef7ddf41e9f3d15691
45917c43a657a18b95d8b7a43b437ac39ec30b96
v1.0
complete
Docs
Docs: Scikit_5822_C
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(file_path: str): """ Generator function to yield instances from the file. Each line in the file represents a single instance in the format ...
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(file_path: str): """ Generator function to yield instances from the file. Each line in the file represents a single instance in the format ...
import pytest from solution import stream_data, train_and_evaluate def test_stream_data(tmp_path): # Create a temporary file with test data test_data = "0\ttext one\n1\ttext two\n0\ttext three\n" test_file = tmp_path / "test_stream_data.txt" test_file.write_text(test_data) result = list(stream...
[ { "docstring": "Generator function to yield instances from the file.\nEach line in the file represents a single instance in the format <label> <text>.", "function_declaration": "def stream_data(file_path):", "function_name": "stream_data", "parameter_list": "(file_path)" }, { "docstring":...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\n\ndef stream_...
trial_gpt4o_0
{ "original_instruction": "Out-of-Core Text Classification\n\nIn this exercise, you are required to implement an out-of-core learning system using scikit-learn. The system should train a classifier incrementally on text data that is too large to fit into memory.\n\n#### Task:\n1. **Data Streaming**: Implement a gener...
0.641156
Docs: Scikit_5822
C
[ "stream_data", "train_and_evaluate" ]
2
[ [ "train_and_evaluate", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
4bb812b3d692d29a58b6d4681d83dac1c476b10d
1b70ea012072e4c58506cfb5cc44015f6cabe40e
v1.0
complete
Docs
Docs: Python310_5806_C
import threading import struct from collections import deque from typing import List, Dict, Tuple, Union class ThreadSafeRecords: """Thread-safe custom data structure to store records.""" def __init__(self): self.records = deque() self.lock = threading.Lock() def add_record(self, record: D...
import threading import struct from collections import deque from typing import List, Dict, Tuple, Union class ThreadSafeRecords: def __init__(self): self.records = deque() self.lock = threading.Lock() def add_record(self, record: Dict[str, Union[int, bytes]]): with self.lock: ...
import pytest from solution import ThreadSafeRecords, read_and_process_binary_file, compute_average_data_length, find_latest_record def test_thread_safe_records(): records = ThreadSafeRecords() record1 = {'record_id': 1, 'timestamp': 1234567890, 'data': b'test1'} record2 = {'record_id': 2, 'timestamp': 123...
[]
[ 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 threading\nimport struct\nfrom collections import deque, defaultdict\nfrom typing import Dict, Any\n\n# Thread-safe custom data structure\nclass RecordStore:\n ...
trial_gpt4o_3
{ "original_instruction": "**Problem Statement:**\n\nYou are tasked with developing a Python program that reads a binary file, processes the data to extract meaningful information, stores the results in a custom data structure, and performs computations on the data. The program must also use multithreading to enhance...
0.486254
Docs: Python310_5806
C
[ "parse_record", "process_file_segment", "read_and_process_binary_file", "compute_average_data_length", "find_latest_record" ]
5
[ [ "process_file_segment", "parse_record" ] ]
1
[]
false
[ "ThreadSafeRecords" ]
true
pytest
true
[]
true
87e2082790249f5b23876e3640accdb378156f58
b16de0ec045fb029c259865f9eb96ac570fdd2ce
v1.0
complete
Docs
Docs: Scikit_4868_C
import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.semi_supervised import SelfTrainingClassifier, LabelPropagation from sklearn.metrics import accuracy_score, precision_score, recall_score def load_data(file_path: str) -> pd.DataFrame: """ Load the dataset from a CSV file. ...
import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.semi_supervised import SelfTrainingClassifier, LabelPropagation from sklearn.metrics import accuracy_score, precision_score, recall_score from sklearn.model_selection import train_test_split def load_data(file_path: str) -> pd.DataFra...
import pytest import os def create_sample_data(): """ Create sample data for testing. """ data = { 'X1': [1, 2, 3, 4, 5, 6], 'X2': [6, 5, 4, 3, 2, 1], 'Y': [1, -1, -1, 0, 1, 0] } df = pd.DataFrame(data) df.to_csv('points.csv', index=False) def test_load_data(): ...
[ { "docstring": "Load the dataset from a CSV file.\n\n:param file_path: Path to the CSV file.\n:return: DataFrame with columns ['X1', 'X2', 'Y'].", "function_declaration": "def load_data(file_path):", "function_name": "load_data", "parameter_list": "(file_path)" }, { "docstring": "Train a Sel...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.semi_supervised import SelfTrainingClassifier, LabelPropagation\nfrom sklearn.met...
trial_gpt4o_2
{ "original_instruction": "### Semi-supervised Learning Implementation and Comparison\n\n**Objective**: Implement and compare two semi-supervised learning techniques, `SelfTrainingClassifier` and `LabelPropagation`, from the `sklearn.semi_supervised` module using a synthetic dataset.\n\n**Background**:\nYou are provi...
0.709776
Docs: Scikit_4868
C
[ "load_data", "train_self_training_classifier", "train_label_propagation", "evaluate_model", "compare_models" ]
5
[ [ "compare_models", "evaluate_model" ], [ "compare_models", "train_label_propagation" ], [ "compare_models", "train_self_training_classifier" ] ]
3
[]
false
[]
false
pytest
false
[ "pandas", "sklearn" ]
false
eb6176fe3bc9ea6fabb7aec047d37e81a9075297
a14503f78b7f536d124cfe4d99f9d78f8435cab4
v1.0
complete
Docs
Docs: Scikit_5850_C
import pandas as pd from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score, roc_auc_score def sgd_classifier_pipeline(filepat...
import pandas as pd from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score, roc_auc_score def load_data(filepath): """ ...
import pandas as pd import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from solution import sgd_classifier_pipeline, load_data, split_data, create_pipeline, define_param_grid, perform_grid_search, evaluate_model def create_test_data(): """ C...
[ { "docstring": "Load the dataset from the given filepath.", "function_declaration": "def load_data(filepath):", "function_name": "load_data", "parameter_list": "(filepath)" }, { "docstring": "Split the dataset into training and testing sets.", "function_declaration": "def split_data(data...
[ 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import ...
trial_gpt4o_9
{ "original_instruction": "**Objective**: Implement and evaluate an `SGDClassifier` to solve a binary classification problem using a given dataset, focusing on hyperparameter optimization and performance evaluation.\n\n#### Question\nYou are provided with a dataset `data.csv` containing features (numerical) and a tar...
0.723059
Docs: Scikit_5850
C
[ "load_data", "split_data", "create_pipeline", "define_param_grid", "perform_grid_search", "evaluate_model", "sgd_classifier_pipeline" ]
7
[ [ "sgd_classifier_pipeline", "create_pipeline" ], [ "sgd_classifier_pipeline", "define_param_grid" ], [ "sgd_classifier_pipeline", "evaluate_model" ], [ "sgd_classifier_pipeline", "load_data" ], [ "sgd_classifier_pipeline", "perform_grid_search" ], [ "...
6
[]
false
[]
false
pytest
true
[ "numpy", "pandas", "sklearn" ]
false
56b331df499b978ca42b62ffe2533f1a85f80bec
19c255bb30f1bf9c6e8ec67728cf616eff413ab0
v1.0
complete
Docs
Docs: Python310_5080_C
import sys import ctypes class PyConfig(ctypes.Structure): _fields_ = [ ("program_name", ctypes.c_wchar_p), ("home", ctypes.c_wchar_p), ("executable", ctypes.c_wchar_p), ] class PyWideStringList(ctypes.Structure): _fields_ = [ ("length", ctypes.c_int), ("items", cty...
import sys import ctypes class PyConfig(ctypes.Structure): _fields_ = [ ("program_name", ctypes.c_wchar_p), ("home", ctypes.c_wchar_p), ("executable", ctypes.c_wchar_p), ] class PyWideStringList(ctypes.Structure): _fields_ = [ ("length", ctypes.c_int), ("items", cty...
def test_pyconfig_initialization(): config = PyConfig() PyConfig_InitPythonConfig(config) assert config.program_name == "custom_program" assert config.home == "custom_home" assert config.executable == "custom_executable" def test_pywidestringlist_initialization(): wide_string_list = PyWide...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\nfrom ctypes import c_wchar_p, c_int, POINTER, Structure, byref, windll, wstring_at\n\nclass PyWideStringList(Structure):\n _fields_ = [(\"length\", c_int...
trial_gpt4o_8
{ "original_instruction": "### Configuration and Initialization in Python\n\n**Objective:**\nImplement and customize Python initialization using the `PyConfig` and `PyWideStringList` structures. This task will assess your ability to manipulate configuration settings, manage wide string lists, and handle initializatio...
0.514636
Docs: Python310_5080
C
[ "PyConfig_InitPythonConfig", "PyWideStringList_Init", "check_status", "init_python_configuration" ]
4
[ [ "init_python_configuration", "PyConfig_InitPythonConfig" ], [ "init_python_configuration", "PyWideStringList_Init" ], [ "init_python_configuration", "check_status" ] ]
3
[]
false
[ "PyConfig", "PyWideStringList", "PyStatus" ]
true
pytest
false
[]
true
ca285aa0a876b283f46a73245485e2852ff5471a
7c64241572be0e162c5285d793a5fdc43ca0d2da
v1.0
complete
Docs
Docs: Python310_6309_C
def encode_to_custom_hex(text: str) -> str: """ Encodes a given text to a custom-hex encoded string. >>> encode_to_custom_hex("Hello") == '48-65-6c-6c-6f' >>> encode_to_custom_hex(" ") == '20' >>> encode_to_custom_hex("A") == '41' >>> encode_to_custom_hex("Aa") == '41-61' """ pass def d...
import codecs def encode_to_custom_hex(text: str) -> str: """ Encodes a given text to a custom-hex encoded string. """ return '-'.join(f'{ord(char):02x}' for char in text) def custom_ignore_error(exception: UnicodeError): """ Custom ignore error handler. """ return ('', exception.end) ...
from solution import encode_to_custom_hex, decode_from_custom_hex def test_encode_to_custom_hex(): assert encode_to_custom_hex("Hello") == "48-65-6c-6c-6f" assert encode_to_custom_hex(" ") == "20" assert encode_to_custom_hex("A") == "41" assert encode_to_custom_hex("Aa") == "41-61" def test_decode_fro...
[ { "docstring": "Encodes a given text to a custom-hex encoded string.", "function_declaration": "def encode_to_custom_hex(text):", "function_name": "encode_to_custom_hex", "parameter_list": "(text)" }, { "docstring": "Custom ignore error handler.", "function_declaration": "def custom_igno...
[ 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 codecs\n\ndef encode_to_custom_hex(text: str) -> str:\n \"\"\"\n Encodes a given text to a custom-hex encoded string.\n \"\"\"\n return '-'.join(f'{o...
trial_gpt4o_0
{ "original_instruction": "<|Analysis Begin|>\n\nThe provided documentation is extensive and detailed, covering the `codecs` module in Python, which handles various encoding and decoding tasks, including text encodings, byte encodings, error handling, and more.\n\nKey aspects of the `codecs` module:\n1. **Basic Funct...
0.768397
Docs: Python310_6309
C
[ "encode_to_custom_hex", "custom_ignore_error", "custom_replace_error", "decode_from_custom_hex" ]
4
[ [ "decode_from_custom_hex", "custom_ignore_error" ], [ "decode_from_custom_hex", "custom_replace_error" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1d725eac61f9c97e18a9eb34f8773b9c56705e50
509fc68831861ab6edb402b8617bae108f3eeb7a
v1.0
complete
Docs
Docs: Python310_6360_C
def process_experiment_data(data): """ Processes a list of experimental data points and returns various mathematical calculations. Args: data (List[Tuple[float, float]]): A list of tuples where each tuple represents the coordinates of a point (x, y) with angle values in degrees. Returns: ...
import math from math import gcd from functools import reduce def lcm(a, b): return abs(a * b) // gcd(a, b) def process_experiment_data(data): # Convert degrees to radians normalized_data = [(math.radians(x), math.radians(y)) for x, y in data] # Calculate Euclidean distances distances = [] ...
from solution import process_experiment_data import pytest def test_normalized_data(): data = [ (0.0, 0.0), (180.0, 90.0) ] result = process_experiment_data(data) expected_normalized_data = [ (0.0, 0.0), (math.pi, math.pi / 2) ] assert result['normalized_data'] =...
[ { "docstring": null, "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def process_experiment_data(data):", "function_name": "process_experiment_data", "parameter_list": "(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 math\nfrom functools import reduce\nfrom math import gcd\n\ndef normalize_data(data):\n return [(math.radians(x), math.radians(y)) for x, y in data]\n\ndef eu...
trial_gpt4o_3
{ "original_instruction": "You are provided with a series of physics experiments recording different values, and you need to process the data using various mathematical calculations. Implement a function `process_experiment_data(data)` that performs the following steps:\n\n1. **Normalize the Data**: Normalize the rec...
0.595163
Docs: Python310_6360
C
[ "lcm", "process_experiment_data" ]
2
[ [ "process_experiment_data", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9bf1061fcddb1ed24bf6df78d094c80bd425585c
7202d51df252e291b3fbb56010a625e62883a4f8
v1.0
complete
Docs
Docs: Python310_6029_C
from email.charset import Charset, add_charset, QP, BASE64 def setup_custom_charset(input_charset: str, header_enc: str, body_enc: str, output_charset: str) -> Charset: """ Registers a custom charset and returns a Charset instance. """ pass def encode_email_parts(charset_instance: Charset, header: str...
from email.charset import Charset, add_charset, QP, BASE64 def setup_custom_charset(input_charset: str, header_enc: str, body_enc: str, output_charset: str): """ Registers a custom charset and returns a Charset instance. """ header_enc_map = { 'quoted-printable': QP, 'base64': BASE64, ...
import pytest from solution import setup_custom_charset, encode_email_parts, test_custom_charset def test_setup_custom_charset(): charset_instance = setup_custom_charset("iso-8859-1", "quoted-printable", "base64", "utf-8") assert charset_instance.input_charset == "iso-8859-1" assert charset_instance.header...
[ { "docstring": "Registers a custom charset and returns a Charset instance.", "function_declaration": "def setup_custom_charset(input_charset, header_enc, body_enc, output_charset):", "function_name": "setup_custom_charset", "parameter_list": "(input_charset, header_enc, body_enc, output_charset)" ...
[ 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 email.charset\n\ndef setup_custom_charset(input_charset, header_enc, body_enc, output_charset):\n \"\"\"\n Registers a new charset with specified encoding ...
trial_gpt4o_7
{ "original_instruction": "**Question: Implementing and Testing Custom Charset Handling in Emails**\n\nBackground:\nIn email communication, different character sets may require different encodings for compatibility and proper handling. In particular, headers and bodies in emails might need specific encodings like quo...
0.591007
Docs: Python310_6029
C
[ "setup_custom_charset", "encode_email_parts", "test_custom_charset" ]
3
[ [ "test_custom_charset", "encode_email_parts" ], [ "test_custom_charset", "setup_custom_charset" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b00340dfc77833b97cc799f0bb11f93bd4e50b37
beafc8bd3e5ff4994fc3625f8efdca03f4ba6579
v1.0
complete
Docs
Docs: Python310_6985_C
from contextlib import contextmanager @contextmanager def managed_file(filename, mode): """ Context manager to open, yield, and then close a file. Ensures the file is closed even if an exception occurs. """ # Your implementation here def write_to_file(filename, content): """ Writes the spe...
from contextlib import contextmanager @contextmanager def managed_file(filename, mode): """ Context manager to open, yield, and then close a file. Ensures the file is closed even if an exception occurs. """ f = open(filename, mode) try: yield f finally: f.close() def write_...
from solution import managed_file, write_to_file import os def test_managed_file(): # Test that the file is opened and closed properly with managed_file('test.txt', 'w') as f: f.write('Test content') assert os.path.exists('test.txt'), "File was not created by managed_file." # Test that it thro...
[ { "docstring": "Context manager to open, yield, and then close a file.\nEnsures the file is closed even if an exception occurs.", "function_declaration": "def managed_file(filename, mode):", "function_name": "managed_file", "parameter_list": "(filename, mode)" }, { "docstring": "Writes the s...
[ 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 contextlib import contextmanager\n\n@contextmanager\ndef managed_file(filename, mode):\n \"\"\"\n A context manager to handle opening and closing of a file.\...
trial_gpt4o_2
{ "original_instruction": "### Question: Context Managers in `contextlib`\n\n#### Objective:\nCreate a custom context manager using the `contextlib.contextmanager` decorator to manage a resource. Additionally, implement a synchronous function that makes use of this context manager to demonstrate its utility.\n\n#### ...
0.480235
Docs: Python310_6985
C
[ "managed_file", "write_to_file" ]
2
[ [ "write_to_file", "managed_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1e6042bc21233c25bc4dfef0c57bb7bfa3a205e0
89ed922081c55552d4cc9532e4e031472f99024e
v1.0
complete
Docs
Docs: Scikit_4560_C
import numpy as np from sklearn.mixture import GaussianMixture, BayesianGaussianMixture import matplotlib.pyplot as plt from matplotlib.patches import Ellipse def generate_data(seed=42) -> np.ndarray: """ Generate a synthetic dataset with 500 samples in 2D space, composed of three distinct Gaussian clusters. ...
import numpy as np from sklearn.mixture import GaussianMixture, BayesianGaussianMixture import matplotlib.pyplot as plt from matplotlib.patches import Ellipse # Data Generation def generate_data(seed=42): np.random.seed(seed) means = [[2, 2], [-2, -2], [2, -2]] covariances = [[[1, 0.5], [0.5, 1]], [[1, -0....
import numpy as np from sklearn.mixture import GaussianMixture, BayesianGaussianMixture def test_generate_data(): X = generate_data() assert X.shape == (450, 2) # 3 clusters x 150 points each in 2D def test_fit_gaussian_mixture(): X = generate_data() gmm, optimal_components = fit_gaussian_mixture(X) ...
[ { "docstring": null, "function_declaration": "def generate_data(seed=42):", "function_name": "generate_data", "parameter_list": "(seed=42)" }, { "docstring": null, "function_declaration": "def fit_gaussian_mixture(X, max_components=10, random_state=42):", "function_name": "fit_gaussi...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.mixture import GaussianMixture, BayesianGaussianMixture\nfrom matplotlib.patches import Ellipse\n\ndef...
trial_gpt4o_3
{ "original_instruction": "### Gaussian Mixture Model Implementation and Analysis\n\n**Objective:**\nImplement and analyze Gaussian Mixture Models using Scikit-learn’s `sklearn.mixture` package to demonstrate your understanding of the concepts and functionalities discussed in the document.\n\n**Tasks:**\n\n1. **Data ...
0.594581
Docs: Scikit_4560
C
[ "generate_data", "fit_gaussian_mixture", "fit_bayesian_gaussian_mixture", "draw_ellipse", "plot_gmm", "main" ]
6
[ [ "plot_gmm", "draw_ellipse" ] ]
1
[]
false
[]
false
pytest
false
[ "matplotlib", "numpy", "sklearn" ]
false
68527bcfbedf92e500551998699a224f5bcef3e0
0ce75eacbc657743cef1295fa8d48a8af7f9b6a2
v1.0
complete
Docs
Docs: Python310_6508_C
import signal import threading import time def signal_handler(signum, frame): """ Handle the signal and raise TimeoutError when SIGALRM is received. Params: signum (int): The signal number. frame (frame object): Current stack frame. """ print(f"Signal handler called with signal {signum}...
import signal import threading import time def signal_handler(signum, frame): print(f"Signal handler called with signal {signum}") raise TimeoutError("Computation took too long!") def long_computation(): try: for i in range(1, 100): print(f"Computation step {i}") time.sleep...
import signal import time import threading from solution import run_with_timeout def test_run_with_timeout_completes_within_time(): def mock_long_computation(): print("Mock short computation started") time.sleep(1) print("Mock short computation finished") run_with_timeout(2) # The...
[ { "docstring": null, "function_declaration": "def signal_handler(signum, frame):", "function_name": "signal_handler", "parameter_list": "(signum, frame)" }, { "docstring": null, "function_declaration": "def long_computation():", "function_name": "long_computation", "parameter_lis...
[ 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 signal\nimport threading\nimport time\n\ndef signal_handler(signum, frame):\n \"\"\"\n Signal handler for SIGALRM.\n Raises a TimeoutError when invoked....
trial_gpt4o_1
{ "original_instruction": "**Objective**: Implement a Python function to safely handle an asynchronous event in a multithreaded environment using the `signal` module.\n\n#### Task\n\nYou are required to write a program that:\n\n1. Sets up a signal handler for `SIGALRM` that performs a specific task.\n2. Creates and s...
0.619369
Docs: Python310_6508
C
[ "signal_handler", "long_computation", "run_with_timeout" ]
3
[ [ "run_with_timeout", "signal_handler" ] ]
1
[]
false
[]
false
pytest
true
[]
true
83252d610003dbc9ca906dcce54fc7176bc321f4
45e280728bf333109cbfe320d7d18e2db67519e0
v1.0
complete
Docs
Docs: Python310_5133_C
import math from typing import List, Tuple def clean_data(data: List[float]) -> List[float]: """ Removes any non-finite numbers (such as NaN, inf, -inf) from the data. Args: data (List[float]): The list of temperature data to be cleaned. Returns: List[float]: The cleaned list...
import math from typing import List, Tuple def clean_data(data: List[float]) -> List[float]: """ Cleans the input data by removing all non-finite numbers (NaN, inf, -inf). """ return [x for x in data if math.isfinite(x)] def calculate_statistics(data: List[float]) -> Tuple[float, float, float, float...
from solution import clean_data, calculate_statistics, weekly_temperature_analysis def test_clean_data(): assert clean_data([1.0, math.nan, 2.0, math.inf, -math.inf, 3.0]) == [1.0, 2.0, 3.0] assert clean_data([math.nan, math.inf, -math.inf]) == [] assert clean_data([7.7, 8.8, 9.9]) == [7.7, 8.8, 9.9] de...
[ { "docstring": "Cleans the input data by removing all non-finite numbers (NaN, inf, -inf).", "function_declaration": "def clean_data(data):", "function_name": "clean_data", "parameter_list": "(data)" }, { "docstring": "Calculates the following statistics from the given data:\n- Mean\n- Stand...
[ 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 math\nfrom typing import List, Tuple\n\ndef clean_data(data: List[float]) -> List[float]:\n \"\"\"\n Removes non-finite numbers (NaN, inf, -inf) from the l...
trial_gpt4o_1
{ "original_instruction": "**Problem:** \n\nYou are working on a scientific project that involves analyzing temperature data collected from various sources globally. Given the temperature readings for a week from different monitoring stations, you need to preprocess and analyze this data. This problem involves severa...
0.745437
Docs: Python310_5133
C
[ "clean_data", "calculate_statistics", "weekly_temperature_analysis" ]
3
[ [ "weekly_temperature_analysis", "calculate_statistics" ], [ "weekly_temperature_analysis", "clean_data" ] ]
2
[]
false
[]
false
pytest
true
[]
true
203241af7b62b35a19296789f7773ecac17f82ff
273e91345d6b9cfe753fc5a1ecf1dcce8038a0c0
v1.0
complete
Docs
Docs: Python310_5892_C
def flatten_nested_list(nested_list): """ Flattens a nested list into a single-level list. Parameters: nested_list (list): A nested list of arbitrary depth. Returns: list: A flattened single-level list. Example: >>> flatten_nested_list([1, [2, [3, 4], 5], [6, 7]]) [1, ...
def flatten_nested_list(nested_list): """ Flattens a nested list into a single-level list. Parameters: nested_list (list): A nested list of arbitrary depth. Returns: list: A flattened single-level list. """ flattened_list = [] def flatten(sublist): for item in ...
import pytest from solution import flatten_nested_list, unique_values, nested_dict_construction def test_flatten_nested_list(): assert flatten_nested_list([1, [2, [3, 4], 5], [6, 7]]) == [1, 2, 3, 4, 5, 6, 7] assert flatten_nested_list([1, [2, 3]]) == [1, 2, 3] assert flatten_nested_list([1]) == [1] as...
[ { "docstring": "Flattens a nested list into a single-level list.\n\nParameters:\nnested_list (list): A nested list of arbitrary depth.\n\nReturns:\nlist: A flattened single-level list.", "function_declaration": "def flatten_nested_list(nested_list):", "function_name": "flatten_nested_list", "paramet...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def flatten_nested_list(nested_list):\n \"\"\"\n Flattens a nested list into a single-level list.\n \n Parameters:\n nested_list (list): A nested list of...
trial_gpt4o_2
{ "original_instruction": "### Comprehensive List Manipulation and Data Extraction\n\nYou are asked to write a series of functions to manipulate and extract data from nested lists, combining fundamentals of list operations, comprehensions, and set/dictionary use.\n\n#### Function 1: Flatten Nested List\n\nWrite a fun...
0.639339
Docs: Python310_5892
C
[ "flatten_nested_list", "unique_values", "nested_dict_construction" ]
3
[ [ "unique_values", "flatten_nested_list" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1a02804583318ca1047ff82d44f15de302134114
071835117594209f99f0c3652ed5f5182b66e020
v1.0
complete
Docs
Docs: Pytorch_5639_C
import torch import torch.nn as nn import torch.distributed as dist from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.utils.data import DataLoader, DistributedSampler import torchvision.datasets as datasets import torchvision.transforms as transforms # Define the simple neural network clas...
import torch import torch.nn as nn import torch.distributed as dist from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.utils.data import DataLoader, DistributedSampler import torchvision.datasets as datasets import torchvision.transforms as transforms # 1. Define the simple neural network ...
def test_network_architecture(): model = SimpleNN() assert isinstance(model.fc1, nn.Linear) assert model.fc1.in_features == 784 assert model.fc1.out_features == 256 assert isinstance(model.fc2, nn.Linear) assert model.fc2.in_features == 256 assert model.fc2.out_features == 128 assert isi...
[]
[ 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.nn as nn\nimport torch.distributed as dist\nfrom torch.distributed.fsdp import fully_shard, FlattenParamsWrapper\nfrom torch.utils.data impor...
trial_gpt4o_6
{ "original_instruction": "**Question:**\n\nYou are provided with the code for a simple neural network implemented in PyTorch. Your task is to modify this neural network to use FSDP2 (Fully Sharded Data Parallelism 2) for distributed training. Follow these steps:\n\n1. Implement a basic fully connected neural network...
0.612337
Docs: Pytorch_5639
C
[ "setup_model", "init_distributed", "train" ]
3
[ [ "train", "init_distributed" ], [ "train", "setup_model" ] ]
2
[]
false
[ "SimpleNN" ]
true
pytest
false
[ "torch", "torchvision" ]
false
478099e10d2b70c5e929951ba00b24cf135c2896
3dde8c38363dd81d4124ef53ea8cbcd6fa134c0e
v1.0
complete
Docs
Docs: Python310_5622_C
import pickle import sqlite3 class User: def __init__(self, name: str, age: int, email: str): self.name = name self.age = age self.email = email def serialize_user(user: User) -> bytes: """Serialize User object to bytes using pickle.""" pass def deserialize_user(user_data: bytes) ...
import pickle import sqlite3 class User: def __init__(self, name: str, age: int, email: str): self.name = name self.age = age self.email = email def serialize_user(user: User) -> bytes: """Serialize User object to bytes using pickle.""" return pickle.dumps(user) def deserialize_us...
import os import pytest from solution import User, serialize_user, deserialize_user, create_user_table, insert_user, get_user, update_user, delete_user def test_serialization(): user = User(name='Alice', age=30, email='alice@example.com') data = serialize_user(user) assert isinstance(data, bytes) ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pickle\nimport sqlite3\n\n\nclass User:\n def __init__(self, name: str, age: int, email: str):\n self.name = name\n self.age = age\n self...
trial_gpt4o_2
{ "original_instruction": "#### Objective\n\nWrite a Python program that manages user data by combining object serialization (`pickle`) and database operations (`sqlite3`). The user data includes basic information such as name, age, and email. You will be required to implement the following:\n\n1. A `User` class with...
0.593743
Docs: Python310_5622
C
[ "serialize_user", "deserialize_user", "create_user_table", "insert_user", "get_user", "update_user", "delete_user" ]
7
[ [ "get_user", "deserialize_user" ], [ "insert_user", "serialize_user" ], [ "update_user", "serialize_user" ] ]
3
[]
false
[ "User" ]
true
pytest
true
[]
true
84e885b184628cbd9bd4260bb36762ea15a98fc4
1e5564816c4c65f4cfafe59de5048d00d0e550b8
v1.0
complete
Docs
Docs: Pandas_6669_C
import pandas as pd def optimize_dataframe(df: pd.DataFrame) -> tuple: """ Optimize the memory usage of a given Pandas DataFrame. This function: 1. Converts any columns with dtype=object to categorical if the number of unique values is less than 50% of the total rows. 2. Calculates the...
import pandas as pd import numpy as np def fill_missing_with_median(series: pd.Series) -> pd.Series: """ Fills missing values in a pandas Series with the median of the Series. """ if pd.api.types.is_integer_dtype(series): median_value = series.median() return series.fillna(median_value)...
import pytest import pandas as pd import numpy as np from solution import optimize_dataframe def test_memory_optimization(): data = { 'int_col': np.random.randint(1, 100, size=1000), 'object_col': np.random.choice(['A','B','C','D'], size=1000), 'mix_col': np.random.choice([1, np.nan], size=...
[ { "docstring": "Fills missing values in a pandas Series with the median of the Series.", "function_declaration": "def fill_missing_with_median(series):", "function_name": "fill_missing_with_median", "parameter_list": "(series)" }, { "docstring": "Optimizes a DataFrame by converting object co...
[ 0, 0, 0, 0, 0, 1, 1, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\n\ndef fill_median(col):\n \"\"\"\n Fill NaN values in a column with the median of that column.\n \"\"\"\n if pd.api.types.is_integer_dt...
trial_gpt4o_8
{ "original_instruction": "### Memory Optimization, Handling Missing Values, and UDF in Pandas\n\n#### **Objective:**\n\nWrite a function `optimize_dataframe` that optimizes the memory usage of a given Pandas DataFrame. This function should:\n\n1. Convert any columns with `dtype=object` to `categorical` if the number...
0.637515
Docs: Pandas_6669
C
[ "fill_missing_with_median", "optimize_dataframe" ]
2
[ [ "optimize_dataframe", "fill_missing_with_median" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "pandas" ]
false
67029e711473bea2651ad75620df137274bb48a5
9dbaa1e2122d021934f8110cb97340bb36128b4c
v1.0
complete
Docs
Docs: Python310_7276_C
import asyncio import socket async def broadcast(message, writer): """ Broadcast the message to all clients except the sender. """ pass async def handle_client(reader, writer): """ Handle the communication with a single client. """ pass async def start_chat_server(): """ Start the chat server tha...
import asyncio import socket clients = [] async def broadcast(message, writer): for client_writer in clients: if client_writer != writer: client_writer.write(message) await client_writer.drain() async def handle_client(reader, writer): addr = writer.get_extra_info('peername') ...
import asyncio import socket import pytest @pytest.fixture async def echo_server(): server = await asyncio.start_server( handle_client, 'localhost', 12345) async with server: yield server @pytest.mark.asyncio async def test_client_connection(echo_server): reader, writer = await asyncio.ope...
[]
[ 0, 0, 0, 0, 1, 0, 1, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nclients = {}\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"New connection from {addr}\")\n ...
trial_gpt4o_8
{ "original_instruction": "### Asynchronous Chat Server\n\n#### Objective:\nImplement a simple chat server using the `asyncio` and `socket` modules that supports multiple clients connecting and sending messages to a chat room.\n\n#### Task:\n1. Implement an asynchronous chat server that can handle multiple clients.\n...
0.582916
Docs: Python310_7276
C
[ "broadcast", "handle_client", "start_chat_server" ]
3
[ [ "handle_client", "broadcast" ], [ "start_chat_server", "handle_client" ] ]
2
[]
false
[]
false
pytest
false
[]
true
123582a746c38754e4dbda327f7c731e9d4bbbfe
d8a1c4357ebfbfbc5402e21817e7c9c1f11d0b3d
v1.0
complete
Docs
Docs: Python310_5870_C
import contextlib import aiohttp import asyncio @contextlib.contextmanager def file_manager(file_name): print(f"Opening file {file_name}") try: with open(file_name, 'w') as file: yield file finally: print(f"Closing file {file_name}") @contextlib.asynccontextmanager async def as...
import contextlib import aiohttp import asyncio @contextlib.contextmanager def file_manager(file_name): print(f"Opening file {file_name}") try: with open(file_name, 'w') as file: yield file finally: print(f"Closing file {file_name}") @contextlib.asynccontextmanager async def as...
import pytest import asyncio from unittest.mock import patch, mock_open from aiohttp import ClientSession from solution import manage_resources @pytest.mark.asyncio async def test_manage_resources_all_sync(): resources = [ {"type": "sync", "resource": "test_file_1.txt", "optional": False}, {"type":...
[ { "docstring": null, "function_declaration": "def file_manager(file_name):", "function_name": "file_manager", "parameter_list": "(file_name)" } ]
[ 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 contextlib\nimport aiohttp\nimport asyncio\n\n@contextlib.contextmanager\ndef file_manager(file_name):\n print(f\"Opening file {file_name}\")\n try:\n ...
trial_gpt4o_0
{ "original_instruction": "**Coding Assessment Question**\n\n### Objective\nImplement a custom context manager that ensures the proper management of multiple resources, allows for optional resource management, and supports both synchronous and asynchronous operations.\n\n### Problem Statement\nYou are required to imp...
0.494304
Docs: Python310_5870
C
[ "file_manager", "async_http_session", "manage_resources" ]
3
[ [ "manage_resources", "async_http_session" ], [ "manage_resources", "file_manager" ] ]
2
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
a9b88e9f15ba8430b4b4c555d7837b1d1edfe798
e9e99faba2040660077f1575f933a08b2fe6d799
v1.0
complete
Docs
Docs: Python310_6602_C
import asyncio import random from typing import List, Dict import logging # Setup logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) async def fetch_data(url: str) -> int: """ Simulates fetching data from a URL by asynchronously sleeping for a random duration (1-5 seconds) and t...
import asyncio import logging import random from typing import List, Dict # Setup logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) async def fetch_data(url: str) -> int: try: await asyncio.sleep(random.randint(1, 5)) data_length = len(url) logger.debug(...
import pytest from solution import fetch_data, process_data, execute_tasks @pytest.mark.asyncio async def test_fetch_data(): url = "https://example.com" result = await fetch_data(url) assert result == len(url) @pytest.mark.asyncio async def test_process_data(): data = 10 result = await process_dat...
[]
[ 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\nfrom typing import List, Dict\n\n# Initialize logging for debugging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = l...
trial_gpt4o_2
{ "original_instruction": "### Advanced Asynchronous Programming with Asyncio\n\n#### Objective:\nDesign and implement a Python function that performs multiple asynchronous tasks efficiently while ensuring proper error handling, logging, and concurrency management.\n\n#### Problem Statement:\nYou are tasked with simu...
0.604874
Docs: Python310_6602
C
[ "fetch_data", "process_data", "execute_tasks" ]
3
[ [ "execute_tasks", "fetch_data" ], [ "execute_tasks", "process_data" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
43be522b4d4a9bb2fa7ccf5c83947b6cd1627729
8942e689d6c2fa3fe59db6d2f2b24cb1d59dd8be
v1.0
complete
Docs
Docs: Python310_6743_C
import asyncio import time import math from typing import List async def worker(name: str, queue: asyncio.Queue, results: List[float]): """ Worker coroutine that processes numbers from a queue, computes their factorial, and records the time taken to process. """ start_time = time.monotonic() wh...
import asyncio import time import math from typing import List async def worker(name: str, queue: asyncio.Queue, results: List[float]): start_time = time.monotonic() while True: try: number = await queue.get() except asyncio.QueueEmpty: break # Compute factorial ...
import pytest import asyncio from solution import process_factorials @pytest.mark.asyncio async def test_process_factorials_single_worker(): numbers = [5, 10, 15] num_workers = 1 result = await process_factorials(numbers, num_workers) assert len(result) == 1 assert result[0] >= 0 @pytest.mark.asyn...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport time\nimport math\nfrom typing import List\n\nasync def worker(name: str, queue: asyncio.Queue, results: List[float]):\n worker_id = int(name....
trial_gpt4o_2
{ "original_instruction": "#### Objective:\nTo assess your understanding of asynchronous programming and the usage of `asyncio` queues in Python.\n\n#### Problem Statement:\n\nImplement a system that processes a batch of asynchronous tasks using `asyncio.Queue`. The tasks involve calculating the factorial of multiple...
0.701401
Docs: Python310_6743
C
[ "worker", "process_factorials" ]
2
[ [ "process_factorials", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
15bf75373287dd633840143ec0b9aaa7dc1856bc
50a5774a9f3ef39f70b5554d4dca418766b6e8bc
v1.0
complete
Docs
Docs: Python310_7065_C
import ctypes def create_capsule(): """ Create a PyCapsule encapsulating a function pointer to a C function that sums two integers. Returns: A PyCapsule encapsulating the function pointer. >>> isinstance(create_capsule(), ctypes.py_object) True """ def use_capsule(capsule, a, b): "...
import ctypes # Define the C function we want to wrap as a capsule def add_function(a, b): return a + b # Define the destructor for the capsule def capsule_destructor(capsule): print("Capsule is being destroyed") # Create a capsule encapsulating the add_function def create_capsule(): ADD_FUNC_TYPE = ctyp...
import ctypes from solution import create_capsule, use_capsule def test_create_capsule(): capsule = create_capsule() assert isinstance(capsule, ctypes.py_object), "Capsule should be an instance of ctypes.py_object" def test_use_capsule_valid(): capsule = create_capsule() result = use_capsule(capsule, ...
[ { "docstring": null, "function_declaration": "def add_function(a, b):", "function_name": "add_function", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def capsule_destructor(capsule):", "function_name": "capsule_destructor", "parameter_list": "(capsu...
[ 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 ctypes\n\n# Define the C function we want to wrap as a capsule\ndef add_function(a, b):\n return a + b\n\n# Define the destructor for the capsule\ndef capsule...
trial_gpt4o_0
{ "original_instruction": "### Python C API: PyCapsule Integration\n\n#### Objective\nYour task is to write a Python extension module in C that demonstrates the use of `PyCapsule` to pass a C function pointer through Python code and invoke it from another C function. This will test your ability to correctly use the `...
0.460079
Docs: Python310_7065
C
[ "add_function", "capsule_destructor", "create_capsule", "use_capsule" ]
4
[ [ "create_capsule", "add_function" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b8c57893f0b3f1289f44f5ac7b7961f6c2d904ec
c70de86c8fd65d10038893444e41c5847b016979
v1.0
complete
Docs
Docs: Python310_7484_C
from datetime import datetime, timedelta from typing import List, Tuple def event_scheduler(events: List[Tuple[str, datetime, datetime]]) -> None: """ Initialize the scheduler with a list of events. """ pass def add_event(event: Tuple[str, datetime, datetime]) -> bool: """ Add an event if it d...
from datetime import datetime, timedelta from typing import List, Tuple from collections import defaultdict, OrderedDict # A global variable to maintain events events_by_date = defaultdict(OrderedDict) def event_scheduler(events: List[Tuple[str, datetime, datetime]]) -> None: """ Initialize the scheduler with...
from datetime import datetime, timedelta import pytest from solution import event_scheduler, add_event, get_daily_events def test_event_scheduler(): events = [ ("Meeting", datetime(2023, 10, 1, 9, 0), datetime(2023, 10, 1, 10, 0)), ("Workshop", datetime(2023, 10, 1, 10, 30), datetime(2023, 10, 1, 1...
[ { "docstring": "Initialize the scheduler with a list of events.", "function_declaration": "def event_scheduler(events):", "function_name": "event_scheduler", "parameter_list": "(events)" }, { "docstring": "Add an event if it does not conflict with existing events.", "function_declaration...
[ 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 datetime import datetime, timedelta\nfrom typing import List, Tuple\nfrom collections import defaultdict, OrderedDict\n\n# A global variable to maintain events\nev...
trial_gpt4o_0
{ "original_instruction": "### Python310 Coding Assessment Question\n\n#### Objective:\nTo assess the ability to work with specialized data types and collections provided in python310.\n\n#### Problem Statement:\nYou are required to write a function `event_scheduler()` that schedules events based on their start and e...
0.700437
Docs: Python310_7484
C
[ "event_scheduler", "add_event", "get_daily_events" ]
3
[ [ "event_scheduler", "add_event" ] ]
1
[]
false
[]
false
pytest
true
[]
true
188ca2bcb7848a9065a22f07bd55f8d330d1ce26
0455561575cd35a2beb7501dffc35c65f02eec98
v1.0
complete
Docs
Docs: Python310_6136_C
import atexit class InsufficientFunds(Exception): pass class BankAccount: """ A simple bank account class for managing deposits, withdrawals, and transaction history. Methods: - __init__(self, account_number): Initializes the account with a number and zero balance. - deposit(self, amount): De...
import atexit class InsufficientFunds(Exception): pass class BankAccount: def __init__(self, account_number): self.account_number = account_number self.balance = 0 self.transaction_history = [] def deposit(self, amount): self.balance += amount self.transaction_hist...
import pytest from solution import BankAccount, InsufficientFunds, create_account def test_create_account(): account = create_account(1) assert account.account_number == 1 assert account.get_balance() == 0 assert account.get_transaction_history() == [] def test_deposit(): account = create_account(...
[]
[ 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 atexit\n\nclass InsufficientFunds(Exception):\n pass\n\nclass BankAccount:\n def __init__(self, account_number):\n self.account_number = account_num...
trial_gpt4o_1
{ "original_instruction": "You are required to design an application that simulates a simple banking system providing the following functionalities:\n1. Create an account.\n2. Deposit money into the account.\n3. Withdraw money from the account.\n4. Save the account transaction history to a file upon program terminati...
0.559931
Docs: Python310_6136
C
[ "save_transaction_history", "create_account" ]
2
[ [ "create_account", "save_transaction_history" ] ]
1
[]
false
[ "InsufficientFunds", "BankAccount" ]
true
pytest
true
[]
true
1cf929e0e5ddfdc37b51a3d3cdef4984a3250b2b
d329aa8298c4ea9ca886f0c30aad34da84eda17c
v1.0
complete
Docs
Docs: Python310_6768_C
class PyPreConfig: def __init__(self): self.utf8_mode = 0 self.allocator = 0 self.isolated = False self.configure_locale = True def PyPreConfig_InitIsolatedConfig(self): self.isolated = True self.configure_locale = False class PyConfig: def __init__(self): ...
class PyPreConfig: def __init__(self): self.utf8_mode = 0 self.allocator = 0 self.isolated = False self.configure_locale = True def PyPreConfig_InitIsolatedConfig(self): self.isolated = True self.configure_locale = False class PyConfig: def __init__(self): ...
from solution import initialize_isolated_python, PyConfig, PyStatus def test_initialize_successful(): config = PyConfig() config.SetSysPath(['/custom/path/to/modules']) assert simulate_initialize(config) == PyStatus.Ok() def test_initialize_empty_sys_path(): config = PyConfig() assert PyStatus.I...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class PyPreConfig:\n def __init__(self):\n self.utf8_mode = 0\n self.allocator = 0\n\n def PyPreConfig_InitIsolatedConfig(self):\n self.isola...
trial_gpt4o_1
{ "original_instruction": "### Advanced Python Initialization and Configuration\n\n#### Background\n\nPython can be initialized and configured in a highly customizable manner using structures `PyConfig` and `PyPreConfig`. These structures allow setting numerous parameters that can control Python's behavior on initial...
0.443713
Docs: Python310_6768
C
[ "initialize_isolated_python", "simulate_initialize", "cleanup" ]
3
[ [ "initialize_isolated_python", "cleanup" ], [ "initialize_isolated_python", "simulate_initialize" ] ]
2
[]
false
[ "PyPreConfig", "PyConfig", "PyStatus" ]
true
pytest
true
[]
true
6cf5beff34e94da0a86fd5cd1ee83a3c84270b0e
3042275da614caa85ba8c8a6a1b7d2cf09ea9bc2
v1.0
complete
Docs
Docs: Python310_7483_C
from typing import Iterator, List def generate_primes() -> Iterator[int]: """ A generator that yields an infinite sequence of prime numbers. >>> prime_gen = generate_primes() >>> next(prime_gen) 2 >>> next(prime_gen) 3 >>> next(prime_gen) 5 >>> next(prime_gen) 7 """ def...
from typing import Iterator, List import itertools def generate_primes() -> Iterator[int]: """ A generator that yields an infinite sequence of prime numbers. """ D = {} q = 2 while True: if q not in D: # q is a prime number yield q D[q * q] = [q] ...
from solution import generate_primes, filter_primes_below def test_generate_primes(): prime_gen = generate_primes() primes_expected = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] primes_actual = [next(prime_gen) for _ in range(10)] assert primes_actual == primes_expected def test_filter_primes_below_10(): ...
[ { "docstring": "A generator that yields an infinite sequence of prime numbers.", "function_declaration": "def generate_primes():", "function_name": "generate_primes", "parameter_list": "()" }, { "docstring": "Filters out all prime numbers below a given integer n.", "function_declaration"...
[ 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 Iterator, List\n\ndef generate_primes() -> Iterator[int]:\n \"\"\"\n Generates an infinite sequence of prime numbers using a generator.\n Ut...
trial_gpt4o_2
{ "original_instruction": "#### Objective:\nTo design a function that utilizes iterators, generators, and other functional programming constructs to solve a practical problem. This will test the student's understanding and ability to implement Python's functional programming features.\n\n#### Problem Statement:\nYou ...
0.730118
Docs: Python310_7483
C
[ "generate_primes", "filter_primes_below" ]
2
[ [ "filter_primes_below", "generate_primes" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a65d2a33dd75e6c7348230a73e6681b24a3875f5
97777d7de966b510c41980410578876e043ba276
v1.0
complete
Docs
Docs: Python310_7165_C
import aiohttp import asyncio from typing import List, Dict async def fetch_url(url: str) -> Dict[str, any]: """ Fetch a URL asynchronously and return its status and content length. Args: url (str): The URL to fetch. Returns: dict: A dictionary with keys 'url', 'status', and 'content_length...
import aiohttp import asyncio from typing import List, Dict async def fetch_url(url: str) -> Dict[str, any]: async with aiohttp.ClientSession() as session: try: async with session.get(url) as response: content = await response.read() return { ...
import pytest import asyncio from solution import fetch_url, fetch_all @pytest.mark.asyncio async def test_fetch_url_success(): result = await fetch_url("http://example.com") assert result["url"] == "http://example.com" assert result["status"] == 200 assert result["content_length"] > 0 @pytest.mark.as...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import aiohttp\nimport asyncio\nfrom typing import List, Dict\n\nasync def fetch_url(url: str) -> Dict[str, any]:\n async with aiohttp.ClientSession() as session:\n ...
trial_gpt4o_0
{ "original_instruction": "### Question: Asynchronous HTTP Fetcher\n\n**Objective:** Implement an asynchronous HTTP fetcher using the `asyncio` module in Python.\n\n**Requirements:**\n- Create an asynchronous function `fetch_url(url: str) -> dict` that takes a URL as input and returns a dictionary with the keys `\"ur...
0.624386
Docs: Python310_7165
C
[ "fetch_url", "fetch_all" ]
2
[ [ "fetch_all", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
6e5e454ec17e58fb3726e0d3c36b7574675c8e0f
cc70489252740661d469709c7e648df1069a8678
v1.0
complete
Docs
Docs: Python310_7418_C
import requests from concurrent.futures import ThreadPoolExecutor from typing import List, Optional def fetch_parallel(urls: List[str], timeout: int) -> List[Optional[str]]: """ Fetches the content of a list of URLs in parallel using a thread pool. Args: - urls: List of URLs to fetch. - timeout: T...
import requests from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List, Optional def fetch_url(url: str, timeout: int) -> Optional[str]: """ Helper function to fetch the content of a single URL with a specified timeout. Returns the content of the URL or None if the request ...
import pytest from solution import fetch_parallel # Mocking requests.get to simulate different scenarios from unittest.mock import patch, MagicMock URLs = ["http://example.com/success", "http://example.com/fail", "http://example.com/timeout", "http://example.com/another"] def mock_requests_get(url, timeout): if ...
[ { "docstring": "Helper function to fetch the content of a single URL with a specified timeout.\nReturns the content of the URL or None if the request fails.", "function_declaration": "def fetch_url(url, timeout):", "function_name": "fetch_url", "parameter_list": "(url, timeout)" }, { "docstr...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List, Optional\n\ndef fetch_url(url: str, timeout: int) -> Optional...
trial_gpt4o_0
{ "original_instruction": "### Concurrent Futures Assessment\n\n#### Objective\nImplement a function using the `concurrent.futures` module to perform parallel processing on a set of tasks, demonstrating the ability to manage asynchronous operations and handle exceptions properly.\n\n#### Problem Statement\nYou are gi...
0.543226
Docs: Python310_7418
C
[ "fetch_url", "fetch_parallel" ]
2
[ [ "fetch_parallel", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
c431080d5076ae62978aa9b74d4db418c0ee3679
07cb22d50d8991080809c7c1e518606dd34e118a
v1.0
complete
Docs
Docs: Python310_7521_C
import asyncio async def fetch_data(id, delay): """ Simulate fetching data by awaiting asyncio.sleep(delay). >>> await fetch_data(1, 1) == "Data from source 1" """ pass async def process_data(data): """ Simulate data processing by awaiting asyncio.sleep(2). >>> await process_data("Data...
import asyncio async def fetch_data(id, delay): """ Simulate fetching data by awaiting asyncio.sleep(delay). """ await asyncio.sleep(delay) return f"Data from source {id}" async def process_data(data): """ Simulate data processing by awaiting asyncio.sleep(2). """ await asyncio.sle...
import asyncio import pytest from solution import fetch_data, process_data, main @pytest.mark.asyncio async def test_fetch_data(): result = await fetch_data(1, 1) assert result == "Data from source 1" @pytest.mark.asyncio async def test_process_data(): result = await process_data("Data from source 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 fetch_data(id, delay):\n \"\"\"\n Simulate fetching data by awaiting asyncio.sleep(delay).\n \"\"\"\n await asyncio.sleep(delay)...
trial_gpt4o_0
{ "original_instruction": "### Asyncio Task Management and Timeout Handling\n\nYou are tasked with building a simple simulation of a data processing system using `asyncio`. Your goal is to create multiple concurrent tasks that simulate data fetching and processing. You need to demonstrate your understanding of asynci...
0.528526
Docs: Python310_7521
C
[ "fetch_data", "process_data", "fetch_and_process", "main" ]
4
[ [ "fetch_and_process", "fetch_data" ], [ "fetch_and_process", "process_data" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
eba46ec77bc5b8417c593406ac478f0395c71e6b
c199601beae67bc20f347fe527573f2bb4b7c4c8
v1.0
complete
Docs
Docs: Python310_7104_C
import signal import time import os def sigint_handler(signum, frame): """Handle SIGINT signal (Ctrl+C) >>> sigint_handler(signal.SIGINT, None) SIGINT received Program terminated by KeyboardInterrupt """ print("SIGINT received") raise KeyboardInterrupt def sigalrm_handler(signum, frame): ...
import signal import time import os def sigint_handler(signum, frame): print("SIGINT received") raise KeyboardInterrupt def sigalrm_handler(signum, frame): print("Alarm Triggered") def sigterm_handler(signum, frame): print("SIGTERM received, shutting down gracefully") clean_up() exit(0) def ...
import signal import os import time import subprocess from threading import Timer import pytest def test_sigint_handling(): def send_sigint(): os.kill(os.getpid(), signal.SIGINT) Timer(2, send_sigint).start() with pytest.raises(KeyboardInterrupt): signal.signal(signal.SIGINT, sigint_handle...
[ { "docstring": null, "function_declaration": "def sigint_handler(signum, frame):", "function_name": "sigint_handler", "parameter_list": "(signum, frame)" }, { "docstring": null, "function_declaration": "def sigalrm_handler(signum, frame):", "function_name": "sigalrm_handler", "pa...
[ 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 signal\nimport time\nimport os\n\ndef sigint_handler(signum, frame):\n print(\"SIGINT received\")\n raise KeyboardInterrupt\n\ndef sigalrm_handler(signum, ...
trial_gpt4o_1
{ "original_instruction": "### Signal Handling in Python\n\nYou are required to implement a Python program that demonstrates the use of the `signal` module to handle various types of signals. You will set up signal handlers for `SIGINT`, `SIGALRM`, and `SIGTERM` and ensure the application handles these signals gracef...
0.514631
Docs: Python310_7104
C
[ "sigint_handler", "sigalrm_handler", "sigterm_handler", "clean_up", "main" ]
5
[ [ "sigterm_handler", "clean_up" ] ]
1
[]
false
[]
false
pytest
false
[]
true
51a06f1e1602be5674a31ec4865692d61367ef4b
12213d7bb5966a2af35be04fbaf88a77f4a5f965
v1.0
complete
Docs
Docs: Pytorch_6319_C
import torch from torch import nn from torch import optim # 1. Custom Linear Module class CustomLinear(nn.Module): def __init__(self, in_features, out_features): super(CustomLinear, self).__init__() self.weight = nn.Parameter(torch.empty(in_features, out_features)) self.bias = nn.Parameter(...
import torch from torch import nn import torch.nn.functional as F from torch import optim # 1. Custom Linear Module class CustomLinear(nn.Module): def __init__(self, in_features, out_features): super(CustomLinear, self).__init__() # Initialize parameters with custom techniques self.weight =...
import torch from torch import nn from solution import CompositeNet def test_model_initialization(): model = CompositeNet() for name, param in model.named_parameters(): if 'weight' in name: assert torch.all(param != 0), f"Weight {name} is not properly initialized" if 'bias' in name:...
[]
[ 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\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch import optim\n\n# 1. Custom Linear Module\nclass CustomLinear(nn.Module):\n def __ini...
trial_gpt4o_9
{ "original_instruction": "#### Objective\nDesign a PyTorch module and demonstrate advanced features such as hooks, custom initialization, and training using optimizers. Your task is to create a composite module that first applies a custom linear transformation followed by a non-linear activation function, and train ...
0.6113
Docs: Pytorch_6319
C
[ "forward_hook", "backward_hook", "train_model" ]
3
[ [ "train_model", "backward_hook" ], [ "train_model", "forward_hook" ] ]
2
[]
false
[ "CustomLinear", "CompositeNet" ]
true
pytest
true
[ "torch" ]
false
7077cc038ca74f8e8a372e3647e1e6dc14bdfbbe
fc61866713670f4d7f357caa8b823f3e1feab273
v1.0
complete
Docs
Docs: Python310_6951_C
import gc def custom_gc_callback(phase, info): """Callback function for garbage collection phases.""" print(f"Custom: GC {phase}") def manage_gc(): """ Manage and manipulate Python's garbage collector using the `gc` module. 1. Disable and Enable Garbage Collection: - Initially, disable aut...
import gc def custom_gc_callback(phase, info): print(f"Custom: GC {phase}") def manage_gc(): # Disable automatic garbage collection gc.disable() print(f"Garbage collection enabled: {gc.isenabled()}") # Create cyclic references deliberately cycle_list = [] cycle_list.append(cycle_list) ...
import gc from solution import manage_gc def test_disable_enable_gc(): # Ensure GC is enabled before disabling gc.enable() assert gc.isenabled() == True manage_gc() # After function execution, GC should be re-enabled assert gc.isenabled() == True def test_manual_gc_collection(): # Create c...
[ { "docstring": null, "function_declaration": "def custom_gc_callback(phase, info):", "function_name": "custom_gc_callback", "parameter_list": "(phase, info)" }, { "docstring": null, "function_declaration": "def manage_gc():", "function_name": "manage_gc", "parameter_list": "()" ...
[ 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 gc\n\ndef disable_gc():\n gc.disable()\n return gc.isenabled()\n\ndef create_cyclic_reference():\n lst = []\n lst.append(lst)\n return lst\n\ndef ...
trial_gpt4o_2
{ "original_instruction": "### Garbage Collection Optimization and Debugging with Python's `gc` Module\n\n#### Objective\nImplement a Python script that performs the following tasks using the `gc` module:\n\n1. **Disable and Enable Garbage Collection:**\n - Initially, disable automatic garbage collection.\n - Con...
0.353893
Docs: Python310_6951
C
[ "custom_gc_callback", "manage_gc" ]
2
[ [ "manage_gc", "custom_gc_callback" ] ]
1
[]
false
[]
false
pytest
true
[]
true
57a80471cb26e2faf0e60379c90556a173f166d0
cd26ee264f51e203646790d52420d119dd0616fa
v1.0
complete
Docs
Docs: Python310_7769_C
def function_1(): """ Simulates function 1's execution. >>> function_1() "Function 1" """ def function_2(): """ Calls function_1 and simulates function 2's execution. >>> function_2() "Function 1\nFunction 2" """ def function_3(): """ Calls function_2 and simulates function 3's exe...
# sample_program.py def function_1(): print("Function 1") def function_2(): function_1() print("Function 2") def function_3(): function_2() print("Function 3") def start(): function_3() if __name__ == "__main__": start()
from solution import function_1, function_2, function_3, start def test_function_1(capsys): function_1() captured = capsys.readouterr() assert captured.out == "Function 1\n" def test_function_2(capsys): function_2() captured = capsys.readouterr() assert captured.out == "Function 1\nFunction 2\...
[ { "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, 0, 1, 0, 0, 0, 0, 0, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "# sample_program.py\ndef function_1():\n print(\"Function 1\")\n\ndef function_2():\n function_1()\n print(\"Function 2\")\n\ndef func...
trial_gpt4o_1
{ "original_instruction": "**Challenging Coding Assessment Question: Understanding CPython Instrumentation with DTrace and SystemTap**\n\n**Objective:**\nWrite a Python script that simulates a basic program's execution and design a corresponding DTrace or SystemTap script that monitors its function call entries and e...
0.59324
Docs: Python310_7769
C
[ "function_1", "function_2", "function_3", "start" ]
4
[ [ "function_2", "function_1" ], [ "function_3", "function_2" ], [ "start", "function_3" ] ]
3
[]
false
[]
false
pytest
true
[]
true
a92c31d268867b6c997c1dc19f90e4ce10829536
42afbee4414a05f81df59190841b233bd57c2130
v1.0
complete
Docs
Docs: Python310_6348_C
import hmac import hashlib def generate_secure_hash(message: str, key: bytes) -> str: """ Generate a secure HMAC hash of the message using the provided key and SHA-256 algorithm. Parameters: message (str): The message to hash. key (bytes): The secret key used for hashing. Returns: str: Th...
import hmac import hashlib def generate_secure_hash(message: str, key: bytes) -> str: """ Generate a secure HMAC hash of the message using the provided key and SHA-256 algorithm. Parameters: message (str): The message to hash. key (bytes): The secret key used for hashing. Returns: str: Th...
from solution import generate_secure_hash, verify_secure_hash def test_generate_secure_hash(): message = "Hello, world!" key = b"this_is_a_secret_key" generated_hash = generate_secure_hash(message, key) assert isinstance(generated_hash, str) assert len(generated_hash) == 64 def test_verify_secure_...
[ { "docstring": "Generate a secure HMAC hash of the message using the provided key and SHA-256 algorithm.\n\nParameters:\nmessage (str): The message to hash.\nkey (bytes): The secret key used for hashing.\n\nReturns:\nstr: The hexadecimal representation of the HMAC hash.", "function_declaration": "def genera...
[ 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 hmac\nimport hashlib\n\ndef generate_secure_hash(message: str, key: bytes) -> str:\n \"\"\"\n Generate a secure HMAC hash of the message using the provided...
trial_gpt4o_2
{ "original_instruction": "### Cryptographic Services: Secure Message Verification\n\nIn this coding assessment, you will demonstrate your understanding of the `hashlib` and `hmac` modules by implementing a secure message verification system.\n\n### Problem Statement\n\nYou need to implement two functions to ensure t...
0.817693
Docs: Python310_6348
C
[ "generate_secure_hash", "verify_secure_hash" ]
2
[ [ "verify_secure_hash", "generate_secure_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a0bf9aaf0654b24670b0cddc986e1a9ece4eeb05
a5ce0946a4b021b54f57ea3c35ecde13566abcd1
v1.0
complete
Docs
Docs: Scikit_6621_C
import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def out_of_core_learning(file_path: str, minibatch_size: int) -> float: """ Perform out-of-core learning using SGDClassifier and HashingVectoriz...
import os import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(file_path): """ Generator to stream data from a file, one line at a time. Each line is expected to be in the f...
import pytest from solution import out_of_core_learning # Test the function with a small synthetic dataset def test_out_of_core_learning(): # Create a temporary file with labeled instances test_file_path = 'test_large_text_data.txt' with open(test_file_path, 'w') as f: f.write("0\tThis is the first...
[ { "docstring": "Generator to stream data from a file, one line at a time.\nEach line is expected to be in the format: <label> <text>.", "function_declaration": "def stream_data(file_path):", "function_name": "stream_data", "parameter_list": "(file_path)" }, { "docstring": "Extract features ...
[ 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 numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics impor...
trial_gpt4o_0
{ "original_instruction": "You are tasked with building an out-of-core learning system using scikit-learn. This system should be able to handle extremely large datasets that cannot fit into the computer's main memory (RAM). The task involves creating a pipeline that:\n\n1. Streams data from a large text file.\n2. Ext...
0.58543
Docs: Scikit_6621
C
[ "stream_data", "extract_features", "incremental_train", "out_of_core_learning" ]
4
[ [ "incremental_train", "extract_features" ], [ "incremental_train", "stream_data" ], [ "out_of_core_learning", "extract_features" ], [ "out_of_core_learning", "incremental_train" ], [ "out_of_core_learning", "stream_data" ] ]
5
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
d9a238e12b749c6bd4fa6b618f0ea415597c2219
625004779b1682dfa7ef489e313684b682c26d3c
v1.0
complete
Docs
Docs: Python310_7775_C
import asyncio import signal clients = {} async def handle_client(reader, writer): """ Manages individual client connections and messages. """ pass async def broadcast_message(message, sender): """ Sends messages to all clients except the sender. """ pass async def main(host, port): """ ...
import asyncio import signal clients = {} async def handle_client(reader, writer): addr = writer.get_extra_info('peername') username = (await reader.read(100)).decode().strip() clients[username] = writer try: while data := await reader.read(100): message = f"{username}: {data.decod...
import asyncio import pytest from unittest.mock import Mock from solution import handle_client, broadcast_message, clients @pytest.mark.asyncio async def test_handle_client(): reader = Mock() writer = Mock() writer.get_extra_info.return_value = ('127.0.0.1', 12345) reader.read = Mock(side_effect=[b"te...
[]
[ 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\nimport signal\n\nclients = {}\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n username = (await reader.re...
trial_gpt4o_0
{ "original_instruction": "### Asynchronous Chat Server with `asyncio` Event Loop\n\n### Objective:\nDesign and implement an asynchronous chat server using Python's `asyncio` event loop. Your task is to handle multiple client connections, manage messages asynchronously, and implement a way to broadcast messages to al...
0.579527
Docs: Python310_7775
C
[ "handle_client", "broadcast_message", "main" ]
3
[ [ "handle_client", "broadcast_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e01f5c70d47ceb886ab6983977432637afc2c86e
8a3e8d55abdb99521f6bbe3b69748e161a6fed07
v1.0
complete
Docs
Docs: Python310_7787_C
class DataError(Exception): pass class FileFormatError(DataError): pass class FileEmptyError(DataError): pass class CorruptDataError(DataError): pass def process_file(file_content: str) -> None: """ Simulates the processing of a data file. Raises appropriate exceptions based on the conte...
class DataError(Exception): pass class FileFormatError(DataError): pass class FileEmptyError(DataError): pass class CorruptDataError(DataError): pass def process_file(file_content: str) -> None: """ Simulates the processing of a data file. Raises appropriate exceptions based on the conte...
import pytest from solution import ( DataError, FileFormatError, FileEmptyError, CorruptDataError, process_file, run_processing ) def test_process_file_empty(): with pytest.raises(FileEmptyError): process_file("") def test_process_file_corrupt(): with pytest.raises(Corrupt...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class DataError(Exception):\n pass\n\nclass FileFormatError(DataError):\n pass\n\nclass FileEmptyError(DataError):\n pass\n\nclass CorruptDataError(DataError):...
trial_gpt4o_2
{ "original_instruction": "### Custom Exception Implementation and Handling\n\nYou are asked to implement a custom hierarchical exception handling system for a hypothetical library that processes data files. The objectives are as follows:\n\n1. **Define Custom Exceptions:**\n - Implement the following custom excep...
0.529168
Docs: Python310_7787
C
[ "process_file", "run_processing" ]
2
[ [ "run_processing", "process_file" ] ]
1
[]
false
[ "DataError", "FileFormatError", "FileEmptyError", "CorruptDataError" ]
true
pytest
true
[]
true
126d576f3bf34cfb7f14f8c9c16faaa25a7289db
99eb09b12b634eac2106942dc027deabda8b2f40
v1.0
complete
Docs
Docs: Pytorch_7949_C
import os import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms def set_environment_variables(): """ Set up the necessary environment variables for CUDA and NCCL. """ pass def build_cnn_model(): """ Implement a simple CNN for CIFA...
import os import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms def set_environment_variables(): os.environ['PYTORCH_NO_CUDA_MEMORY_CACHING'] = '1' os.environ['TORCH_NCCL_USE_COMM_NONBLOCKING'] = '1' os.environ['CUDA_VISIBLE_DEVICES'] ...
import os import torch from solution import set_environment_variables, build_cnn_model def test_set_environment_variables(): set_environment_variables() assert os.environ['PYTORCH_NO_CUDA_MEMORY_CACHING'] == '1' assert os.environ['TORCH_NCCL_USE_COMM_NONBLOCKING'] == '1' assert os.environ['CUDA_VISIBLE...
[]
[ 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 torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\n\ndef set_environment_vari...
trial_gpt4o_9
{ "original_instruction": "### PyTorch Environment Variables and CUDA\n\nYou are tasked with setting up a PyTorch project that utilizes CUDA for GPU acceleration. The project involves:\n\n1. Creating a simple neural network for image classification on CIFAR-10 dataset.\n2. Ensuring optimized and efficient use of CUDA...
0.490155
Docs: Pytorch_7949
C
[ "set_environment_variables", "build_cnn_model", "train_model" ]
3
[ [ "train_model", "build_cnn_model" ], [ "train_model", "set_environment_variables" ] ]
2
[]
false
[]
false
pytest
true
[ "torch", "torchvision" ]
false
c2ccb0a23377a126083d97170a8be6f411eef536
37b4679202eb2d251ea5e7219bf808c4485985b2
v1.0
complete
Docs
Docs: Scikit_6685_C
import numpy as np from typing import Generator, List from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import itertools def stream_data(file_path: str, batch_size:...
import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import itertools def stream_data(file_path, batch_size): with open(file_path, 'r', encoding...
import os import pytest from solution import stream_data, train_and_evaluate def test_stream_data(tmpdir): test_file = tmpdir.join("test_data.txt") with open(test_file, "w") as f: f.write("class1,This is the first document.\n") f.write("class2,This is the second document.\n") f.write("...
[ { "docstring": null, "function_declaration": "def stream_data(file_path, batch_size):", "function_name": "stream_data", "parameter_list": "(file_path, batch_size)" }, { "docstring": null, "function_declaration": "def train_and_evaluate(file_path, batch_size, num_batches):", "function...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import t...
trial_gpt4o_0
{ "original_instruction": "#### Objective:\nTo assess the student's understanding of out-of-core learning, feature extraction, and the use of incremental learning algorithms in scikit-learn.\n\n#### Background:\nYou are given a large text dataset that cannot fit into the system's main memory. Your task is to build a ...
0.633639
Docs: Scikit_6685
C
[ "stream_data", "train_and_evaluate" ]
2
[ [ "train_and_evaluate", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
2818e2892648c15a7ac423174a7b720e643fd7c8
e2b7c3abe1ecf095bdedce3a258f2b633c837225
v1.0
complete
Docs
Docs: Python310_7930_C
from typing import List import asyncio async def async_scraper(urls: List[str]) -> List[str]: """ Asynchronous Web Scraping with Subprocesses and Queues Implement an asynchronous web scraping solution using the `asyncio` library's tasks, queues, and subprocesses to scrape data from multiple URLs simultaneously...
import asyncio from asyncio.subprocess import create_subprocess_exec, PIPE from typing import List async def fetch_url_content(url: str) -> str: process = await create_subprocess_exec( 'curl', '-s', url, stdout=PIPE, stderr=PIPE ) stdout, stderr = await process.communicate() if process....
import pytest import asyncio from solution import async_scraper @pytest.mark.asyncio async def test_async_scraper_single_url(): urls = ["http://example.com"] contents = await async_scraper(urls) assert len(contents) == 1 assert "Example Domain" in contents[0] @pytest.mark.asyncio async def test_async_...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom asyncio.subprocess import create_subprocess_exec, PIPE\nfrom typing import List\n\nasync def fetch_url_content(url: str) -> str:\n process = awa...
trial_gpt4o_0
{ "original_instruction": "### Asynchronous Web Scraping with Subprocesses and Queues\n\n**Objective:**\nImplement an asynchronous web scraping solution using the `asyncio` library's tasks, queues, and subprocesses to scrape data from multiple URLs simultaneously.\n\n**Problem Statement:**\n\nYou are required to writ...
0.619753
Docs: Python310_7930
C
[ "fetch_url_content", "worker", "async_scraper" ]
3
[ [ "async_scraper", "worker" ], [ "worker", "fetch_url_content" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b6983afb1dc91ec4805ec382394c7eed402ad22b
ebe406f264d947f608f1ecc2b9fdc344e0bd7a80
v1.0
complete
Docs
Docs: Python310_8061_C
import concurrent.futures import time def heavy_computation(n): time.sleep(0.1) return n * n def parallel_processing(data: list) -> list: """ Processes a list of integers using heavy_computation function in parallel. Parameters: data (list): A list of integers to be processed. Re...
import concurrent.futures import time def heavy_computation(n): time.sleep(0.1) return n * n def parallel_processing(data): """ Processes a list of integers using heavy_computation function in parallel. Parameters: data (list): A list of integers to be processed. Returns: lis...
from solution import parallel_processing def test_parallel_processing_basic(): data = [1, 2, 3, 4, 5] assert parallel_processing(data) == [1, 4, 9, 16, 25] def test_parallel_processing_empty_list(): data = [] assert parallel_processing(data) == [] def test_parallel_processing_single_element(): da...
[ { "docstring": null, "function_declaration": "def heavy_computation(n):", "function_name": "heavy_computation", "parameter_list": "(n)" }, { "docstring": "Processes a list of integers using heavy_computation function in parallel.\n\nParameters:\ndata (list): A list of integers to be processe...
[ 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 concurrent.futures import ProcessPoolExecutor, as_completed\n\ndef heavy_computation(n: int) -> int:\n \"\"\"\n Simulate a heavy computational task\n \"\"...
trial_gpt4o_1
{ "original_instruction": "You are tasked with processing a large list of numerical data. Each element of the list needs to be processed by a computational heavy function. To efficiently handle this workload, you decide to implement a function using the `concurrent.futures` module to parallelize the computation. Your...
0.618722
Docs: Python310_8061
C
[ "heavy_computation", "parallel_processing" ]
2
[ [ "parallel_processing", "heavy_computation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1df5957fcd9985d42f1b93c1fce4cbdcb3ad4c8f
e4524ceb29ab2fbf902050b02c97ae3f3138f789
v1.0
complete
Docs
Docs: Python310_7323_C
import _thread from typing import List def concurrent_prime_calculation(start: int, end: int, num_threads: int) -> List[int]: """ Calculate prime numbers concurrently within a given range using multiple threads. >>> concurrent_prime_calculation(1, 10, 2) [2, 3, 5, 7] >>> concurrent_prime_calculation(10...
import _thread from typing import List def is_prime(n: int) -> bool: if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return...
def test_concurrent_prime_calculation_small_range(): assert concurrent_prime_calculation(1, 10, 2) == [2, 3, 5, 7] def test_concurrent_prime_calculation_large_range(): assert concurrent_prime_calculation(1, 50, 4) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] def test_concurrent_prime_calculatio...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def concurrent_prime_calculation(start, end, num_threads):", "function_name": "concurrent_prime_calculation", "pa...
[ 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 _thread\nimport math\n\ndef is_prime(num):\n \"\"\"Check if a number is prime.\"\"\"\n if num < 2:\n return False\n if num in (2, 3):\n re...
trial_gpt4o_1
{ "original_instruction": "### Question: Concurrent Prime Number Calculation\n\nYou are tasked with implementing a concurrent prime number calculation using the low-level threading API provided by the `_thread` module. The goal is to determine the prime numbers within a given range `[start, end]` using multiple threa...
0.560446
Docs: Python310_7323
C
[ "is_prime", "concurrent_prime_calculation" ]
2
[ [ "concurrent_prime_calculation", "is_prime" ] ]
1
[]
false
[]
false
pytest
false
[]
true
5914703ad169b5126e3dcd4eb95f63f52ade032d
f41540465719c30dd03d847d8830738b6bd6288b
v1.0
complete
Docs
Docs: Python310_7475_C
import turtle def setup_screen(): """ Setup the turtle graphics screen with a light grey background. """ pass # Implementation here def setup_turtle(): """ Setup the turtle with shape 'turtle' and moderate speed. """ pass # Implementation here def move_forward(): """ Move the turtle forward by ...
import turtle def setup_screen(): screen = turtle.Screen() screen.bgcolor("lightgrey") return screen def setup_turtle(): t = turtle.Turtle() t.shape("turtle") t.speed(5) return t def move_forward(): turtle.forward(50) def move_backward(): turtle.backward(50) def turn_left(): ...
# Since the turtle module and its graphics interface doesn't support automated unit tests in a traditional # manner, we can only provide a structured way to manually verify the functionality by running the code. # Automated tests for turtle graphics would require a mock environment that does not exist here. # Thus, no ...
[ { "docstring": null, "function_declaration": "def setup_screen():", "function_name": "setup_screen", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def setup_turtle():", "function_name": "setup_turtle", "parameter_list": "()" }, { "docstring": nul...
[ 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 turtle\n\ndef setup_screen():\n screen = turtle.Screen()\n screen.bgcolor(\"lightblue\")\n screen.title(\"Interactive Turtle Graphics\")\n \n return ...
trial_gpt4o_4
{ "original_instruction": "### Coding Assessment: Turtle Graphics Drawing with Events\n\n**Objective:**\nDemonstrate your understanding of the `turtle` module by creating an interactive drawing program using specified turtle graphics concepts.\n\n**Description:**\nCreate a turtle graphics program in Python where the ...
0.726666
Docs: Python310_7475
C
[ "setup_screen", "setup_turtle", "move_forward", "move_backward", "turn_left", "turn_right", "toggle_color", "draw_circle", "draw_square", "reset_screen", "main" ]
11
[ [ "draw_circle", "toggle_color" ], [ "draw_square", "toggle_color" ], [ "reset_screen", "main" ] ]
3
[]
false
[]
false
pytest
false
[]
true
f6ed6303f43a38344b23d97e1df99246458649c3
6fa604be81b664ec61c0fb1c03609c36709da268