version
stringclasses
1 value
style
stringclasses
2 values
subset
stringclasses
12 values
question_id
stringlengths
9
23
question
stringlengths
27
8.13k
solution
stringlengths
99
5.97k
test
stringlengths
105
4.45k
test_info
listlengths
0
13
gpt_pass_sequence
listlengths
1
10
gpt_pass_trial_num
int64
1
10
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
trials
dict
chosen_trial
stringclasses
10 values
metadata
dict
benchmark_similarity
float64
0.16
0.93
benchmark_instruction
stringclasses
1 value
benchmark_task_id
stringclasses
1 value
filter_reason
stringclasses
1 value
base_id
stringlengths
7
21
variant
stringclasses
2 values
top_function_names
listlengths
2
13
n_top_functions
int64
2
13
helper_call_edges
listlengths
1
16
n_helper_call_edges
int64
1
16
harness_functions
listlengths
0
3
structural_wrapper
bool
1 class
class_names
listlengths
0
5
has_class
bool
2 classes
test_kind
stringclasses
1 value
test_has_solution_import
bool
2 classes
third_party_imports
listlengths
0
5
stdlib_only
bool
2 classes
question_norm_sha1
stringlengths
40
40
solution_ast_sha1
stringlengths
40
40
v1.0
instruct
Docs
Docs: Python310_43979_I
### Advanced Coding Assessment Question: Managing PyCapsules **Objective**: Implement a Python C extension module that creates, manages, and verifies PyCapsule objects to encapsulate data and ensure data consistency throughout the module. ### Requirements: 1. **Create and Manage PyCapsules**: Write a Python C extens...
# solution.py from typing import Dict # Simulate the PyCapsule in Python class PyCapsule: def __init__(self, data, name, destructor): self.data = data self.name = name self.destructor = destructor # Dictionary to store PyCapsules by name capsules: Dict[str, PyCapsule] = {} def create_caps...
# test_solution.py from solution import ( create_capsule, get_capsule_data, set_capsule_data, is_capsule_valid, cleanup_capsules ) def test_create_and_get_capsule_data(): create_capsule(42, 'example.capsule') assert get_capsule_data('example.capsule') == 42 def test_set_capsule_data(): create_cap...
[]
[ 0, 0, 0, 0, 1, 0, 1, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from cffi import FFI\n\nffi = FFI()\n\nmodule_code = \"\"\"\n#include <Python.h>\n\nstatic PyObject *capsule_dict = NULL;\n\nstatic void capsule_destructor(PyObject *ca...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00043979", "row_id": 43979, "seed_ids": "[16]" }
0.356234
Docs: Python310_43979
I
[ "create_capsule", "get_capsule_data", "set_capsule_data", "is_capsule_valid", "capsule_destructor", "cleanup_capsules" ]
6
[ [ "create_capsule", "capsule_destructor" ] ]
1
[]
false
[ "PyCapsule" ]
true
pytest
true
[]
true
c996ccd28b16b2fd533a674474cb7d05782cfd2c
2b3c389eb07a99e603706b19db55bdc73cdbaac9
v1.0
instruct
Docs
Docs: Python310_44024_I
**Problem Statement: Asynchronous Task and Network Management with `asyncio`** You are tasked with writing an asynchronous Python program which simulates a simple network service monitoring system. The program should periodically fetch status updates from different servers and log the results. Additionally, it should ...
import asyncio import random async def fetch_status(server: str) -> str: delay = random.randint(1, 3) await asyncio.sleep(delay) return f"Status from {server}" async def log_status(server: str): try: status = await asyncio.wait_for(fetch_status(server), timeout=5) print(status) exc...
import asyncio import random from unittest.mock import patch, AsyncMock from solution import fetch_status, log_status # Since the actual implementation involves non-deterministic delays and network calls, # we will mock fetch_status to control the behavior and test log_status behavior @patch('solution.fetch_status'...
[]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\n\nasync def fetch_status(server: str) -> str:\n delay = random.randint(1, 3)\n await asyncio.sleep(delay)\n return f\"Status fro...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00044024", "row_id": 44024, "seed_ids": "[267]" }
0.646441
Docs: Python310_44024
I
[ "fetch_status", "log_status", "main" ]
3
[ [ "log_status", "fetch_status" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1afc56541a194bcf227b6362a0a304e1cbc32f7c
6de3d3bc734e53a9762425face97458fcff2a397
v1.0
instruct
Docs
Docs: Python310_44050_I
**Question: Debugging Tool Implementation** In this task, you will implement a Python function using the Python C API functions outlined in the provided documentation. This function will act as a debugging tool to retrieve and display the current state of execution, including calling function information and variable ...
import inspect import builtins def debug_info(): """ Prints debug information of the currently executing function, including its name, description, current line number, and all available local, global, and built-in variables. """ frame = inspect.currentframe().f_back if frame is not None: ...
from solution import debug_info, sample_function def test_debug_info(): import builtins from io import StringIO import sys old_stdout = sys.stdout sys.stdout = StringIO() # Call the sample function to initiate debug_info from within its frame sample_function(1, 2) output = sys.stdout...
[ { "docstring": "Prints debug information of the currently executing function, including its\nname, description, current line number, and all available local, global, and\nbuilt-in variables.", "function_declaration": "def debug_info():", "function_name": "debug_info", "parameter_list": "()" }, {...
[ 0, 0, 1, 0, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import inspect\n\ndef debug_info():\n \"\"\"\n This function prints the current execution state including \n function name, description, line number, and local...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00044050", "row_id": 44050, "seed_ids": "[51]" }
0.540146
Docs: Python310_44050
I
[ "debug_info", "sample_function" ]
2
[ [ "sample_function", "debug_info" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7a554f88c3d6754e5f8cc082361492b243d630e3
1036effa4fe1e508cb352a42ecf0cfacc1613ca1
v1.0
instruct
Docs
Docs: Python310_44056_I
**Title: Efficient function memoization using `functools.lru_cache` & custom `partial` functions** #### Objective: Implement a function that utilizes `functools.lru_cache` to efficiently compute the value of a mathematical function while caching its results. In addition, create a partial function using `functools.part...
from functools import lru_cache, partial @lru_cache(maxsize=100) def compute_polynomial(a: int, b: int, c: int, x: int) -> int: return a * x * x + b * x + c def create_partial_polynomial(a: int, b: int, c: int): return partial(compute_polynomial, a, b, c)
from solution import compute_polynomial, create_partial_polynomial def test_compute_polynomial(): # Test polynomial: 2x^2 + 3x + 4 assert compute_polynomial(2, 3, 4, 1) == 9 assert compute_polynomial(2, 3, 4, 0) == 4 assert compute_polynomial(2, 3, 4, -1) == 3 assert compute_polynomial(2, 3, 4, 2) ...
[ { "docstring": null, "function_declaration": "def compute_polynomial(a, b, c, x):", "function_name": "compute_polynomial", "parameter_list": "(a, b, c, x)" }, { "docstring": null, "function_declaration": "def create_partial_polynomial(a, b, c):", "function_name": "create_partial_poly...
[ 0, 0, 0, 0, 0, 1, 0, 1, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from functools import lru_cache, partial\n\n@lru_cache(maxsize=100)\ndef compute_polynomial(a: int, b: int, c: int, x: int) -> int:\n \"\"\"\n Returns the value o...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00044056", "row_id": 44056, "seed_ids": "[236]" }
0.494098
Docs: Python310_44056
I
[ "compute_polynomial", "create_partial_polynomial" ]
2
[ [ "create_partial_polynomial", "compute_polynomial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
32191bbbb20ba43ea37dee9d55f158cb03dc0aff
dc01f5f0081937e9b69fd664e62dce88b00cdb88
v1.0
instruct
Docs
Docs: Python310_44061_I
## Coding Assessment Question: Synchronization of Generator Operations ### Objective Demonstrate your understanding of Python 3.8+ generator expressions, custom functions, synchronization, and complex expression handling in Python. ### Problem Statement You are tasked with creating a system that processes a series of...
def data_stream(data): """ Generator that yields squared values of even numbers from the input list. """ for value in data: if value % 2 == 0: yield value ** 2 def filtered_stream(data, threshold): """ Generator that filters values from data_stream based on a threshold. ...
from solution import data_stream, filtered_stream, stream_processor def test_data_stream(): data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] output = list(data_stream(data)) assert output == [4, 16, 36, 64, 100] def test_filtered_stream(): data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] threshold = 10 output = l...
[ { "docstring": "Generator that yields squared values of even numbers from the input list.", "function_declaration": "def data_stream(data):", "function_name": "data_stream", "parameter_list": "(data)" }, { "docstring": "Generator that filters values from data_stream based on a threshold.\nYi...
[ 0, 1, 0, 1, 0, 0, 1, 1, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def data_stream(data):\n \"\"\"\n Generator function that yields squared values of even numbers from the input list.\n \"\"\"\n for value in data:\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00044061", "row_id": 44061, "seed_ids": "[98]" }
0.525558
Docs: Python310_44061
I
[ "data_stream", "filtered_stream", "stream_processor" ]
3
[ [ "filtered_stream", "data_stream" ], [ "stream_processor", "filtered_stream" ] ]
2
[]
false
[]
false
pytest
true
[]
true
65b829240d570271dddcf13069f8318e8f720896
4a810599b782077a66b0b9f31ca5d62a466f362c
v1.0
instruct
Docs
Docs: Python310_44141_I
#### Objective: You are to demonstrate your understanding of Python's functional programming capabilities by implementing a custom iterator and a generator, as well as utilizing `itertools` and `functools` library functions. #### Task: 1. **Custom Range Iterator** Implement a custom iterator class `CustomRange` tha...
import itertools import functools import math class CustomRange: def __init__(self, start, stop, step=1): self.start = start self.stop = stop self.step = step def __iter__(self): current = self.start if self.step > 0: while current < self.stop: ...
from solution import CustomRange, prime_numbers, process_primes_and_range def test_custom_range(): assert list(CustomRange(1, 10, 2)) == [1, 3, 5, 7, 9] assert list(CustomRange(10, 1, -3)) == [10, 7, 4] assert list(CustomRange(0, 5, 1)) == [0, 1, 2, 3, 4] assert list(CustomRange(-5, 5, 2)) == [-5, -3, ...
[]
[ 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 itertools\nimport functools\n\nclass CustomRange:\n def __init__(self, start, stop, step=1):\n self.start = start\n self.stop = stop\n se...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00044141", "row_id": 44141, "seed_ids": "[78]" }
0.709895
Docs: Python310_44141
I
[ "prime_numbers", "process_primes_and_range" ]
2
[ [ "process_primes_and_range", "prime_numbers" ] ]
1
[]
false
[ "CustomRange" ]
true
pytest
true
[]
true
6b637c501a86b1e53954a27ac3be43a87fb43171
955390ed57ba2379b3330002dc127270e6d21d30
v1.0
instruct
Docs
Docs: Python310_44158_I
### Concurrent Data Processing and Synchronization You are tasked with creating a system that processes a large dataset concurrently, divides the workload across multiple threads, and uses inter-process communication to aggregate results. This problem will help assess your understanding of both thread-based and proces...
from typing import List from threading import Thread from multiprocessing import Process, Queue def split_list(data: List[int], n: int) -> List[List[int]]: """ Split the input list `data` into `n` equal parts. If the list cannot be divided equally, distribute the remaining elements. """ length = l...
import pytest from solution import split_list, compute_partial_sum, compute_sum_multithreaded, aggregate_sums, concurrent_sum def test_split_list(): assert split_list([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) == [[1, 2, 3], [4, 5, 6], [7, 8, 9]] assert split_list([1, 2, 3, 4, 5, 6], 4) == [[1, 2], [3, 4], [5], [6]] ...
[ { "docstring": "Split the input list `data` into `n` equal parts. If the list cannot be divided \nequally, distribute the remaining elements.", "function_declaration": "def split_list(data, n):", "function_name": "split_list", "parameter_list": "(data, n)" }, { "docstring": "Compute the sum ...
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport threading\nfrom multiprocessing import Process, Queue\n\ndef split_list(data: List[int], n: int) -> List[List[int]]:\n \"\"\"\n Sp...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00044158", "row_id": 44158, "seed_ids": "[206]" }
0.566753
Docs: Python310_44158
I
[ "split_list", "compute_partial_sum", "compute_sum_multithreaded", "aggregate_sums", "concurrent_sum" ]
5
[ [ "compute_sum_multithreaded", "compute_partial_sum" ], [ "compute_sum_multithreaded", "split_list" ], [ "concurrent_sum", "aggregate_sums" ], [ "concurrent_sum", "compute_sum_multithreaded" ] ]
4
[]
false
[]
false
pytest
true
[]
true
3c5947e9107ab308e8a58a128a729c67c9d18aaf
dd90648eb5cb9d64d5e7464840a1e425d8046850
v1.0
instruct
Docs
Docs: Python310_44162_I
### Asynchronous Event Loop Configuration and Platform-Specific Implementation #### Problem Statement You are tasked with implementing a Python application that needs to run different event loop configurations based on the operating system it is running on. Your application will handle socket connections and subproce...
import sys import platform import asyncio import selectors async def subprocess_demo(): process = await asyncio.create_subprocess_exec( 'python', '--version', stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await process.communicate() print...
import platform import asyncio from solution import configure_event_loop, run_demo def test_configure_event_loop(): current_os = platform.system() configure_event_loop() if current_os == 'Windows': current_loop = asyncio.get_event_loop() assert isinstance(current_loop, asyncio.ProactorEvent...
[ { "docstring": null, "function_declaration": "def configure_event_loop():", "function_name": "configure_event_loop", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def run_demo():", "function_name": "run_demo", "parameter_list": "()" } ]
[ 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 sys\nimport platform\nimport asyncio\nimport selectors\n\nasync def subprocess_demo():\n process = await asyncio.create_subprocess_exec(\n 'python', '-...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00044162", "row_id": 44162, "seed_ids": "[370]" }
0.543766
Docs: Python310_44162
I
[ "subprocess_demo", "server_socket_demo", "configure_event_loop", "run_demo" ]
4
[ [ "run_demo", "configure_event_loop" ], [ "run_demo", "server_socket_demo" ], [ "run_demo", "subprocess_demo" ] ]
3
[]
false
[]
false
pytest
true
[]
true
49550d59399dc49d685113d4db31a36cf5dc89ac
06b6ac33cfec387ca659aba5bf22a55dc4433bde
v1.0
instruct
Docs
Docs: Python310_44167_I
**Secure File Integrity Verifier** You are tasked to implement a utility that verifies the integrity of files using secure hash functions. The program should have two parts: 1. **Hash Generation**: Read a file and generate a hash digest using a specified hash algorithm. 2. **Hash Verification**: Compare the hash diges...
import hashlib def generate_file_hash(file_path: str, hash_alg: str) -> str: """ Generates the hash digest of a file using the specified hash algorithm. :param file_path: Path to the file :param hash_alg: Hash algorithm to use (md5, sha1, sha256, sha512, blake2b, blake2s) :return: Hexadecimal ...
import os import pytest from solution import generate_file_hash, verify_file_integrity # Helper function to create a temporary test file def create_temp_file(filename, content): with open(filename, "w") as f: f.write(content) def test_generate_file_hash_md5(tmpdir): filename = tmpdir.join("testfile.tx...
[ { "docstring": "Generates the hash digest of a file using the specified hash algorithm.\n\n:param file_path: Path to the file\n:param hash_alg: Hash algorithm to use (md5, sha1, sha256, sha512, blake2b, blake2s)\n:return: Hexadecimal hash digest of the file content", "function_declaration": "def generate_fi...
[ 1, 1, 1, 1, 0, 1, 0, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\n\nSUPPORTED_ALGORITHMS = {\n 'md5': hashlib.md5,\n 'sha1': hashlib.sha1,\n 'sha256': hashlib.sha256,\n 'sha512': hashlib.sha512,\n 'blake...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00044167", "row_id": 44167, "seed_ids": "[225]" }
0.635614
Docs: Python310_44167
I
[ "generate_file_hash", "verify_file_integrity" ]
2
[ [ "verify_file_integrity", "generate_file_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9f07210b040b58979c0c313452490f23e5ac46c2
bc23058fe5bb7863c6a4fbef46ed3b22a1ad288d
v1.0
instruct
Docs
Docs: Pytorch_44184_I
### PyTorch Accelerator Management In this task, you are required to write a few functions using PyTorch's `torch.accelerator` module to manage device resources and synchronize operations. This will demonstrate your understanding of handling GPUs in PyTorch. #### Task 1: Check Device Availability Write a function `ch...
import torch def check_device_availability() -> bool: """ Checks if any accelerators are available. Returns: bool: True if at least one accelerator is available, False otherwise. """ return torch.cuda.is_available() def get_current_device() -> int: """ Gets the current accelerator...
from solution import check_device_availability, get_current_device, set_device_by_index, synchronize_device, test_accelerator_module def test_check_device_availability(): assert isinstance(check_device_availability(), bool) def test_set_and_get_current_device(): if check_device_availability(): set_dev...
[ { "docstring": "Checks if any accelerators are available.\n\nReturns:\nbool: True if at least one accelerator is available, False otherwise.", "function_declaration": "def check_device_availability():", "function_name": "check_device_availability", "parameter_list": "()" }, { "docstring": "G...
[ 1, 0, 1, 0, 0, 1, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef check_device_availability() -> bool:\n \"\"\"\n Checks if any accelerators are available.\n \n Returns:\n bool: True if at least one ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00044184", "row_id": 44184, "seed_ids": "[19]" }
0.365054
Docs: Pytorch_44184
I
[ "check_device_availability", "get_current_device", "set_device_by_index", "synchronize_device", "test_accelerator_module" ]
5
[ [ "test_accelerator_module", "check_device_availability" ], [ "test_accelerator_module", "get_current_device" ], [ "test_accelerator_module", "set_device_by_index" ], [ "test_accelerator_module", "synchronize_device" ] ]
4
[]
false
[]
false
pytest
true
[ "torch" ]
false
a7283049497977a1b01f425f92dfb5c89a64bd12
cee6a43a93d3e1387b23257ccd42efa7476eae6d
v1.0
instruct
Docs
Docs: Python310_44269_I
### Function Object Manipulation in Python Using the provided functions, your task is to create a set of utility functions in Python using the C API to perform specific operations on Python function objects. You will implement the following functions: 1. **is_function(obj)**: Given a PyObject, check if it is a funct...
import types def is_function(obj): """ Check if the object is a function. """ return isinstance(obj, types.FunctionType) def create_function(code_obj, globals_dict, qualname=None): """ Create a new function object given a code object, globals dictionary, and optionally, a qualified name. ...
import pytest import types from solution import is_function, create_function, get_function_details, set_function_defaults, set_function_annotations def dummy_function(a, b=2): """ A dummy function for testing purposes. """ return a + b def test_is_function(): assert is_function(dummy_function) ==...
[ { "docstring": "Check if the object is a function.", "function_declaration": "def is_function(obj):", "function_name": "is_function", "parameter_list": "(obj)" }, { "docstring": "Create a new function object given a code object, globals dictionary, and optionally,\na qualified name.", "f...
[ 1, 1, 0, 0, 1, 1, 0, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import types\n\ndef is_function(obj):\n \"\"\"\n Check if the given object is a function.\n \"\"\"\n return isinstance(obj, types.FunctionType)\n\ndef creat...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00044269", "row_id": 44269, "seed_ids": "[2]" }
0.683827
Docs: Python310_44269
I
[ "is_function", "create_function", "get_function_details", "set_function_defaults", "set_function_annotations" ]
5
[ [ "get_function_details", "is_function" ], [ "set_function_annotations", "is_function" ], [ "set_function_defaults", "is_function" ] ]
3
[]
false
[]
false
pytest
true
[]
true
cf31455731a3d242af5f5dcbc0794358fa6dbe20
d3260fe30bb9287adf5ca4aa421d5783eb49fc3d
v1.0
instruct
Docs
Docs: Python310_44272_I
### Question: Implementing a Parallel Web Scraper using Python's `multiprocessing` Module You are assigned to develop a web scraping utility that extracts data from a list of URLs concurrently. Your solution should leverage Python's `multiprocessing` module for efficiency and scalability. ### Requirements: 1. **Fun...
import requests from multiprocessing import Pool, Manager def fetch_data(url): """ Fetch the HTML content from the provided URL and returns the URL and the content length. """ response = requests.get(url) return url, len(response.content) def parallel_scraper(urls, num_workers): """ Fetch ...
from solution import fetch_data, parallel_scraper import requests def test_fetch_data(monkeypatch): class MockResponse: def __init__(self, content): self.content = content def mock_get(url): return MockResponse(b"Test content") monkeypatch.setattr(requests, "get", mock_get) ...
[ { "docstring": "Fetch the HTML content from the provided URL and returns the URL and the content length.", "function_declaration": "def fetch_data(url):", "function_name": "fetch_data", "parameter_list": "(url)" }, { "docstring": "Fetch data from a list of URLs concurrently using a pool of w...
[ 0, 1, 0, 1, 1, 0, 1, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom multiprocessing import Pool\n\ndef fetch_data(url):\n \"\"\"\n Fetches HTML content from the provided URL.\n\n Parameters:\n url (str)...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00044272", "row_id": 44272, "seed_ids": "[338]" }
0.575038
Docs: Python310_44272
I
[ "fetch_data", "parallel_scraper" ]
2
[ [ "parallel_scraper", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
d98f5ef0c339cd3bec1bffac68bf27c5c7277748
b0addfecc3728fa2d9e098bf2afb9ffdcd91439c
v1.0
instruct
Docs
Docs: Python310_44289_I
#### Problem Statement You are tasked with developing a simple multi-threaded web scraper using the `_thread` module in Python. The scraper will query a list of URLs and store the HTML content in a dictionary. To ensure thread safety when accessing the shared dictionary, you must use lock mechanisms. #### Requirement...
import _thread import requests from time import sleep # Global dictionary to store web content WEB_CONTENT = {} def fetch_content(url, lock): try: response = requests.get(url) lock.acquire() try: WEB_CONTENT[url] = response.text finally: lock.release() e...
from solution import scrape_urls, WEB_CONTENT import _thread def test_scrape_urls_with_valid_urls(): urls = ["http://example.com"] scrape_urls(urls) assert "http://example.com" in WEB_CONTENT assert WEB_CONTENT["http://example.com"].startswith("<!doctype html>") or WEB_CONTENT["http://example.com"...
[ { "docstring": null, "function_declaration": "def fetch_content(url, lock):", "function_name": "fetch_content", "parameter_list": "(url, lock)" }, { "docstring": null, "function_declaration": "def scrape_urls(url_list):", "function_name": "scrape_urls", "parameter_list": "(url_li...
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import _thread\nimport requests\n\n# Global dictionary to store web content\nWEB_CONTENT = {}\n\ndef fetch_content(url, lock):\n \"\"\"\n Fetches the HTML content...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00044289", "row_id": 44289, "seed_ids": "[223]" }
0.657904
Docs: Python310_44289
I
[ "fetch_content", "scrape_urls" ]
2
[ [ "scrape_urls", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
a181b2ef14ec711eb85773b9d5d137dec9ab5033
1065e41982192811af454804e1b02595b6a053f9
v1.0
instruct
Docs
Docs: Python310_44300_I
### Complex Logging Configuration and Custom Filtering **Objective:** Implement a structured logging system using the Python logging module. The logging configuration should demonstrate the ability to: 1. Set up multiple loggers with different logging levels. 2. Create custom handlers to direct log messages to specifi...
import logging class ContextFilter(logging.Filter): def __init__(self, user): super().__init__() self.user = user def filter(self, record): record.user = self.user return True def setup_logging(): user = "test_user" # assuming user is predefined # Creating and co...
import pytest import os import logging from solution import setup_logging, log_messages, ContextFilter def test_logging_system(): # Set up loggers app_logger, audit_logger = setup_logging() # Ensure loggers are configured correctly assert app_logger.level == logging.DEBUG assert audit_logger.l...
[]
[ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import logging\n\nclass ContextFilter(logging.Filter):\n def __init__(self, user):\n super().__init__()\n self.user = user\n\n def filter(self, reco...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00044300", "row_id": 44300, "seed_ids": "[250]" }
0.652735
Docs: Python310_44300
I
[ "setup_logging", "log_messages" ]
2
[ [ "log_messages", "setup_logging" ] ]
1
[]
false
[ "ContextFilter" ]
true
pytest
true
[]
true
f48f7b623859a2ecbcb5221a28a792ab95dc8416
aca09bbe59466e5a0fa699daed80e9f7922afc6e
v1.0
instruct
Docs
Docs: Python310_44309_I
**Problem Statement:** You are given a set of CSV files that hold information about books in a library. Each file has a different structure, and they all come from different sources. Your task is to: 1. Create a function `parse_csv(file_name, delimiter, quotechar, quoting, has_header)` that reads a CSV file and retur...
import csv def parse_csv(file_name, delimiter, quotechar, quoting, has_header): """ Parses a CSV file and returns the data in structured format. Parameters: - file_name (string): The name of the CSV file. - delimiter (char): The character that separates fields in the CSV file. - quotechar ...
import pytest import csv from solution import parse_csv, merge_csv def create_test_file(file_name, content): with open(file_name, mode='w', newline='', encoding='utf-8') as file: file.write(content) def test_parse_csv_with_header(): content = 'name,age\nAlice,30\nBob,25\n' create_test_file('test_w...
[ { "docstring": "Parses a CSV file and returns the data in structured format.\n\nParameters:\n- file_name (string): The name of the CSV file.\n- delimiter (char): The character that separates fields in the CSV file.\n- quotechar (char): The character used to quote fields containing special characters.\n- quoting...
[ 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def parse_csv(file_name, delimiter, quotechar, quoting, has_header):\n import csv\n result = []\n try:\n with open(file_name, mode='r', newline='', enco...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00044309", "row_id": 44309, "seed_ids": "[272]" }
0.71976
Docs: Python310_44309
I
[ "parse_csv", "merge_csv" ]
2
[ [ "merge_csv", "parse_csv" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6518cb12ec702b96a3e3d24f17cb4ac4c97c8959
096dd3c30d9de63175b7a86c70334c8b4c5e8733
v1.0
instruct
Docs
Docs: Python310_44493_I
### Python Coding Assessment Question: Method Binding **Objective**: Implement a Python function that programmatically binds a given callable to an instance of a user-defined class and retrieves the callable from the bound method. **Description**: You are given a class `MyClass` and a function `my_function`. You need...
import ctypes import inspect # Load the Python C-API pythonapi = ctypes.PyDLL(None) class PyObject(ctypes.Structure): pass PyObject._fields_ = [("ob_refcnt", ctypes.c_long), ("ob_type", ctypes.POINTER(PyObject))] # Define C-API functions used PyMethod_New = pythonapi.PyMethod_New PyMethod_New.argtypes = [ctypes...
def test_create_and_retrieve_bound_method(): class MyClass: def __init__(self, name): self.name = name def my_function(self): return f"Hello, {self.name}!" instance = MyClass("Alice") bound_method = create_bound_method(my_function, instance) assert callable(boun...
[]
[ 1, 1, 1, 1, 0, 0, 0, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import ctypes\nimport inspect\n\n# Load the Python C-API\npythonapi = ctypes.PyDLL(None)\n\nclass PyObject(ctypes.Structure):\n pass\n\nPyObject._fields_ = [(\"ob_re...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00044493", "row_id": 44493, "seed_ids": "[36]" }
0.551897
Docs: Python310_44493
I
[ "get_pyobject_pointer", "get_python_function", "create_bound_method", "get_bound_method_function", "my_function" ]
5
[ [ "create_bound_method", "get_pyobject_pointer" ], [ "get_bound_method_function", "get_pyobject_pointer" ], [ "get_bound_method_function", "get_python_function" ] ]
3
[]
false
[ "PyObject", "MyClass" ]
true
pytest
false
[]
true
8a2c6f45516a6d0ace6f76773313e12ca7a76d4e
97d788c557f094d0156bce95a8f6e0e9ef5a0fec
v1.0
instruct
Docs
Docs: Python310_44499_I
### Advanced Python Coding Assessment: Custom Exception Handling in Asyncio #### Objective: You are required to demonstrate your understanding of handling custom exceptions in Python’s `asyncio` module. This task will involve writing an asynchronous function that processes data and appropriately handles these custom e...
import asyncio async def process_data_streams(sources: list, timeout: float) -> dict: """ Processes data from multiple sources asynchronously. Parameters: sources (list): A list of asynchronous data source callables. timeout (float): Timeout duration for each data fetching task. Returns: ...
import pytest from solution import process_data_streams import asyncio async def mock_success_data_source(data, delay): await asyncio.sleep(delay) return data async def mock_failure_incomplete_read_data_source(delay): await asyncio.sleep(delay) raise asyncio.IncompleteReadError(10, b"partial data") a...
[]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def process_data_streams(sources: list, timeout: float) -> dict:\n \"\"\"\n Processes data from multiple sources asynchronously.\n \n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00044499", "row_id": 44499, "seed_ids": "[396]" }
0.508729
Docs: Python310_44499
I
[ "process_data_streams", "fetch_data" ]
2
[ [ "process_data_streams", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2fc546c44c9c830cee7d8359943840ac29874c72
cc06bf85040d87f5c1063ff56fb195c1b476d68f
v1.0
instruct
Docs
Docs: Pytorch_44500_I
**Question:** In this assessment, you are required to implement a function that performs a series of tests to ensure the correctness of tensor operations. Specifically, you will: 1. Generate a tensor using the `make_tensor` function. 2. Perform a mathematical operation on the generated tensor. 3. Manually create an e...
import torch import torch.testing as tt def make_tensor(shape, dtype, low, high, pin_memory): """ Helper function to generate a tensor with given shape, dtype, range and memory pinning. """ return torch.empty(shape, dtype=dtype).uniform_(low, high) def test_tensor_operations(): """ Function to...
import torch import torch.testing as tt from solution import test_tensor_operations, make_tensor def test_tensor_operations_correctness(): """ Test to verify the tensor operations. """ test_tensor_operations() def test_make_tensor(): """ Test to verify the make_tensor function. """ sha...
[ { "docstring": "Helper function to generate a tensor with given shape, dtype, range and memory pinning.", "function_declaration": "def make_tensor(shape, dtype, low, high, pin_memory):", "function_name": "make_tensor", "parameter_list": "(shape, dtype, low, high, pin_memory)" }, { "docstring...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.testing as tt\n\ndef test_tensor_operations():\n # Generate tensor A\n A = tt.make_tensor(shape=(3, 3), dtype=torch.float, low=-10, hig...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00044500", "row_id": 44500, "seed_ids": "[128]" }
0.566938
Docs: Pytorch_44500
I
[ "make_tensor", "test_tensor_operations" ]
2
[ [ "test_tensor_operations", "make_tensor" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
3c63578769c890b38b23982c55432f89f3eabfb4
6cab64026bbb86d8e7faba17d06df6ff12a4066c
v1.0
instruct
Docs
Docs: Python310_44532_I
**Question: Implement a Custom Interactive Shell with Logging** **Objective:** Create a custom interactive shell that mimics a simplified version of the Unix shell. Your shell should be able to execute commands entered by the user interactively and log all input commands and their respective output to a file. Use the ...
import os import pty import logging def master_read(fd, log_file): data = os.read(fd, 1024) if data: log_file.write(data.decode()) log_file.flush() return data def stdin_read(fd, log_file): data = os.read(fd, 1024) if data: log_file.write(data.decode()) log_file.flu...
import os import subprocess from solution import interactive_shell def test_interactive_shell_execution(): log_filename = 'test_session.log' # Remove log file if it exists if os.path.exists(log_filename): os.remove(log_filename) # Start the interactive shell in a subprocess to make it tes...
[ { "docstring": null, "function_declaration": "def master_read(fd, log_file):", "function_name": "master_read", "parameter_list": "(fd, log_file)" }, { "docstring": null, "function_declaration": "def stdin_read(fd, log_file):", "function_name": "stdin_read", "parameter_list": "(fd...
[ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport pty\nimport sys\n\ndef interactive_shell(log_filename):\n \"\"\"\n Starts an interactive shell session and logs all input commands and their res...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00044532", "row_id": 44532, "seed_ids": "[145]" }
0.44908
Docs: Python310_44532
I
[ "master_read", "stdin_read", "interactive_shell" ]
3
[ [ "interactive_shell", "master_read" ], [ "interactive_shell", "stdin_read" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3d28abfadb676c9eb5add65b892be91dce63b7f7
1268f5dbf73d24743692807c25736f8c9b72c746
v1.0
instruct
Docs
Docs: Python310_44542_I
### Advanced Python Comprehensions and Generators **Objective:** To assess the student's understanding of Python generator expressions, comprehensions, and their use in combination with asynchronous operations. **Problem Statement:** You are tasked with creating a Python module that processes a list of transactions ...
from typing import List, Dict, Union, AsyncGenerator import asyncio def read_transactions(transactions: List[Dict[str, Union[int, float]]]) -> List[Dict[str, Union[int, float]]]: """ Given a list of transactions, filter out the transactions where the amount is negative. :param transactions: List of tr...
import pytest import asyncio from solution import read_transactions, compute_summary, transaction_generator, process_transactions def test_read_transactions(): transactions = [ {'transaction_id': 1, 'amount': 50.0}, {'transaction_id': 2, 'amount': -20.0}, {'transaction_id': 3, 'amount': 30...
[ { "docstring": "Given a list of transactions, filter out the transactions where the amount is negative.\n\n:param transactions: List of transaction dictionaries.\n:return: List of filtered transactions with non-negative amounts.", "function_declaration": "def read_transactions(transactions):", "function...
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Dict, Union, AsyncGenerator\n\ndef read_transactions(transactions: List[Dict[str, Union[int, float]]]) -> List[Dict[str, Union[int, float]]]:\n...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00044542", "row_id": 44542, "seed_ids": "[98]" }
0.500052
Docs: Python310_44542
I
[ "read_transactions", "compute_summary", "transaction_generator", "process_transactions" ]
4
[ [ "process_transactions", "transaction_generator" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6480be9f92604e7caca6463741bc6f318a897fd1
b68b4eca8e0485097e11042301ae7c9bdee756ed
v1.0
instruct
Docs
Docs: Python310_44553_I
**Advanced Python Task: Context Management with `contextvars`** **Problem Statement:** You are to implement a Python module that manages user session data using the `contextvars` module. This module should allow storing, retrieving, and resetting user-specific session data in a thread-safe manner. This is particularl...
import contextvars # Creating a context variable to store session data session_data = contextvars.ContextVar("session_data", default={}) def initialize_session(session_id, data): """Initializes a new session with given session ID and associated data""" current_data = session_data.get() current_data[sessio...
import pytest from solution import (initialize_session_track_initial as initialize_session, get_session_data, update_session_data, reset_session_data) def test_initialize_session(): initialize_session("session1", {"user": "Alice", "role": "admin"...
[ { "docstring": "Initializes a new session with given session ID and associated data", "function_declaration": "def initialize_session(session_id, data):", "function_name": "initialize_session", "parameter_list": "(session_id, data)" }, { "docstring": "Retrieves the data associated with the g...
[ 0, 1, 1, 0, 0, 0, 1, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import contextvars\n\n# Context variable to store all session data\nsessions = contextvars.ContextVar('sessions', default={})\n\ndef initialize_session(session_id, data...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00044553", "row_id": 44553, "seed_ids": "[60]" }
0.508601
Docs: Python310_44553
I
[ "initialize_session", "get_session_data", "update_session_data", "reset_session_data", "initialize_session_track_initial" ]
5
[ [ "initialize_session_track_initial", "initialize_session" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6c76f6ba4686ad4cc61bff9631bbc062c82139b6
5504effed86010f8cbd1a87169c288ee55aca036
v1.0
instruct
Docs
Docs: Scikit_44558_I
Implementing Custom Pairwise Metrics and Kernels with Scikit-learn **Objective:** This task aims to assess your comprehension of pairwise metrics and kernel functions as provided by the `scikit-learn` package. You will implement custom metrics and kernels and then utilize them in a small machine learning task. **Part...
import numpy as np def manhattan_distance(a, b): """ Compute the Manhattan distance between two vectors. Parameters: a (np.ndarray): 1D array, the first vector. b (np.ndarray): 1D array, the second vector. Returns: float: The Manhattan distance between vectors a and b. """ ...
import numpy as np from solution import manhattan_distance, rbf_kernel, custom_rbf_kernel def test_manhattan_distance(): assert manhattan_distance(np.array([1, 2, 3]), np.array([4, 5, 6])) == 9 assert manhattan_distance(np.array([0, 0]), np.array([0, 0])) == 0 assert manhattan_distance(np.array([1, -1]), n...
[ { "docstring": "Compute the Manhattan distance between two vectors.\n\nParameters:\na (np.ndarray): 1D array, the first vector.\nb (np.ndarray): 1D array, the second vector.\n\nReturns:\nfloat: The Manhattan distance between vectors a and b.", "function_declaration": "def manhattan_distance(a, b):", "fu...
[ 0, 1, 1, 1, 1, 0, 0, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef manhattan_distance(a, b):\n \"\"\"\n Compute the Manhattan distance between two vectors.\n \n Parameters:\n a (ndarray): 1D arr...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00044558", "row_id": 44558, "seed_ids": "[38]" }
0.512899
Docs: Scikit_44558
I
[ "manhattan_distance", "rbf_kernel", "custom_rbf_kernel" ]
3
[ [ "custom_rbf_kernel", "rbf_kernel" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
fa055a7de74f275848cfb9d43d4a884accc9269f
12da5883d92e4dc7a5c99b53e38f9cd7c3474d4d
v1.0
instruct
Docs
Docs: Python310_44590_I
### Memory Management with Python and C API #### Objective: Your task is to simulate a basic custom memory allocation setup using Python's memory management C API calls described in the provided documentation. #### Problem Statement: You need to implement a Python extension that creates custom allocator functions and...
import ctypes import logging # Configuration to output logs to the console logging.basicConfig(level=logging.DEBUG, format='%(message)s') class MyAllocator: @staticmethod def malloc(size): logging.info("Allocating memory") return ctypes.create_string_buffer(size) @staticmethod def...
from solution import set_custom_allocator, reset_allocator, custom_allocate, custom_reallocate, custom_free, test_custom_allocator def test_set_custom_allocator(): set_custom_allocator() # No outputs, just ensure no exceptions def test_reset_allocator(): reset_allocator() # No outputs, just ensure...
[]
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import ctypes\nimport logging\n\n# Set up logging\nlogging.basicConfig(level=logging.DEBUG, format='%(message)s')\nlogger = logging.getLogger(__name__)\n\nclass MyAlloc...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00044590", "row_id": 44590, "seed_ids": "[46]" }
0.441987
Docs: Python310_44590
I
[ "set_custom_allocator", "reset_allocator", "custom_allocate", "custom_reallocate", "custom_free", "test_custom_allocator" ]
6
[ [ "test_custom_allocator", "custom_allocate" ], [ "test_custom_allocator", "custom_free" ], [ "test_custom_allocator", "custom_reallocate" ], [ "test_custom_allocator", "reset_allocator" ], [ "test_custom_allocator", "set_custom_allocator" ] ]
5
[]
false
[ "MyAllocator" ]
true
pytest
true
[]
true
36921e1deacf2461d1610fbef540c519e10507bb
048bc7b6d7d80927e3cce6e14eede6e2be34f389
v1.0
instruct
Docs
Docs: Scikit_44600_I
### Out-of-Core Learning for Text Classification #### Objective Build an out-of-core learning system to classify text documents into different categories using scikit-learn. The system will stream data from a file, extract features using a stateless feature extractor, and incrementally train a classifier. #### Requir...
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score from scipy.sparse import vstack import numpy as np def stream_data(file_path, batch_size): """ Streams data from the file in mini-batches of size 'batch_size'....
from solution import stream_data, extract_features, train_out_of_core import os def test_stream_data(): test_file_path = 'test_data.txt' with open(test_file_path, 'w') as file: file.write("text_document_1\tcategory_1\n") file.write("text_document_2\tcategory_2\n") file.write("text_docum...
[ { "docstring": "Streams data from the file in mini-batches of size 'batch_size'.\n\nYields tuples of (text data, labels).", "function_declaration": "def stream_data(file_path, batch_size):", "function_name": "stream_data", "parameter_list": "(file_path, batch_size)" }, { "docstring": "Transf...
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00044600", "row_id": 44600, "seed_ids": "[63]" }
0.535634
Docs: Scikit_44600
I
[ "stream_data", "extract_features", "train_out_of_core" ]
3
[ [ "train_out_of_core", "extract_features" ], [ "train_out_of_core", "stream_data" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "scipy", "sklearn" ]
false
81466cd4e1d838a0194823111066bfbe42efe320
785eb358e831a32e5c1f74f93f2bf4d894197b0f
v1.0
instruct
Docs
Docs: Python310_44603_I
### Advanced Coding Assessment Question #### Objective: To assess the comprehension of advanced XML and DOM operations using the `xml.dom.minidom` module in Python. #### Problem Statement: You are tasked with developing a new XML-based configuration management system. The configuration files will be in XML format, an...
from xml.dom.minidom import parse, Document import xml.dom.minidom def dict_from_element(element) -> dict: node_dict = {} for node in element.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.hasChildNodes() and any(child.nodeType == child.ELEMENT_NODE for child in node.childNodes)...
import pytest import os from xml.dom.minidom import parseString from solution import read_config, modify_config, save_config @pytest.fixture def sample_xml(tmp_path): content = '''<config> <database> <host>localhost</host> <port>3306</port> ...
[ { "docstring": null, "function_declaration": "def dict_from_element(element):", "function_name": "dict_from_element", "parameter_list": "(element)" }, { "docstring": null, "function_declaration": "def element_from_dict(document, tag, content):", "function_name": "element_from_dict", ...
[ 0, 0, 0, 1, 1, 0, 1, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from xml.dom.minidom import parse, parseString, Document\nfrom xml.etree.ElementTree import Element, tostring, fromstring\n\ndef read_config(file_path: str) -> dict:\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00044603", "row_id": 44603, "seed_ids": "[287]" }
0.638068
Docs: Python310_44603
I
[ "dict_from_element", "element_from_dict", "read_config", "modify_config", "save_config" ]
5
[ [ "read_config", "dict_from_element" ], [ "save_config", "element_from_dict" ] ]
2
[]
false
[]
false
pytest
true
[]
true
8407081d2061c6b5ea2e16d3c51e7da9708c031e
30e270775b6224dcd13c885af77d6e5035ed0e2b
v1.0
instruct
Docs
Docs: Python310_44613_I
#### Objective Design a command-line tool using the `optparse` module. This tool is intended to be a utility for managing a simple to-do list stored in a file. The tool should provide various commands to add tasks, list tasks, mark tasks as completed, and remove tasks. #### Requirements 1. **Initialization** - T...
import os import json from optparse import OptionParser TODO_TEMPLATE = { "tasks": [] } def load_todo_list(filename): if not os.path.isfile(filename): with open(filename, 'w') as f: json.dump(TODO_TEMPLATE, f) with open(filename, 'r') as f: return json.load(f) def save_todo_li...
import os import pytest from solution import add_task, list_tasks, mark_as_complete, remove_task, load_todo_list, save_todo_list TEST_FILE = 'test_todo_list.json' def setup_module(module): """ setup any state specific to the execution of the given module.""" if os.path.isfile(TEST_FILE): os.remove(TES...
[ { "docstring": null, "function_declaration": "def load_todo_list(filename):", "function_name": "load_todo_list", "parameter_list": "(filename)" }, { "docstring": null, "function_declaration": "def save_todo_list(filename, todo_list):", "function_name": "save_todo_list", "paramete...
[ 1, 1, 1, 1, 0, 1, 1, 0, 0, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport json\nfrom optparse import OptionParser\n\nTODO_TEMPLATE = {\n \"tasks\": []\n}\n\ndef load_todo_list(filename):\n if not os.path.isfile(filenam...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00044613", "row_id": 44613, "seed_ids": "[209]" }
0.49562
Docs: Python310_44613
I
[ "load_todo_list", "save_todo_list", "add_task", "list_tasks", "mark_as_complete", "remove_task", "main" ]
7
[ [ "add_task", "load_todo_list" ], [ "add_task", "save_todo_list" ], [ "list_tasks", "load_todo_list" ], [ "mark_as_complete", "load_todo_list" ], [ "mark_as_complete", "save_todo_list" ], [ "remove_task", "load_todo_list" ], [ "remove_task"...
7
[]
false
[]
false
pytest
true
[]
true
8f9056db00a95bc9d6bc9efd58dc073e9ef942b9
cfb7403bde7f166f2aac6f4ef381687cd1cb3c50
v1.0
instruct
Docs
Docs: Scikit_44616_I
**Title:** Data Loading and Preprocessing from OpenML with Scikit-Learn **Objective:** The goal of this task is to assess your understanding of loading datasets from OpenML, handling and preprocessing the data, and implementing a basic machine learning model using scikit-learn. **Problem Statement:** You are provi...
import numpy as np from sklearn.datasets import fetch_openml from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder, StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer from s...
import pytest from solution import load_and_preprocess_data, train_and_evaluate def test_load_and_preprocess_data(): X_train, X_test, y_train, y_test = load_and_preprocess_data() assert X_train.shape[0] > 0 assert X_test.shape[0] > 0 assert y_train.shape[0] > 0 assert y_test.shape[0] > 0 a...
[ { "docstring": "Fetches the Mice Protein Expression dataset from OpenML, preprocesses it and returns the preprocessed data.\n\nReturn:\nTuple containing:\n- X_train: Features for training\n- X_test: Features for testing\n- y_train: Labels for training\n- y_test: Labels for testing", "function_declaration": ...
[ 1, 1, 0, 0, 1, 1, 0, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.datasets import fetch_openml\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nf...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00044616", "row_id": 44616, "seed_ids": "[6]" }
0.490989
Docs: Scikit_44616
I
[ "load_and_preprocess_data", "train_and_evaluate" ]
2
[ [ "train_and_evaluate", "load_and_preprocess_data" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
c7049f56e398caab6ff4b69496c013359df63e55
4f3862ab87e061d9ab02066b62cf4768bba592d6
v1.0
instruct
Docs
Docs: Python310_44674_I
### Concurrent Task Management Using `concurrent.futures` #### Objective: Implement a function that processes a list of URLs concurrently and returns the contents of each URL using the `concurrent.futures` module. #### Problem Statement: You are given a list of URLs. Your task is to implement a function `fetch_all_ur...
import requests from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List def fetch_url(url: str) -> str: """ Fetches the content of the given URL. Args: - url: The URL as a string. Returns: - The content of the URL as a string. If an exception occurs, re...
from solution import fetch_all_urls import requests from unittest.mock import patch def test_fetch_all_urls_success(): urls = [ "http://example.com", "http://example.org", "http://example.net" ] responses = ["<html>Example Com</html>", "<html>Example Org</html>", "<html>Example...
[ { "docstring": "Fetches the content of the given URL.\n\nArgs:\n- url: The URL as a string.\n\nReturns:\n- The content of the URL as a string. If an exception occurs, returns an empty string.", "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_list": "(url)" }...
[ 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 requests\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List\n\ndef fetch_url(url: str) -> str:\n try:\n response...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00044674", "row_id": 44674, "seed_ids": "[224]" }
0.518069
Docs: Python310_44674
I
[ "fetch_url", "fetch_all_urls" ]
2
[ [ "fetch_all_urls", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
be3a5de339aa52f5064f07c9f6b04ac645636856
50fb87c59a74cc36e21459c6a53eb8e0d5974dc8
v1.0
instruct
Docs
Docs: Pytorch_44725_I
### PyTorch Distributed RPC and RRef Protocol Implementation **Objective:** Design and implement a function to calculate the sum of tensors located on different workers using PyTorch's distributed RPC and RRef protocol. **Task:** You are required to implement a function `distributed_tensor_sum` that calculates the ...
import torch import torch.distributed.rpc as rpc from torch.distributed.rpc import RRef import os def remote_tensor_sum(*tensors): """ Returns the sum of the given tensors. """ return sum(tensors) def distributed_tensor_sum(): """ Sets up the distributed RPC framework, performs the distributio...
import os import pytest import torch import torch.distributed.rpc as rpc from solution import distributed_tensor_sum def init_rpc_framework(worker_name, rank, world_size): options = rpc.TensorPipeRpcBackendOptions() rpc.init_rpc( worker_name, rank=rank, world_size=world_size, r...
[ { "docstring": "Returns the sum of the given tensors.", "function_declaration": "def remote_tensor_sum(*tensors):", "function_name": "remote_tensor_sum", "parameter_list": "(*tensors)" }, { "docstring": "Sets up the distributed RPC framework, performs the distribution of tensors to worker no...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.distributed.rpc as rpc\nfrom torch.distributed.rpc import RRef\nimport os\n\ndef remote_tensor_sum(*tensors):\n \"\"\"\n Returns the su...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00044725", "row_id": 44725, "seed_ids": "[158]" }
0.410166
Docs: Pytorch_44725
I
[ "remote_tensor_sum", "distributed_tensor_sum" ]
2
[ [ "distributed_tensor_sum", "remote_tensor_sum" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
6248a0ded5ca52685efda91b15255cf8ac6bae37
2b020753c3988d0e4cd602628e85fe6e54b0b6c6
v1.0
instruct
Docs
Docs: Python310_44727_I
### Coding Assessment Task #### Objective: Demonstrate understanding of low-level Python system interaction by utilizing `os.PathLike` and process control functions. #### Problem Statement: You are tasked with creating a Python module that integrates filesystem path handling and inter-process communication using for...
import os import sys def validate_path(path): if isinstance(path, (str, bytes)): return path elif isinstance(path, os.PathLike): result = path.__fspath__() if isinstance(result, (str, bytes)): return result raise TypeError("Invalid path format") def process_path_handlin...
import os import pytest from solution import process_path_handling, validate_path class CustomPath: def __fspath__(self): return "/custom/path" def test_validate_path_with_string(): assert validate_path("/valid/path") == "/valid/path" def test_validate_path_with_bytes(): assert validate_path(b"/v...
[ { "docstring": null, "function_declaration": "def validate_path(path):", "function_name": "validate_path", "parameter_list": "(path)" }, { "docstring": null, "function_declaration": "def process_path_handling(parent_path, child_path):", "function_name": "process_path_handling", "...
[ 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 sys\n\ndef validate_path(path):\n if isinstance(path, (str, bytes)):\n return os.fspath(path)\n elif hasattr(path, '__fspath__'):\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00044727", "row_id": 44727, "seed_ids": "[49]" }
0.568479
Docs: Python310_44727
I
[ "validate_path", "process_path_handling" ]
2
[ [ "process_path_handling", "validate_path" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5e8f69f2a97221c8e73940668cd1d6cfb1c3b48b
d2fc382eeca182f5ed7bf07dd31981c08da66d34
v1.0
instruct
Docs
Docs: Python310_44766_I
**Coding Assessment Question:** ### Asynchronous Subprocess Manager You are tasked with writing a function `manage_subprocesses` that handles multiple asynchronous subprocesses using Python's `asyncio` library. Your function should launch multiple shell commands, process their outputs, and handle potential subprocess...
import asyncio import subprocess async def run_command(command, timeout): process = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) try: stdout, stderr = await asyncio.wait_for(process.communicate(), timeo...
import pytest import asyncio from solution import manage_subprocesses @pytest.mark.asyncio async def test_manage_subprocesses_success(): commands = ["echo 'Hello World'", "uname -a"] timeout = 2.0 result = await manage_subprocesses(commands, timeout) assert "echo 'Hello World'" in result assert res...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport shlex\n\nasync def manage_subprocesses(commands: list[str], timeout: float) -> dict[str, dict[str, str]]:\n async def run_command(command):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00044766", "row_id": 44766, "seed_ids": "[264]" }
0.678159
Docs: Python310_44766
I
[ "run_command", "manage_subprocesses" ]
2
[ [ "manage_subprocesses", "run_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1309a61a9b88867812c806081123d5e59b5cab2f
c58e6afdadfbdaaf5c479dcead801e44bb408ed1
v1.0
instruct
Docs
Docs: Pytorch_44798_I
### Custom Attention Mechanism with Block Masking **Objective:** Implement a custom multi-head attention mechanism using PyTorch's `flex_attention` module and its block mask utilities. This question is intended to test your understanding of both fundamental and advanced concepts of PyTorch, specifically the `torch.nn...
import torch import torch.nn.functional as F def create_custom_block_mask(seq_length, block_size): """ Creates a block mask for the given sequence length and block size. Args: seq_length (int): The sequence length. block_size (int): The block size for masking. Returns: ...
import pytest from solution import custom_multi_head_attention, create_custom_block_mask import torch def test_create_custom_block_mask(): seq_length = 10 block_size = 3 expected_mask = torch.tensor([ [1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0,...
[ { "docstring": "Creates a block mask for the given sequence length and block size.\n\nArgs:\n seq_length (int): The sequence length.\n block_size (int): The block size for masking.\n\nReturns:\n Tensor: A block mask for the attention mechanism.", "function_declaration": "def create_custom_block_mas...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn.functional as F\n\ndef create_custom_block_mask(seq_length, block_size):\n \"\"\"\n Creates a block mask for the given sequence leng...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00044798", "row_id": 44798, "seed_ids": "[0]" }
0.452548
Docs: Pytorch_44798
I
[ "create_custom_block_mask", "custom_multi_head_attention" ]
2
[ [ "custom_multi_head_attention", "create_custom_block_mask" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
935b740c819dcda6992e339a54ee0250bd6be259
f37febe486e45b1fbfd9a2aa5be34b14b9be3e83
v1.0
instruct
Docs
Docs: Scikit_44893_I
### Question: Kernel Density Estimation with Different Kernels #### Background Kernel Density Estimation (KDE) is a non-parametric way to estimate the probability density function of a random variable. It smoothens the data points by considering each point as a kernel. This technique is valuable for data visualization...
import numpy as np import matplotlib.pyplot as plt from sklearn.neighbors import KernelDensity # Generating sample data np.random.seed(0) X = np.concatenate([ np.random.normal(loc=-1.0, scale=0.5, size=(100, 2)), np.random.normal(loc=2.0, scale=0.5, size=(100, 2)) ]) def plot_kde(X, kde, ax): x = np.linsp...
def test_kde(): from sklearn.neighbors import KernelDensity import numpy as np np.random.seed(0) X = np.concatenate([ np.random.normal(loc=-1.0, scale=0.5, size=(100, 2)), np.random.normal(loc=2.0, scale=0.5, size=(100, 2)) ]) kernels = ['gaussian', 'tophat', 'epanechnikov', '...
[ { "docstring": null, "function_declaration": "def plot_kde(X, kde, ax):", "function_name": "plot_kde", "parameter_list": "(X, kde, ax)" }, { "docstring": null, "function_declaration": "def analyze_kde(X, kernels, bandwidths):", "function_name": "analyze_kde", "parameter_list": "(...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import KernelDensity\n\n# Given dataset\nnp.random.seed(0)\nX = np.concatenate([\n np.ran...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00044893", "row_id": 44893, "seed_ids": "[51]" }
0.554322
Docs: Scikit_44893
I
[ "plot_kde", "analyze_kde" ]
2
[ [ "analyze_kde", "plot_kde" ] ]
1
[]
false
[]
false
pytest
false
[ "matplotlib", "numpy", "sklearn" ]
false
877265ab2023f24d760d62e3b898bf94841d48ec
cd51d571677a1f0ab7ae2a621c290f99d800d6aa
v1.0
instruct
Docs
Docs: Python310_44914_I
#### Objective: To assess your understanding of the `contextvars` package in Python, you will implement a function that manages context-specific configurations in an asynchronous web server setting. #### Problem Statement: You are required to implement an asynchronous web server using the `asyncio` and `contextvars` p...
import asyncio import contextvars # Define client configuration context variable client_config = contextvars.ContextVar('client_config', default=None) def set_client_config(config: dict) -> None: """Set the client's configuration.""" client_config.set(config) def get_client_config() -> dict: """Get the c...
import pytest from solution import set_client_config, get_client_config import contextvars def test_set_and_get_client_config(): config = {'test_key': 'test_value'} set_client_config(config) assert get_client_config() == config def test_get_client_config_default(): client_config = contextvars.Context...
[ { "docstring": "Set the client's configuration.", "function_declaration": "def set_client_config(config):", "function_name": "set_client_config", "parameter_list": "(config)" }, { "docstring": "Get the client's current configuration.", "function_declaration": "def get_client_config():", ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\n\n# Define client configuration context variable\nclient_config = contextvars.ContextVar('client_config')\n\ndef set_client_config(c...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00044914", "row_id": 44914, "seed_ids": "[392]" }
0.507527
Docs: Python310_44914
I
[ "set_client_config", "get_client_config", "handle_request", "main" ]
4
[ [ "handle_request", "get_client_config" ], [ "handle_request", "set_client_config" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5aa3f6fe3e4d66e74225ea4c0b306a5ad3a5d186
d4556963fa7cc3311d00cc232d8eb1d983992bb2
v1.0
instruct
Docs
Docs: Python310_45009_I
#### Objective: Create a Python program that utilizes the `signal` module to manage timed events and demonstrates proper handling of multiple signals in a multi-threaded context. #### Problem Statement: You are required to implement a function `setup_signal_handlers()` that sets up custom signal handlers for the `SIGI...
import signal import threading import time import os def sigint_handler(signum, frame): print("SIGINT received!") raise KeyboardInterrupt def sigterm_handler(signum, frame): print("SIGTERM received!") os._exit(0) def sigalrm_handler(signum, frame): print("SIGALRM received!") def setup_signal_han...
import signal import os import pytest from solution import setup_signal_handlers, timer_signal def test_setup_signal_handlers(monkeypatch): def mock_sigint_handler(signum, frame): print("Mock SIGINT received!") def mock_sigterm_handler(signum, frame): print("Mock SIGTERM received!") ...
[ { "docstring": null, "function_declaration": "def sigint_handler(signum, frame):", "function_name": "sigint_handler", "parameter_list": "(signum, frame)" }, { "docstring": null, "function_declaration": "def sigterm_handler(signum, frame):", "function_name": "sigterm_handler", "pa...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import signal\nimport threading\nimport time\nimport os\n\ndef sigint_handler(signum, frame):\n print(\"SIGINT received!\")\n raise KeyboardInterrupt\n\ndef sigte...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00045009", "row_id": 45009, "seed_ids": "[253]" }
0.546537
Docs: Python310_45009
I
[ "sigint_handler", "sigterm_handler", "sigalrm_handler", "setup_signal_handlers", "timer_signal" ]
5
[ [ "setup_signal_handlers", "sigalrm_handler" ], [ "setup_signal_handlers", "sigint_handler" ], [ "setup_signal_handlers", "sigterm_handler" ] ]
3
[]
false
[]
false
pytest
true
[]
true
33345a61eb696bea58fe24c79c706b6491156b19
fe8c7ce9e8aeff869bf67e5edca19443e8ae250f
v1.0
instruct
Docs
Docs: Seaborn_45080_I
### Seaborn Color Palette Blending **Objective:** Assess your ability to work with color palettes in seaborn by generating and visualizing custom palettes using the `blend_palette` function. **Problem Statement:** You are tasked with creating a custom color palette and using it to visualize data. Specifically, you ne...
import seaborn as sns import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap from typing import List, Union, Tuple def create_custom_palette(color_list: List[str], as_cmap: bool) -> Union[List[Tuple[float, float, float]], LinearSegmentedColormap]: """ Generates a custom color pal...
from solution import create_custom_palette import seaborn as sns from matplotlib.colors import LinearSegmentedColormap def test_create_custom_palette_continuous(): colors = ["#FF5733", "blue", "xkcd:golden"] palette = create_custom_palette(colors, as_cmap=True) assert isinstance(palette, LinearSegmentedCol...
[ { "docstring": "Generates a custom color palette from a list of colors and a boolean indicating whether \nthe output should be a continuous colormap or a discrete palette.\n\n:param color_list: List of colors to blend. Can be named colors, hex codes, or numeric values.\n:param as_cmap: Boolean indicating whethe...
[ 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import seaborn as sns\nimport matplotlib.pyplot as plt\nfrom typing import List, Union, Tuple\nfrom matplotlib.colors import LinearSegmentedColormap, to_rgb\n\ndef crea...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00045080", "row_id": 45080, "seed_ids": "[76]" }
0.6545
Docs: Seaborn_45080
I
[ "create_custom_palette", "plot_heatmap_with_custom_palette" ]
2
[ [ "plot_heatmap_with_custom_palette", "create_custom_palette" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "seaborn" ]
false
2719812f09cd6ee9f43db2781cd9d3a8cf7db408
02eeb7c55bdc095b2068aa461138465ab543bcb2
v1.0
instruct
Docs
Docs: Pytorch_45182_I
### Distributed Training with PyTorch Multiprocessing **Objective:** Implement a distributed training setup for a simple neural network using PyTorch's `torch.distributed.elastic.multiprocessing` module. The goal is to understand how to manage multiple worker processes and synchronize their work. **Task:** 1. Create ...
import torch import torch.nn as nn import torch.optim as optim from torch.distributed import init_process_group, destroy_process_group from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import DataLoader, DistributedSampler from torch.multiprocessing import Process class SimpleNet(nn.Mo...
import pytest import torch from solution import distributed_train, SimpleNet class RandomDataset(torch.utils.data.Dataset): def __init__(self, size): self.data = torch.rand(size, 10) self.labels = torch.rand(size, 1) def __len__(self): return len(self.data) def __getitem__(self, i...
[]
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torch.nn.parallel import Di...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00045182", "row_id": 45182, "seed_ids": "[143]" }
0.542389
Docs: Pytorch_45182
I
[ "setup", "cleanup", "train", "distributed_train" ]
4
[ [ "train", "cleanup" ], [ "train", "setup" ] ]
2
[]
false
[ "SimpleNet" ]
true
pytest
true
[ "torch" ]
false
1019b3514ca58b9538d37eba7de7c3a7274c3f20
6a64de4ca95e2d6348ff89e41b026c75f901dfba
v1.0
instruct
Docs
Docs: Python310_45188_I
**Question: Handling and Filtering Warnings** You are tasked with developing components of a Python library that makes extensive use of deprecated features. To manage this, you need to implement functions that issue and handle warnings in various scenarios. **Objective:** 1. Implement a function `deprecated_functio...
import warnings def deprecated_function(): """ Function that issues a DeprecationWarning. """ warnings.warn("deprecated_function is deprecated", DeprecationWarning) def test_warnings(): """ Function that calls deprecated_function with warnings suppressed. """ with warnings.catch_warnin...
import warnings import pytest from solution import deprecated_function, test_warnings, configure_warning_filters def test_deprecated_function_issues_warning(): with pytest.warns(DeprecationWarning, match="deprecated_function is deprecated"): deprecated_function() def test_deprecated_function_suppressed_wa...
[ { "docstring": "Function that issues a DeprecationWarning.", "function_declaration": "def deprecated_function():", "function_name": "deprecated_function", "parameter_list": "()" }, { "docstring": "Function that calls deprecated_function with warnings suppressed.", "function_declaration":...
[ 1, 0, 1, 0, 0, 1, 1, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import warnings\n\ndef deprecated_function():\n \"\"\"\n Function that issues a DeprecationWarning.\n \"\"\"\n warnings.warn(\"deprecated_function is deprec...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00045188", "row_id": 45188, "seed_ids": "[125]" }
0.387401
Docs: Python310_45188
I
[ "deprecated_function", "test_warnings", "configure_warning_filters" ]
3
[ [ "test_warnings", "deprecated_function" ] ]
1
[]
false
[]
false
pytest
true
[]
true
29e69566ab854bbf622c84b5d6d258ee48148c8c
cf01f971d1089517d75bc8a8c95a465c59f5621d
v1.0
instruct
Docs
Docs: Scikit_45247_I
## Coding Assessment Question ### Objective Design and implement a simple out-of-core learning system to classify text documents using scikit-learn. You will need to: 1. Stream instances from a large text dataset. 2. Extract features using a vectorization technique. 3. Train an incremental learning model using the ext...
def stream_text_data(file_path: str, batch_size: int): """ Streams text data from a file in batches. Parameters: - file_path: str, path to the text file. - batch_size: int, number of lines to yield per batch. Yields: - List of text documents (each document is a string). """ ...
import os import pytest from solution import stream_text_data, train_incremental_classifier # Helper function to create a temporary test file def create_test_file(file_path, content): with open(file_path, 'w') as file: file.write(content) # Define test file content test_content = """sports Soccer game in ...
[ { "docstring": "Streams text data from a file in batches.\n\nParameters:\n- file_path: str, path to the text file.\n- batch_size: int, number of lines to yield per batch.\n\nYields:\n- List of text documents (each document is a string).", "function_declaration": "def stream_text_data(file_path, batch_size):...
[ 1, 1, 1, 1, 1, 0, 0, 0, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def stream_text_data(file_path: str, batch_size: int):\n \"\"\"\n Streams text data from a file in batches.\n \n Parameters:\n - file_path: str, path t...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00045247", "row_id": 45247, "seed_ids": "[63]" }
0.566303
Docs: Scikit_45247
I
[ "stream_text_data", "train_incremental_classifier" ]
2
[ [ "train_incremental_classifier", "stream_text_data" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
325433e663dccaf2acd51237ffa448b6cc5261da
43fbc803dcd65a00561d0d3f5bfda46c69f53570
v1.0
instruct
Docs
Docs: Scikit_45277_I
**Question: Feature Extraction and Transformation with Scikit** You are tasked with building a preprocessing pipeline for a machine learning model that can handle a mixed dataset consisting of both text and structured categorical and numerical data. The goal is to transform the input data into a numerical format suita...
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction import DictVectorizer, FeatureHasher import numpy as np from scipy.sparse import hstack def extract_text_features(reviews): """ Extract TF-IDF features from a list of reviews. """ vectorizer = TfidfVectorizer() ...
from solution import extract_text_features, extract_categorical_features, apply_feature_hashing, preprocess_data import numpy as np def test_extract_text_features(): reviews = [ "The product quality is excellent. Highly recommend!", "Not satisfied with the product. Battery life is too short.", ...
[ { "docstring": "Extract TF-IDF features from a list of reviews.", "function_declaration": "def extract_text_features(reviews):", "function_name": "extract_text_features", "parameter_list": "(reviews)" }, { "docstring": "Extract one-hot encoded features from categorical data and numerical fea...
[ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.feature_extraction import FeatureHasher...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00045277", "row_id": 45277, "seed_ids": "[40]" }
0.591363
Docs: Scikit_45277
I
[ "extract_text_features", "extract_categorical_features", "apply_feature_hashing", "preprocess_data" ]
4
[ [ "preprocess_data", "apply_feature_hashing" ], [ "preprocess_data", "extract_categorical_features" ], [ "preprocess_data", "extract_text_features" ] ]
3
[]
false
[]
false
pytest
true
[ "numpy", "scipy", "sklearn" ]
false
0e4fc097257d8921f78b767f026ca7f1f5caa5f6
688d0f8c53c52cf267b718b366b8143790a9f32f
v1.0
instruct
Docs
Docs: Scikit_45370_I
In this assignment, you will implement, profile, and optimize a simple machine learning pipeline using scikit-learn, and then transform it into a parallelized version. The task will test your understanding of Python, Numpy, Cython, and joblib. You should follow the steps outlined below: 1. **Implement a simple pipelin...
import numpy as np from sklearn.datasets import load_iris from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline def simple_pipeline(): # Load the Iris dataset data = load_iris() X, y = data.data, data.target # Crea...
def test_simple_pipeline(): pipeline = simple_pipeline() assert pipeline is not None def test_optimized_pipeline(): pipeline = optimized_pipeline() assert pipeline is not None def test_parallel_pipeline(): knn = parallel_pipeline() assert knn is not None def test_parallel_pipeline_correctness...
[ { "docstring": null, "function_declaration": "def simple_pipeline():", "function_name": "simple_pipeline", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def profile_pipeline():", "function_name": "profile_pipeline", "parameter_list": "()" }, { "d...
[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom s...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00045370", "row_id": 45370, "seed_ids": "[11]" }
0.455708
Docs: Scikit_45370
I
[ "simple_pipeline", "profile_pipeline", "optimized_pipeline", "parallel_fit_knn", "parallel_pipeline" ]
5
[ [ "parallel_pipeline", "parallel_fit_knn" ], [ "profile_pipeline", "simple_pipeline" ] ]
2
[]
false
[]
false
pytest
false
[ "joblib", "numpy", "sklearn" ]
false
854258d533f7b8e8e593a9efe9afbc67b4ae2f8e
75241348a42db40af85bb68f0cf366b50becb50a
v1.0
instruct
Docs
Docs: Python310_45389_I
**Question: Implementing a Secure File Verification System** **Objective:** You are asked to implement a secure file verification system using the cryptographic services provided by Python. **Requirements:** 1. **File Hashing and Integrity Verification:** - Implement a function `generate_file_hash(file_path: str)...
import hashlib import hmac import os def generate_file_hash(file_path: str) -> str: """ Generates SHA-256 hash for the file content located at file_path. :param file_path: Path to the file. :return: SHA-256 hash of file content in hexadecimal format. """ sha256 = hashlib.sha256() try: ...
import tempfile from solution import generate_file_hash, verify_file_hash, generate_hmac, generate_secure_token def test_generate_file_hash(): with tempfile.NamedTemporaryFile(delete=False) as temp_file: temp_file.write(b"Hello, World!") temp_file_path = temp_file.name expected_hash = hashlib.s...
[ { "docstring": "Generates SHA-256 hash for the file content located at file_path.\n\n:param file_path: Path to the file.\n:return: SHA-256 hash of file content in hexadecimal format.", "function_declaration": "def generate_file_hash(file_path):", "function_name": "generate_file_hash", "parameter_lis...
[ 0, 1, 1, 0, 0, 0, 0, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\nimport hmac\nimport os\n\ndef generate_file_hash(file_path):\n \"\"\"\n Generate SHA-256 hash of the given file.\n \"\"\"\n try:\n sh...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00045389", "row_id": 45389, "seed_ids": "[394]" }
0.662653
Docs: Python310_45389
I
[ "generate_file_hash", "verify_file_hash", "generate_hmac", "generate_secure_token" ]
4
[ [ "verify_file_hash", "generate_file_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e36c7c6f2838e2fba3e29d7ab2da43b80246a67b
8f79aff1c94337fe754b3ba664234831a7464d89
v1.0
instruct
Docs
Docs: Pytorch_45396_I
Custom Block Mask Attention Your task is to implement a custom attention mechanism using PyTorch's `torch.nn.attention.flex_attention` and related BlockMask utilities. You need to create masks that selectively attenuate specific parts of the input data and apply these masks within the attention mechanism. #### Requir...
import torch def custom_block_mask(size: tuple, mask_value: float) -> torch.Tensor: """ Creates a block mask of the given size where each block has the specified mask_value. Args: size (tuple): A tuple defining the size of the mask (rows, columns). mask_value (float): The value to be f...
import pytest import torch from solution import custom_block_mask, apply_attention_with_mask def test_custom_block_mask(): mask = custom_block_mask((3, 3), -1.0) expected_mask = torch.tensor([[-1.0, -1.0, -1.0], [-1.0, -1.0, -1.0], [-1.0, -1.0...
[ { "docstring": "Creates a block mask of the given size where each block has the specified mask_value.\n\nArgs:\n size (tuple): A tuple defining the size of the mask (rows, columns).\n mask_value (float): The value to be filled in each block of the mask.\n\nReturns:\n torch.Tensor: The created block mas...
[ 0, 1, 1, 1, 1, 0, 1, 1, 0, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.nn.functional import softmax\n\ndef custom_block_mask(size: tuple, mask_value: float) -> torch.Tensor:\n \"\"\"\n Creates a block mask of...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00045396", "row_id": 45396, "seed_ids": "[0]" }
0.464966
Docs: Pytorch_45396
I
[ "custom_block_mask", "apply_attention_with_mask" ]
2
[ [ "apply_attention_with_mask", "custom_block_mask" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
18cf4ae7bc65eaada1ba6767acabd58772504730
b0f8c47647b787faaeceb6d914c05a71f522ffc3
v1.0
instruct
Docs
Docs: Python310_45405_I
**Objective:** You are required to write code that demonstrates your understanding of the `email.charset` module within the legacy email API. This will involve manipulating character sets and their encodings as they apply to email headers and bodies. ### Problem Statement: You are working on an email client that needs...
from email.charset import Charset, add_charset, QP, BASE64 def initialize_charset(input_charset: str) -> Charset: """ Initialize and return a Charset object for the given input_charset. """ return Charset(input_charset) def encode_header(input_charset: str, header_string: str) -> str: """ Enco...
import pytest from email.charset import Charset, QP, BASE64 from solution import initialize_charset, encode_header, encode_body, register_charset def test_initialize_charset(): charset = initialize_charset('iso-8859-1') assert isinstance(charset, Charset) assert charset.input_charset == 'iso-8859-1' def t...
[ { "docstring": "Initialize and return a Charset object for the given input_charset.", "function_declaration": "def initialize_charset(input_charset):", "function_name": "initialize_charset", "parameter_list": "(input_charset)" }, { "docstring": "Encode a string for use in an email header for...
[ 1, 1, 0, 0, 0, 0, 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 email.charset import Charset, add_charset, QP, BASE64\n\ndef initialize_charset(input_charset: str) -> Charset:\n \"\"\"\n Initialize and return a Charset ob...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00045405", "row_id": 45405, "seed_ids": "[162]" }
0.535586
Docs: Python310_45405
I
[ "initialize_charset", "encode_header", "encode_body", "register_charset" ]
4
[ [ "encode_body", "initialize_charset" ], [ "encode_header", "initialize_charset" ] ]
2
[]
false
[]
false
pytest
true
[]
true
501ddc76074caca76ff38d14b7ccd03ca8bdadb7
547445e117aceee79a20c381c381d916191f387a
v1.0
instruct
Docs
Docs: Pytorch_45406_I
### PyTorch Distributed Training Setup **Problem Statement:** You are tasked with setting up and managing a distributed training job for a neural network using PyTorch. Your goal is to write a Python script that simulates a distributed training setup. This script should be capable of running on multiple nodes and han...
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP import argparse import random import time import os # 1. Define a basic neural network model class SimpleNeuralNetwork(nn.Module): def __init__(self): ...
# As we cannot test a distributed training job in real-time within a unit test framework, we will simulate the unit tests for each component. def test_simple_neural_network(): model = SimpleNeuralNetwork() assert isinstance(model, nn.Module) sample_input = torch.randn(1, 10) sample_output = model(sampl...
[]
[ 0, 0, 0, 0, 1, 0, 0, 1, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nimport...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00045406", "row_id": 45406, "seed_ids": "[157]" }
0.494401
Docs: Pytorch_45406
I
[ "simulate_node_failure", "train", "main" ]
3
[ [ "train", "simulate_node_failure" ] ]
1
[]
false
[ "SimpleNeuralNetwork" ]
true
pytest
false
[ "torch" ]
false
7afda54dcc40d3b893a8b5be24bf50ce7720667b
12ee58ba8f82c86f99ad70e88b73ba909a155384
v1.0
instruct
Docs
Docs: Python310_45453_I
**Objective:** Create a function that takes an integer errno value as input and returns a tuple containing the corresponding exception class (if any), the error message string, and the string name representation of the error from the `errno.errorcode` dictionary. The function should then demonstrate raising the corres...
import os import errno # Mapping of errno codes to corresponding exceptions errno_to_exception = { errno.EPERM: PermissionError, errno.ENOENT: FileNotFoundError, errno.ESRCH: ProcessLookupError, errno.EINTR: InterruptedError, errno.EIO: OSError, errno.ENXIO: OSError, errno.E2BIG: OSError, ...
import pytest import errno from solution import handle_errno_code, raise_based_on_errno def test_handle_errno_code_ep(): exception_class, error_message, error_name = handle_errno_code(errno.EPERM) assert exception_class == PermissionError assert error_message == "Operation not permitted" assert err...
[]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport errno\n\ndef handle_errno_code(errno_code: int) -> tuple:\n \"\"\"\n Takes an integer errno value and returns a tuple containing:\n - The cor...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00045453", "row_id": 45453, "seed_ids": "[252]" }
0.493079
Docs: Python310_45453
I
[ "handle_errno_code", "raise_based_on_errno" ]
2
[ [ "raise_based_on_errno", "handle_errno_code" ] ]
1
[]
false
[]
false
pytest
true
[]
true
31bf6a41f0e7914bf1e1260a90a429d19e4054cd
579ac85f204091234c350d6c0d72e1a8165f16ac
v1.0
instruct
Docs
Docs: Python310_45499_I
### Advanced Python Coding Assessment **Objective:** Demonstrate your understanding of the asyncio package in Python 3.10 by implementing an asynchronous task manager that orchestrates multiple tasks with various asyncio features. ### Problem Statement You are tasked with creating an asynchronous task manager using...
import asyncio import random import logging # Configure logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) async def dummy_task(task_id, lock): sleep_time = random.uniform(0.1, 2.0) try: async with lock: logger.debug(f"Task {task_id} acquired the lock.") ...
import pytest import asyncio from solution import async_task_manager @pytest.mark.asyncio async def test_async_task_manager(): await async_task_manager(5) @pytest.mark.asyncio async def test_async_task_manager_ten_tasks(): await async_task_manager(10) @pytest.mark.asyncio async def test_async_task_manager_ze...
[]
[ 1, 1, 1, 1, 1, 0, 0, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\n\nasync def worker(lock, queue):\n while True:\n priority, task_id = await queue.get()\n try:\n with await lo...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00045499", "row_id": 45499, "seed_ids": "[360]" }
0.528338
Docs: Python310_45499
I
[ "dummy_task", "worker", "async_task_manager" ]
3
[ [ "async_task_manager", "worker" ], [ "worker", "dummy_task" ] ]
2
[]
false
[]
false
pytest
true
[]
true
0782efb1ae7642299d4bb4e9816b2c0c621286cc
bf7b9674eb74829ee4ebe7f9588f38da2992f9f8
v1.0
instruct
Docs
Docs: Python310_45521_I
### Asynchronous Filename Search with concurrent.futures You are tasked with implementing a function using `concurrent.futures` to improve the performance of searching for files with specific extensions within multiple directories. You should use `ProcessPoolExecutor` for this task to leverage multiple CPU cores effec...
import os from concurrent.futures import ProcessPoolExecutor from typing import List, Dict def search_files_in_directory(directory: str, extension: str) -> List[str]: """ Searches for files with a given extension in the specified directory. """ matching_files = [] for root, _, files in os.walk(dire...
import os import tempfile from solution import find_files_with_extension def create_temp_test_files_structure(): temp_dir = tempfile.TemporaryDirectory() dirs = [tempfile.mkdtemp(dir=temp_dir.name) for _ in range(3)] # Create some test files with open(os.path.join(dirs[0], 'file1.py'), 'w') as f: ...
[ { "docstring": "Searches for files with a given extension in the specified directory.", "function_declaration": "def search_files_in_directory(directory, extension):", "function_name": "search_files_in_directory", "parameter_list": "(directory, extension)" }, { "docstring": "Finds files with...
[ 1, 1, 0, 1, 1, 1, 0, 0, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ProcessPoolExecutor\nimport os\nfrom typing import List, Dict\n\ndef find_files_in_directory(directory: str, extension: str) -> List[str]...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00045521", "row_id": 45521, "seed_ids": "[347]" }
0.569046
Docs: Python310_45521
I
[ "search_files_in_directory", "find_files_with_extension" ]
2
[ [ "find_files_with_extension", "search_files_in_directory" ] ]
1
[]
false
[]
false
pytest
true
[]
true
df9720b548e1df9a3a56dbfb1e79b94484944d9f
5aa41c690fa3c16c26dc4e9e747e03d051a627f0
v1.0
instruct
Docs
Docs: Pytorch_45525_I
### Distributed Training with ZeroRedundancyOptimizer In this task, you are required to implement a distributed training pipeline using PyTorch's `torch.distributed.optim.ZeroRedundancyOptimizer`. **Objective**: Create a PyTorch script to train a simple neural network model using `ZeroRedundancyOptimizer` across mult...
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torchvision import datasets, transforms from torch.utils.data import DataLoader, DistributedSampler from torch.distributed.optim import ZeroRedundancyOptimizer import torch.multiprocessing as mp import os # Define the ...
def test_example(): assert True # Placeholder test. Manual inspection required for distributed training scripts.
[]
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torchvision import datasets...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00045525", "row_id": 45525, "seed_ids": "[137]" }
0.558954
Docs: Pytorch_45525
I
[ "setup", "cleanup", "train", "main" ]
4
[ [ "train", "cleanup" ], [ "train", "setup" ] ]
2
[]
false
[ "SimpleNN" ]
true
pytest
false
[ "torch", "torchvision" ]
false
a81559e684a54ff519147b877582e42739964b2c
47d06b27234bbf695ae2a0442374e611d7eaf960
v1.0
instruct
Docs
Docs: Python310_45526_I
### Advanced Python Programming Assignment #### Objective You are assigned to develop a Python script that demonstrates your understanding and familiarity with Python's data compression and archiving modules. The task requires you to perform operations using multiple compression algorithms and archive formats. #### T...
import os from typing import List, Dict, Any import gzip import bz2 import lzma import zipfile import tarfile def compress_file(input_file: str, output_file: str, algorithm: str) -> int: """ Compresses the input file using the specified compression algorithm and returns the size of the compressed file. ...
import os import pytest from solution import process_files @pytest.fixture(scope="module") def setup_files(tmpdir_factory): file1 = tmpdir_factory.mktemp("data").join("file1.txt") file2 = tmpdir_factory.mktemp("data").join("file2.txt") file3 = tmpdir_factory.mktemp("data").join("file3.txt") with o...
[ { "docstring": "Compresses the input file using the specified compression algorithm and returns the size of the compressed file.\n\n:param input_file: Path to the input file to be compressed.\n:param output_file: Path to the output compressed file.\n:param algorithm: Compression algorithm (gzip, bz2, lzma)\n:re...
[ 1, 1, 0, 1, 0, 1, 1, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport gzip\nimport bz2\nimport lzma\nimport zipfile\nimport tarfile\nfrom typing import List, Dict, Any\n\ndef process_files(file_paths: List[str]) -> Dict[...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00045526", "row_id": 45526, "seed_ids": "[310]" }
0.702202
Docs: Python310_45526
I
[ "compress_file", "create_zip_archive", "create_tar_archive", "process_files" ]
4
[ [ "process_files", "compress_file" ], [ "process_files", "create_tar_archive" ], [ "process_files", "create_zip_archive" ] ]
3
[]
false
[]
false
pytest
true
[]
true
057e9aa3ba26e57a7d1238bb70945dd071062327
eec22e0bbabe642edc71bea9b75b1c1625b58d0a
v1.0
instruct
Docs
Docs: Python310_45531_I
**Question: Implement an Asynchronous Task Management System** **Objective:** Create a Python program that manages and executes multiple asynchronous tasks using the asyncio library. The program should be able to perform I/O-bound operations concurrently and synchronize the results. **Description:** You are required ...
import aiohttp import asyncio from typing import List, Tuple async def fetch_content(session, url): try: async with session.get(url) as response: response.raise_for_status() content = await response.text() return url, content[:100] except Exception as e: retu...
import asyncio from solution import fetch_data_concurrently def test_single_url(): urls = ["https://example.com"] result = asyncio.run(fetch_data_concurrently(urls)) assert len(result) == 1 assert result[0][0] == urls[0] assert isinstance(result[0][1], str) assert len(result[0][1]) == 100 or "E...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\nimport aiohttp\n\nasync def fetch_content(session, url):\n try:\n async with session.get(url) as response:\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00045531", "row_id": 45531, "seed_ids": "[270]" }
0.545325
Docs: Python310_45531
I
[ "fetch_content", "fetch_data_concurrently" ]
2
[ [ "fetch_data_concurrently", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
a4c83a84845f5d16575044a29cf532b71e439ce6
4b06b32f7d9f147ee2abbf7187049b8f39eb34f7
v1.0
instruct
Docs
Docs: Python310_45546_I
### Asynchronous Echo Server with Persistence #### Objective Design and implement an asynchronous TCP echo server using `asyncio` streams that not only echoes back received messages to the sender but also stores each message in a persistent file. #### Task 1. Write an asynchronous function `handle_client` that: -...
import asyncio async def handle_client(reader, writer): """ Handle client connection, read a message, echo it back, and append to a file. """ try: data = await reader.readuntil(b'\n') message = data.decode() # Echo the message back to the client writer.write(data) ...
import asyncio import pytest from solution import handle_client, start_echo_server @pytest.mark.asyncio async def test_handle_client(): reader, writer = await asyncio.open_connection('127.0.0.1', 8888) message = "Hello, World!\n" writer.write(message.encode()) await writer.drain() data = await rea...
[]
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n while True:\n data = await reader.readline()\n if not data:\n break\n me...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00045546", "row_id": 45546, "seed_ids": "[182]" }
0.644097
Docs: Python310_45546
I
[ "handle_client", "start_echo_server" ]
2
[ [ "start_echo_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bbbc0ec56f56967bed395b6c0a8da1b4ec1f5c6b
f07fc78e3118e63d6d284345bcc37d45bfa667d4
v1.0
instruct
Docs
Docs: Python310_45629_I
#### Objective: To assess the student's understanding of socket programming in Python, including creating client and server sockets, handling blocking and non-blocking communication, and ensuring proper data transmission and reception. #### Description: You are to implement a simple client-server application using Pyt...
import socket import threading import struct import time from select import select def handle_client(client_socket): while True: try: # Read message length (4 bytes) raw_msglen = recvall(client_socket, 4) if not raw_msglen: break msglen = stru...
from solution import server, client import threading import time # Automatically run the server and client to test the interaction def test_server_client_interaction(): server_thread = threading.Thread(target=server) server_thread.start() time.sleep(1) # Allow the server to start client_thread = thre...
[ { "docstring": null, "function_declaration": "def handle_client(client_socket):", "function_name": "handle_client", "parameter_list": "(client_socket)" }, { "docstring": null, "function_declaration": "def recvall(sock, n):", "function_name": "recvall", "parameter_list": "(sock, n...
[ 1, 0, 0, 0, 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": "# Server Code\nimport socket\nimport threading\nimport select\nimport struct\nfrom datetime import datetime\n\ndef handle_client(client_socket):\n try:\n clie...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00045629", "row_id": 45629, "seed_ids": "[63]" }
0.725074
Docs: Python310_45629
I
[ "handle_client", "recvall", "send_message", "server", "client" ]
5
[ [ "client", "recvall" ], [ "client", "send_message" ], [ "handle_client", "recvall" ], [ "handle_client", "send_message" ], [ "server", "handle_client" ] ]
5
[]
false
[]
false
pytest
true
[]
true
50e7f1da7d271f21902b0bca87ca132d6ac68af8
6db58e694ff3c48dd88b9abf8dc3979f444c7ff5
v1.0
instruct
Docs
Docs: Scikit_45633_I
Design a function that performs probability calibration on an uncalibrated binary classifier using scikit-learn's `CalibratedClassifierCV` with both sigmoid and isotonic methods. The function should: 1. Fit the uncalibrated model on training data. 2. Calibrate the fitted model using `CalibratedClassifierCV` with both '...
import numpy as np import matplotlib.pyplot as plt from sklearn.calibration import CalibratedClassifierCV, calibration_curve from sklearn.metrics import brier_score_loss, log_loss def plot_calibration_curve(est, X_test, y_test, name): """ Plots the calibration curve for the given estimator. """ prob_pos = est....
from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier from solution import calibrate_classifier def test_calibrate_classifier(): # Generate a binary classification dataset X, y = make_classification(n_samples=1000, n_features=20, random_state=42) # Split ...
[ { "docstring": "Plots the calibration curve for the given estimator. ", "function_declaration": "def plot_calibration_curve(est, X_test, y_test, name):", "function_name": "plot_calibration_curve", "parameter_list": "(est, X_test, y_test, name)" }, { "docstring": "Calibrates a given binary cl...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.calibration import CalibratedClassifierCV, calibration_curve\nfrom sklearn.metrics import brier_score_...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00045633", "row_id": 45633, "seed_ids": "[49]" }
0.482848
Docs: Scikit_45633
I
[ "plot_calibration_curve", "calibrate_classifier" ]
2
[ [ "calibrate_classifier", "plot_calibration_curve" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "sklearn" ]
false
4eb2663c45eeb08108d4650e36a022599112b5f9
863ec1810c67d86cfded032afb70192d54224215
v1.0
instruct
Docs
Docs: Python310_45699_I
### Question: Implementing Python Development Mode Checks #### Objective You need to implement Python code that simulates some effects of Python's Development Mode without actually enabling it. The goal is to help understand underlying issues like resource leakage and memory-related problems. #### Instructions 1. **F...
import signal import warnings import asyncio class ResourceWarning(Warning): pass def count_lines(file_path: str) -> int: """ Count the number of lines in a given file. Raises a custom ResourceWarning if the file is not explicitly closed. """ try: with open(file_path, 'r') as file...
import os import signal import asyncio import warnings from solution import count_lines, enable_fault_handlers, enable_asyncio_debug, ResourceWarning def test_count_lines(): test_file = 'test_file.txt' with open(test_file, 'w') as f: f.write("Line 1\nLine 2\nLine 3\n") count = count_lines(test...
[]
[ 0, 0, 1, 1, 0, 0, 1, 0, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport os\nimport warnings\nimport signal\n\nclass ResourceWarning(Exception):\n pass\n\ndef count_lines(file_path: str) -> int:\n \"\"\"\n Thi...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00045699", "row_id": 45699, "seed_ids": "[249]" }
0.517638
Docs: Python310_45699
I
[ "count_lines", "handle_fault", "enable_fault_handlers", "enable_asyncio_debug" ]
4
[ [ "enable_fault_handlers", "handle_fault" ] ]
1
[]
false
[ "ResourceWarning" ]
true
pytest
true
[]
true
f33385a3d0cdd3075984c5cec97131dcd9e3e335
5c8a41e95bd4d63b18119cd08f34ea9f0bb41ec2
v1.0
instruct
Docs
Docs: Python310_45708_I
### Advanced Python Coding Assessment Question #### Context You are required to implement an asynchronous file downloader using Python’s `asyncio` module. This downloader must be compatible across different platforms, particularly focusing on handling files and subprocesses considering platform-specific limitations. ...
import asyncio import aiohttp import os import sys async def download_file(session, url, local_dir): try: async with session.get(url) as response: if response.status == 200: filename = os.path.join(local_dir, os.path.basename(url)) with open(filename, 'wb') as fi...
import os import asyncio import aiohttp import pytest from solution import main, download_files @pytest.fixture def setup_local_dir(tmpdir): local_dir = tmpdir.mkdir("downloads") return str(local_dir) @pytest.fixture def mock_urls(): return [ 'https://httpbin.org/image/png', 'https://httpb...
[ { "docstring": null, "function_declaration": "def main(urls, local_dir):", "function_name": "main", "parameter_list": "(urls, local_dir)" } ]
[ 0, 0, 1, 0, 1, 1, 1, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nimport os\nimport platform\nfrom aiohttp import ClientSession\n\nasync def download_file(session: ClientSession, url: str, local_dir: st...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00045708", "row_id": 45708, "seed_ids": "[370]" }
0.612398
Docs: Python310_45708
I
[ "download_file", "download_files", "main" ]
3
[ [ "download_files", "download_file" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
409909135c8a21ce4cf81e024c8cf12db3f5890c
e1b5b176afddf5f1e3f5904bba3b8abefe5abab9
v1.0
instruct
Docs
Docs: Python310_45813_I
### Advanced Python Bytecode Analysis with the `dis` Module #### Problem You are given the following Python function: ```python def fibonacci(n): a, b = 0, 1 fib_sequence = [] for _ in range(n): fib_sequence.append(a) a, b = b, a + b return fib_sequence ``` Your task is to: 1. Disasse...
import dis def fibonacci(n): a, b = 0, 1 fib_sequence = [] for _ in range(n): fib_sequence.append(a) a, b = b, a + b return fib_sequence def analyze_fibonacci_bytecode(): # Step 1: Disassemble the function bytecode = dis.Bytecode(fibonacci) # Step 2: Provide detailed a...
from solution import analyze_fibonacci_bytecode def test_analyze_fibonacci_bytecode(): analysis, optimizations = analyze_fibonacci_bytecode() assert isinstance(analysis, list) assert isinstance(optimizations, list) assert all(isinstance(item, tuple) and len(item) == 4 for item in analysis) assert a...
[ { "docstring": null, "function_declaration": "def fibonacci(n):", "function_name": "fibonacci", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def analyze_fibonacci_bytecode():", "function_name": "analyze_fibonacci_bytecode", "parameter_list": "()" } ]
[ 0, 1 ]
1
medium
0.5
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import dis\n\ndef fibonacci(n):\n a, b = 0, 1\n fib_sequence = []\n for _ in range(n):\n fib_sequence.append(a)\n a, b =...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00045813", "row_id": 45813, "seed_ids": "[382]" }
0.582487
Docs: Python310_45813
I
[ "fibonacci", "analyze_fibonacci_bytecode" ]
2
[ [ "analyze_fibonacci_bytecode", "fibonacci" ] ]
1
[]
false
[]
false
pytest
true
[]
true
55c53cadc950665639e0257481baef2fa3eeec0d
95116b7f1da671f2e0a38de50e79a42ce8fc5372
v1.0
instruct
Docs
Docs: Seaborn_45835_I
#### Context You are provided with a dataset named `tips` which contains information about the total bills, tips, and several attributes like the day of the week, sex of the bill payer, etc. You need to create a series of visualizations to explore this dataset using seaborn. #### Task 1. **Data Preprocessing:** Load t...
import seaborn as sns import seaborn.objects as so import pandas as pd import numpy as np import matplotlib.pyplot as plt # Load the dataset tips = sns.load_dataset("tips") # Basic scatter plot of total_bill vs tip def basic_scatter_plot(tips): plt.figure(figsize=(10, 6)) sns.scatterplot(x='total_bill', y='ti...
import pytest from solution import * def test_basic_scatter_plot(): basic_scatter_plot(tips) # Test if plot is created - "plot should not throw any error" assert True def test_enhanced_scatter_plot(): enhanced_scatter_plot(tips) # Test if plot is created - "plot should not throw any error" ass...
[ { "docstring": null, "function_declaration": "def basic_scatter_plot(tips):", "function_name": "basic_scatter_plot", "parameter_list": "(tips)" }, { "docstring": null, "function_declaration": "def enhanced_scatter_plot(tips):", "function_name": "enhanced_scatter_plot", "parameter...
[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import seaborn as sns\nimport seaborn.objects as so\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Load the dataset\ntips = sns.load_dat...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00045835", "row_id": 45835, "seed_ids": "[56]" }
0.73594
Docs: Seaborn_45835
I
[ "basic_scatter_plot", "enhanced_scatter_plot", "colored_scatter_plot", "faceted_scatter_plot", "advanced_plot", "run_all_plots" ]
6
[ [ "run_all_plots", "advanced_plot" ], [ "run_all_plots", "basic_scatter_plot" ], [ "run_all_plots", "colored_scatter_plot" ], [ "run_all_plots", "enhanced_scatter_plot" ], [ "run_all_plots", "faceted_scatter_plot" ] ]
5
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "pandas", "seaborn" ]
false
e3df5b07b9a24ac4073d6d9ac7bdde17e58e1161
a277c852d3c6f911fc8864a8a2c34886ee57936b
v1.0
instruct
Docs
Docs: Scikit_45838_I
### Coding Challenge: Nearest Neighbor Classification and Performance Evaluation **Objective:** Your task is to implement a nearest neighbor classifier using scikit-learn and evaluate its performance on a dataset. **Description:** 1. Load the Iris dataset provided by scikit-learn. 2. Split the dataset into training a...
from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm def load_and_split_iris(): """ Load the Iris dataset and split it into training and testing sets. ...
from solution import load_and_split_iris, calculate_k, train_knn, evaluate_model from sklearn.neighbors import KNeighborsClassifier def test_load_and_split_iris(): X_train, X_test, y_train, y_test = load_and_split_iris() assert len(X_train) > 0 assert len(X_test) > 0 assert len(y_train) > 0 assert ...
[ { "docstring": "Load the Iris dataset and split it into training and testing sets.\nReturns X_train, X_test, y_train, y_test.", "function_declaration": "def load_and_split_iris():", "function_name": "load_and_split_iris", "parameter_list": "()" }, { "docstring": "Calculate the number of neig...
[ 0, 1, 0, 0, 1, 0, 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 import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nimport numpy as np\nimport matpl...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00045838", "row_id": 45838, "seed_ids": "[52]" }
0.552662
Docs: Scikit_45838
I
[ "load_and_split_iris", "calculate_k", "train_knn", "evaluate_model", "visualize_decision_boundaries", "nearest_neighbor_classification" ]
6
[ [ "nearest_neighbor_classification", "calculate_k" ], [ "nearest_neighbor_classification", "evaluate_model" ], [ "nearest_neighbor_classification", "load_and_split_iris" ], [ "nearest_neighbor_classification", "train_knn" ], [ "nearest_neighbor_classification", ...
5
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "sklearn" ]
false
9519651fcf70b01a9901f1d4a4264a21398b8a93
fd4827c25f15256af81184ff2a0931b048696f40
v1.0
instruct
Docs
Docs: Python310_45840_I
**Internationalize and Localize a Python Application** You are required to write a Python function to internationalize and localize a simple application that displays greeting messages in different languages based on user input. The application should support at least three languages: English, French, and German. You ...
import gettext import os def setup_translations(locale_dir: str) -> None: """ Set up the translation functionalities based on the provided locale directory. Parameters: locale_dir (str): The path to the directory containing the translation files. """ locales = ['en', 'fr', 'de'] transl...
import pytest from solution import setup_translations, greet_in_english, greet_in_french, greet_in_german # Setup translations for the tests: @pytest.fixture(scope='module', autouse=True) def setup_trans(): # Assuming a hypothetical path '/path/to/locale' for testing purposes setup_translations('/path/to/local...
[ { "docstring": "Set up the translation functionalities based on the provided locale directory.\n\nParameters:\nlocale_dir (str): The path to the directory containing the translation files.", "function_declaration": "def setup_translations(locale_dir):", "function_name": "setup_translations", "parame...
[ 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 gettext\nimport os\n\ndef setup_translations(locale_dir: str) -> None:\n \"\"\"\n Set up the translation functionalities based on the provided locale direc...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00045840", "row_id": 45840, "seed_ids": "[161]" }
0.497366
Docs: Python310_45840
I
[ "setup_translations", "get_current_locale", "greet_in_english", "greet_in_french", "greet_in_german" ]
5
[ [ "setup_translations", "get_current_locale" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4fc8415986656b68ab3b9db21d2955ac7c7bf5b0
1f1dfba424c67469cc8007c2329e1a088a18ec04
v1.0
instruct
Docs
Docs: Scikit_45845_I
### Custom Metric and Model Evaluation In this task, you'll be required to write a Python function that evaluates a model using a custom metric defined through the `make_scorer` factory in Scikit-learn. You will then apply this custom metric in a cross-validation setup. #### Problem Statement 1. **Custom Metric**: I...
import numpy as np from sklearn.metrics import mean_squared_error def custom_mse(y_true, y_pred, scale_factor: float) -> float: """ Custom Mean Squared Error metric scaled by a factor. Args: y_true (array-like): True labels. y_pred (array-like): Predicted labels. scale_factor (...
from solution import custom_mse, create_custom_scorer import numpy as np from sklearn.metrics import mean_squared_error def test_custom_mse(): y_true = np.array([1.0, 2.0, 3.0]) y_pred = np.array([1.1, 1.9, 3.2]) scale_factor = 2.0 mse = mean_squared_error(y_true, y_pred) assert custom_mse(y_true, ...
[ { "docstring": "Custom Mean Squared Error metric scaled by a factor.\n\nArgs:\n y_true (array-like): True labels.\n y_pred (array-like): Predicted labels.\n scale_factor (float): Factor by which to scale the MSE.\n\nReturns:\n float: Scaled Mean Squared Error.", "function_declaration": "def cust...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.metrics import mean_squared_error, make_scorer\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.model_selection import cross_val_score\nfrom ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00045845", "row_id": 45845, "seed_ids": "[25]" }
0.554484
Docs: Scikit_45845
I
[ "custom_mse", "create_custom_scorer", "evaluate_model_with_custom_metric" ]
3
[ [ "create_custom_scorer", "custom_mse" ], [ "evaluate_model_with_custom_metric", "create_custom_scorer" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
f963411afedbdc4770c0ae148a5b66447d17cc18
8aca0a8af6b1a3bea52a438ac3364ce0e85f1b18
v1.0
instruct
Docs
Docs: Python310_45873_I
### Asynchronous Task Scheduler and Server You are required to implement an asynchronous task scheduler and server using Python's asyncio module. #### Requirements: 1. **Task Scheduler**: - Implement a function `schedule_tasks(loop, tasks)`, where `loop` is the event loop and `tasks` is a list of tasks. - Ea...
import asyncio import signal def schedule_tasks(loop, tasks): """ Schedules tasks to be executed at specified times. :param loop: Event loop in which the tasks will be scheduled. :param tasks: List of dictionaries containing task details. """ for task in tasks: loop.call_later(task...
import asyncio import pytest from unittest.mock import Mock from solution import schedule_tasks, handle_client, start_server @pytest.fixture def event_loop(): loop = asyncio.new_event_loop() yield loop loop.close() def test_schedule_tasks(event_loop): mock_callback = Mock() tasks = [ {'ti...
[ { "docstring": "Schedules tasks to be executed at specified times.\n\n:param loop: Event loop in which the tasks will be scheduled.\n:param tasks: List of dictionaries containing task details.", "function_declaration": "def schedule_tasks(loop, tasks):", "function_name": "schedule_tasks", "parameter...
[ 1, 1, 0, 1, 1, 0, 1, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport signal\n\ndef schedule_tasks(loop, tasks):\n \"\"\"\n Schedule tasks to be executed at specified times.\n \n Args:\n loop (asy...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00045873", "row_id": 45873, "seed_ids": "[267]" }
0.754212
Docs: Python310_45873
I
[ "schedule_tasks", "handle_client", "start_server", "main" ]
4
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6da092a622b76e072647f757831f6eb2b269e647
36e5e0bf3bf0b509c55f6f82180ebb24ae034ca8
v1.0
instruct
Docs
Docs: Python310_45874_I
### AsyncIO Synchronization Primitives - Traffic Light Simulation #### Objective Design a traffic light system at an intersection using asyncio synchronization primitives to manage the traffic flow. The intersection allows one-way traffic at a time; either north-south or east-west, but not both. Use `Locks` to ensure ...
import asyncio async def north_south_traffic(lock, event): while True: async with lock: if event.is_set(): print("North-South: Green Light") await asyncio.sleep(10) event.clear() else: print("North-South: Red Light") ...
import asyncio from solution import traffic_light_system async def test_traffic_light_system(): """Test the traffic light system.""" awaitable = asyncio.wait_for(traffic_light_system(), timeout=25) try: await awaitable except asyncio.TimeoutError: pass # Expected def test_traffic_lig...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def north_south_traffic(lock, event):\n while True:\n async with lock:\n if event.is_set():\n print(\"North-...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00045874", "row_id": 45874, "seed_ids": "[247]" }
0.432049
Docs: Python310_45874
I
[ "north_south_traffic", "east_west_traffic", "traffic_light_system" ]
3
[ [ "traffic_light_system", "east_west_traffic" ], [ "traffic_light_system", "north_south_traffic" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d72b974624825b0c2cd941bb537f920805c62f75
0fcc0ddec6f419a44e26715822d2d281ba9c7869
v1.0
instruct
Docs
Docs: Pytorch_45900_I
Distributed Data Parallel Training with PyTorch #### Objective Implement a distributed training process using `torch.nn.parallel.DistributedDataParallel` (DDP) to train a simple neural network on a dummy dataset. Demonstrate your understanding of setting up the distributed environment, wrapping the model with DDP, and...
import torch import torch.distributed as dist import torch.multiprocessing as mp import torch.nn as nn import torch.optim as optim from torch.nn.parallel import DistributedDataParallel as DDP import os class SimpleNN(nn.Module): def __init__(self): super(SimpleNN, self).__init__() self.fc1 = nn.Lin...
from solution import generate_dummy_data, SimpleNN import torch def test_generate_dummy_data_shapes(): inputs, labels = generate_dummy_data(20, 10, 10) assert inputs.shape == (20, 10) assert labels.shape == (20, 10) def test_simple_nn_forward_pass(): model = SimpleNN() inputs = torch.randn(20, 10)...
[]
[ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.nn.parallel import Di...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00045900", "row_id": 45900, "seed_ids": "[181]" }
0.576331
Docs: Pytorch_45900
I
[ "generate_dummy_data", "train", "main" ]
3
[ [ "train", "generate_dummy_data" ] ]
1
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
b230ba916f1b3c25faf12e1f770ab0a660d712eb
a3f4e5d903207a306d76910969f80cb12b3fd80d
v1.0
instruct
Docs
Docs: Python310_45918_I
**Context Manager for Resource Management** In Python, managing resources (like files, database connections, or network connections) efficiently is crucial to avoid resource leaks. The `contextlib` module provides utilities to simplify the creation and management of such resources using the `with` statement. Your tas...
from contextlib import contextmanager def acquire_db_connection(): print("Acquiring connection") return "db_connection" def release_db_connection(conn): print(f"Releasing connection {conn}") def execute_query(conn, query): print(f"Executing query on {conn}: {query}") @contextmanager def DatabaseConn...
from solution import DatabaseConnectionManager, execute_query def test_database_connection_manager_normal_execution(capfd): queries = [ "SELECT * FROM users", "UPDATE users SET name = 'Alice' WHERE id = 1" ] with DatabaseConnectionManager() as conn: for query in queries: ...
[ { "docstring": null, "function_declaration": "def acquire_db_connection():", "function_name": "acquire_db_connection", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def release_db_connection(conn):", "function_name": "release_db_connection", "parameter_l...
[ 0, 0, 1, 0, 1, 1, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from contextlib import contextmanager\n\ndef acquire_db_connection():\n print(\"Acquiring connection\")\n return \"db_connection\"\n\ndef release_db_connection(co...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00045918", "row_id": 45918, "seed_ids": "[177]" }
0.376637
Docs: Python310_45918
I
[ "acquire_db_connection", "release_db_connection", "execute_query", "DatabaseConnectionManager" ]
4
[ [ "DatabaseConnectionManager", "acquire_db_connection" ], [ "DatabaseConnectionManager", "release_db_connection" ] ]
2
[]
false
[]
false
pytest
true
[]
true
672a7748d9d34d7805cd77149d497340ac4d509c
f94019e6da8dbd511462903d594433cd11776eb7
v1.0
instruct
Docs
Docs: Python310_45956_I
### Cell Objects in Python In Python, cell objects are used internally to handle variables that are referenced in multiple scopes, particularly within closures. In this assignment, you will implement a mini-framework that uses cell objects to manage variables in nested scopes. Your task is to create functions to simul...
import types def is_cell_object(x): """ Returns True if x is a cell object, False otherwise. """ return isinstance(x, types.CellType) def create_cell(value): """ Creates a cell object containing the given value. """ def cell_creator(): cell_value = value def closure(): ...
from solution import is_cell_object, create_cell, get_cell_content, set_cell_content def test_is_cell_object(): cell = create_cell(10) assert is_cell_object(cell) == True assert is_cell_object(10) == False assert is_cell_object("test") == False assert is_cell_object(None) == False def test_create_...
[ { "docstring": "Returns True if x is a cell object, False otherwise.", "function_declaration": "def is_cell_object(x):", "function_name": "is_cell_object", "parameter_list": "(x)" }, { "docstring": "Creates a cell object containing the given value.", "function_declaration": "def create_c...
[ 1, 0, 0, 1, 1, 0, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import types\n\ndef is_cell_object(x):\n \"\"\"\n Returns True if x is a cell object, False otherwise.\n \"\"\"\n return isinstance(x, types.CellType)\n\nde...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00045956", "row_id": 45956, "seed_ids": "[38]" }
0.496686
Docs: Python310_45956
I
[ "is_cell_object", "create_cell", "get_cell_content", "set_cell_content" ]
4
[ [ "get_cell_content", "is_cell_object" ], [ "set_cell_content", "is_cell_object" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9240743c705b3d3ea4a58490af7ad4b091e94981
c919e298e9b3f97e90953987f36f988395ca9a3c
v1.0
instruct
Docs
Docs: Pytorch_45960_I
### Distributed Training with PyTorch Elastic #### Background In distributed machine learning, we often deal with multiple computing nodes working together to train a model. PyTorch provides a package called `torch.distributed.elastic` which allows distributed jobs to be more fault-tolerant and elastic (adaptive to ch...
import torch import torch.nn as nn import torch.optim as optim from torch.distributed.elastic.multiprocessing.errors import record from torch.utils.data import DataLoader, TensorDataset def get_data_loader(batch_size=32): # Generate random data inputs = torch.randn(1000, 10) # 1000 samples with 10 features ea...
import pytest import torch from torch.utils.data import DataLoader # Importing the functions to test from solution import get_data_loader, SimpleNet def test_get_data_loader(): data_loader = get_data_loader(batch_size=32) assert isinstance(data_loader, DataLoader) batch = next(iter(data_loader)) asser...
[]
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom torch.distributed.elastic.multiprocessing...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00045960", "row_id": 45960, "seed_ids": "[21]" }
0.528169
Docs: Pytorch_45960
I
[ "get_data_loader", "train", "main" ]
3
[ [ "train", "get_data_loader" ] ]
1
[]
false
[ "SimpleNet" ]
true
pytest
true
[ "torch" ]
false
56f18974645a2660288019e1c93f1c0e3d24fe73
b2978ed6d8b8fcba23d8d1c42a1c1e39ca819168
v1.0
instruct
Docs
Docs: Python310_45973_I
### Parallel Matrix Multiplication Using Multiprocessing You are required to implement a parallel matrix multiplication function in Python using the `multiprocessing` package. The function will take two matrices as input and return their product. Matrix multiplication is defined as follows: Given two matrices A of si...
import multiprocessing from itertools import product def matrix_element(A, B, i, j): """ Computes the element C[i][j] for the product of matrices A and B """ return sum(A[i][k] * B[k][j] for k in range(len(B))) def parallel_matrix_multiply(A, B): """ Multiplies two matrices A and B using paral...
from solution import parallel_matrix_multiply def test_matrix_multiplication_example(): A = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] B = [ [9, 8, 7], [6, 5, 4], [3, 2, 1] ] expected_result = [ [30, 24, 18], [84, 69, 54], [138, 114, ...
[ { "docstring": "Computes the element C[i][j] for the product of matrices A and B", "function_declaration": "def matrix_element(A, B, i, j):", "function_name": "matrix_element", "parameter_list": "(A, B, i, j)" }, { "docstring": "Multiplies two matrices A and B using parallel processing.\nRet...
[ 1, 1, 0, 1, 0, 1, 0, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import multiprocessing\n\ndef matrix_multiply_worker(args):\n A, B, row_index = args\n C_row = []\n num_cols_B = len(B[0])\n \n for j in range(num_cols_B...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00045973", "row_id": 45973, "seed_ids": "[338]" }
0.561213
Docs: Python310_45973
I
[ "matrix_element", "parallel_matrix_multiply" ]
2
[ [ "parallel_matrix_multiply", "matrix_element" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6d9d4e914afaea576bb878fcb414ebb5670de82c
635bb8e01dafd02343850f925a5e480c151a1996
v1.0
instruct
Docs
Docs: Pytorch_46013_I
You are provided with the requirement to train a PyTorch model using distributed training to speed up the training process. You are to leverage the `torchrun` tool from the `torch.distributed.run` module to train a simple neural network across multiple processes. ## Task Write a Python script that uses the `torchrun` ...
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP import os # Set this environment variable for `torchrun` os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = '12355' def setup(rank, world_size):...
from solution import setup, cleanup, generate_synthetic_data, SimpleNN import torch.distributed as dist import torch import pytest def test_setup_cleanup(): """ Test the setup and cleanup of the distributed training environment. """ world_size = 1 rank = 0 setup(rank, world_size) assert dis...
[]
[ 1, 1, 0, 1, 0, 0, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torch.nn.parallel import Di...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00046013", "row_id": 46013, "seed_ids": "[145]" }
0.447149
Docs: Pytorch_46013
I
[ "setup", "cleanup", "generate_synthetic_data", "train" ]
4
[ [ "train", "cleanup" ], [ "train", "generate_synthetic_data" ], [ "train", "setup" ] ]
3
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
8431cc98bc83c9f8f155c7da6d1acdb24cbd5bd6
b57c3280f6e8e453c72b8c88b9625897785ff45f
v1.0
instruct
Docs
Docs: Python310_46030_I
### Advanced I/O Multiplexing with Python's `select` Module #### Objective Implement a function called `monitor_file_descriptors` that uses the `select` module to monitor multiple file descriptors (FDs) and handle different types of I/O events that occur on them. #### Requirements 1. The function should accept the fo...
import select def handle_read(fd): print(f"Handling read for FD {fd}") def handle_write(fd): print(f"Handling write for FD {fd}") def handle_exception(fd): print(f"Handling exception for FD {fd}") def monitor_file_descriptors(rlist, wlist, xlist, timeout=5.0) -> dict: """ Monitors multiple file ...
# To test this function, we need to mock the select function and file descriptors. # Let's assume `select.select` is correctly implemented and returns a mock result. # Note: We cannot actually test file descriptors without a proper I/O context. # This is a limitation, but we can mock the behavior. import select import...
[ { "docstring": null, "function_declaration": "def handle_read(fd):", "function_name": "handle_read", "parameter_list": "(fd)" }, { "docstring": null, "function_declaration": "def handle_write(fd):", "function_name": "handle_write", "parameter_list": "(fd)" }, { "docstring...
[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import select\n\ndef handle_read(fd):\n print(f\"Handling read for FD {fd}\")\n\ndef handle_write(fd):\n print(f\"Handling write for FD {fd}\")\n\ndef handle_exce...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00046030", "row_id": 46030, "seed_ids": "[172]" }
0.398279
Docs: Python310_46030
I
[ "handle_read", "handle_write", "handle_exception", "monitor_file_descriptors" ]
4
[ [ "monitor_file_descriptors", "handle_exception" ], [ "monitor_file_descriptors", "handle_read" ], [ "monitor_file_descriptors", "handle_write" ] ]
3
[]
false
[]
false
pytest
true
[]
true
83fbd316b80c2acf6f9501ce78ffa789fdd240c2
ffca1c1944063c3d290f74a379d5f82a9bfcddf2
v1.0
instruct
Docs
Docs: Python310_46039_I
<|Analysis Begin|> The provided documentation outlines the `hashlib` library in Python 3.10, detailing various secure hash and message digest algorithms such as SHA-1, SHA-256, BLAKE2, and more. The library offers a unified interface for these algorithms, allowing users to create hash objects, update them with bytes-l...
import hashlib def sign_message(message: bytes, secret_key: bytes) -> str: """ Produces a hexadecimal HMAC using the blake2b algorithm with a digest size of 16 bytes. """ h = hashlib.blake2b(key=secret_key, digest_size=16) h.update(message) return h.hexdigest() def verify_message(message: byte...
import pytest from solution import sign_message, verify_message, generate_personalized_hash def test_sign_message(): message = b'Hello, world!' secret_key = b'secret' expected_length = 32 # 16 bytes as hex is 32 characters hmac = sign_message(message, secret_key) assert len(hmac) == expected_length...
[ { "docstring": "Produces a hexadecimal HMAC using the blake2b algorithm with a digest size of 16 bytes.", "function_declaration": "def sign_message(message, secret_key):", "function_name": "sign_message", "parameter_list": "(message, secret_key)" }, { "docstring": "Verifies if the received H...
[ 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 hashlib\n\ndef sign_message(message: bytes, secret_key: bytes) -> str:\n \"\"\"\n Produces a hexadecimal HMAC using blake2b algorithm with a digest size of...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00046039", "row_id": 46039, "seed_ids": "[225]" }
0.74011
Docs: Python310_46039
I
[ "sign_message", "verify_message", "generate_personalized_hash" ]
3
[ [ "verify_message", "sign_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4294bcae848e19392b8c51349d0bd73ccc9b0036
f4ac52d679085dbd086be92422ed5f4a3a2de6e8
v1.0
instruct
Docs
Docs: Python310_46045_I
#### `site` Module Configuration and Customization **Objective**: Demonstrate understanding and practical usage of the `site` module in Python for site-specific configuration and path manipulations. #### Problem Statement: You are tasked with creating a Python script that customizes the Python environment by adding ...
import sys import os from pathlib import Path from typing import Dict, Any import json def add_custom_directory(path: str) -> None: """ Adds the given directory to sys.path if it exists and isn't already in sys.path. :param path: The directory to add to sys.path. :raises FileNotFoundError: If the dire...
import pytest from tempfile import TemporaryDirectory import json import os import sys from pathlib import Path # Assuming the functions are defined in a module named 'solution' from solution import add_custom_directory, process_pth_files, read_custom_configuration, initialize_custom_environment def test_add_custom_...
[ { "docstring": "Adds the given directory to sys.path if it exists and isn't already in sys.path.\n\n:param path: The directory to add to sys.path.\n:raises FileNotFoundError: If the directory does not exist.", "function_declaration": "def add_custom_directory(path):", "function_name": "add_custom_direct...
[ 0, 0, 1, 1, 1, 1, 1, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import Dict, Any\nimport os\nimport sys\nimport json\nfrom pathlib import Path\n\ndef add_custom_directory(path: str) -> None:\n \"\"\"\n Adds the giv...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00046045", "row_id": 46045, "seed_ids": "[147]" }
0.620469
Docs: Python310_46045
I
[ "add_custom_directory", "process_pth_files", "read_custom_configuration", "initialize_custom_environment" ]
4
[ [ "initialize_custom_environment", "add_custom_directory" ], [ "initialize_custom_environment", "process_pth_files" ], [ "initialize_custom_environment", "read_custom_configuration" ] ]
3
[]
false
[]
false
pytest
true
[]
true
df9883f3c1298517649b362371deb9cb4388cdd8
f56a3813d69bffcaf2b5fecf3e3027adcce7d858
v1.0
instruct
Docs
Docs: Python310_46055_I
**Question:** You are designing a mini web scraper using Python's `urllib.request` module. Your goal is to: 1. Fetch the HTML content of a given URL. 2. Extract all the URLs from the fetched HTML content. 3. Follow one level of links (i.e., fetch the HTML content of the URLs found on the initial page) and list the URL...
import urllib.request import re from urllib.error import URLError, HTTPError def fetch_html(url: str) -> str: """ Takes a URL as input and returns the HTML content of the URL as a string. Raises an exception if the URL cannot be opened. """ try: response = urllib.request.urlopen(url) ...
import pytest import urllib.request from unittest.mock import patch, Mock from solution import fetch_html, extract_urls, scrape_urls def mock_urlopen(url): mock_response = Mock() if url == 'http://example.com': mock_response.read.return_value = b'<a href="http://example1.com">Link1</a><a href="http://...
[ { "docstring": "Takes a URL as input and returns the HTML content of the URL as a string.\nRaises an exception if the URL cannot be opened.", "function_declaration": "def fetch_html(url):", "function_name": "fetch_html", "parameter_list": "(url)" }, { "docstring": "Takes HTML content as inpu...
[ 1, 1, 0, 0, 0, 0, 0, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import urllib.request\nimport re\nfrom urllib.error import URLError, HTTPError\n\ndef fetch_html(url: str) -> str:\n \"\"\"\n Takes a URL as input and returns the...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00046055", "row_id": 46055, "seed_ids": "[343]" }
0.755871
Docs: Python310_46055
I
[ "fetch_html", "extract_urls", "scrape_urls" ]
3
[ [ "scrape_urls", "extract_urls" ], [ "scrape_urls", "fetch_html" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3457cdb77238481e886d66105bdb1c6c6124dbe1
c64afadd2392327d672a971c1a77923adb1a8b26
v1.0
instruct
Docs
Docs: Python310_46058_I
**Topic**: Parallel Task Execution with `concurrent.futures` **Objective**: To evaluate students' understanding of parallel task execution using the `concurrent.futures` module, including creating, managing, and handling results from concurrent tasks. #### Problem Statement You are required to process a list of URLs...
import concurrent.futures import requests from typing import List def fetch_html(url: str) -> str: try: response = requests.get(url, timeout=5) response.raise_for_status() return response.text except requests.RequestException as e: return f"Error fetching {url}: {str(e)}" def f...
from solution import fetch_urls_concurrently def test_fetch_urls_concurrently(): urls = [ "https://www.example.com", "https://www.example.org", "https://www.example.net", ] results = fetch_urls_concurrently(urls) assert isinstance(results, list) assert len(results)...
[ { "docstring": null, "function_declaration": "def fetch_html(url):", "function_name": "fetch_html", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def fetch_urls_concurrently(urls):", "function_name": "fetch_urls_concurrently", "parameter_list": "(urls...
[ 1, 0, 0, 1, 0, 0, 0, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import concurrent.futures\nimport requests\nfrom typing import List\n\ndef fetch_url(url: str) -> str:\n try:\n response = requests.get(url, timeout=10)\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00046058", "row_id": 46058, "seed_ids": "[224]" }
0.525078
Docs: Python310_46058
I
[ "fetch_html", "fetch_urls_concurrently" ]
2
[ [ "fetch_urls_concurrently", "fetch_html" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
1ddb354d7620e5c8411e22a59928f1d485f118a6
50b96cdb0f5edbdbdebc11089ef536437f2a3839
v1.0
instruct
Docs
Docs: Python310_46060_I
### Advanced Memory Management in Python **Objective:** Implement a Python program using the `ctypes` library to interact with the C-style memory management functions provided in the documentation (specifically `PyMem_RawMalloc`, `PyMem_RawFree`, and others). This exercise will test your understanding of Python's memo...
from ctypes import * # Load the Python API shared object file pythonapi = cdll.LoadLibrary("libpython3.so") # Define the PyMem_RawMalloc, PyMem_RawRealloc, and PyMem_RawFree functions PyMem_RawMalloc = pythonapi.PyMem_RawMalloc PyMem_RawMalloc.restype = POINTER(c_void_p) PyMem_RawMalloc.argtypes = [c_size_t] PyMem_R...
from solution import allocate_raw_memory, resize_raw_memory, free_raw_memory, use_memory_management def test_allocate_raw_memory(): size = 64 mem_block = allocate_raw_memory(size) assert mem_block is not None, "Memory allocation failed" free_raw_memory(mem_block) def test_resize_raw_memory(): init...
[ { "docstring": null, "function_declaration": "def allocate_raw_memory(size):", "function_name": "allocate_raw_memory", "parameter_list": "(size)" }, { "docstring": null, "function_declaration": "def resize_raw_memory(ptr, new_size):", "function_name": "resize_raw_memory", "parame...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from ctypes import *\n\n# Load the Python C API memory management functions from the Python C library\nlibpython = CDLL(pythonapi)\n\n# Define memory management functio...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00046060", "row_id": 46060, "seed_ids": "[46]" }
0.486822
Docs: Python310_46060
I
[ "allocate_raw_memory", "resize_raw_memory", "free_raw_memory", "use_memory_management", "memset" ]
5
[ [ "use_memory_management", "allocate_raw_memory" ], [ "use_memory_management", "free_raw_memory" ], [ "use_memory_management", "memset" ], [ "use_memory_management", "resize_raw_memory" ] ]
4
[]
false
[]
false
pytest
true
[]
true
937b59cd9512611bae758f3ebe13f9c2654b5015
91ce70404d4468bb6194a74ae6158022641c92e6
v1.0
instruct
Docs
Docs: Python310_46093_I
You are tasked with simulating the settings management of a macOS application using Python's `plistlib` module. Specifically, you need to handle saving, loading, and updating application settings stored in plist files. Your task is to implement three functions: 1. **`save_settings(settings, filename, fmt='FMT_XML')`...
import plistlib import os def save_settings(settings, filename, fmt='FMT_XML'): """ Saves the settings dictionary to a plist file. :param settings: Dictionary containing settings. :param filename: Name of the file to save settings. :param fmt: Format of the plist file (either 'FMT_XML' or 'FMT_BIN...
import pytest import os import plistlib from solution import save_settings, load_settings, update_setting def test_save_and_load_settings_xml(): settings = { 'username': 'test_user', 'volume': 30 } filename = 'test_settings.xml' # Save settings save_settings(settings, filename,...
[ { "docstring": "Saves the settings dictionary to a plist file.\n\n:param settings: Dictionary containing settings.\n:param filename: Name of the file to save settings.\n:param fmt: Format of the plist file (either 'FMT_XML' or 'FMT_BINARY').", "function_declaration": "def save_settings(settings, filename, f...
[ 1, 1, 0, 1, 0, 0, 0, 0, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import plistlib\n\ndef save_settings(settings, filename, fmt='FMT_XML'):\n \"\"\"\n Save the settings dictionary to a plist file in the specified format.\n \"\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00046093", "row_id": 46093, "seed_ids": "[349]" }
0.535575
Docs: Python310_46093
I
[ "save_settings", "load_settings", "update_setting" ]
3
[ [ "update_setting", "load_settings" ], [ "update_setting", "save_settings" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b4313b4485185f0e9ba9a00acf192c63a558b2a6
dc27c30dc78e9c7245ae5d8d4252d6ac754e3939
v1.0
instruct
Docs
Docs: Scikit_46189_I
### Spectral Biclustering Question **Objective**: Implement the Spectral Biclustering algorithm from scratch and evaluate its performance using the Jaccard index. ### Problem Statement You are required to implement the Spectral Biclustering algorithm and apply it to a given dataset. The dataset is a matrix with a hi...
import numpy as np from scipy.linalg import svd from sklearn.cluster import KMeans from typing import Tuple, List, Set def bistochastization(A: np.ndarray, max_iter: int = 100, tol: float = 1e-6) -> np.ndarray: """ Normalize the matrix A to be bistochastic """ A = A / np.sum(A) for i in range(max_i...
import numpy as np from solution import bistochastization, compute_singular_vectors, find_best_singular_vectors, cluster_rows_and_columns, jaccard_index, evaluate_biclustering def test_bistochastization(): A = np.array([[0.2, 0.3, 0.5], [0.6, 0.3, 0.1], [0.2, 0.4, 0.4]]) bistochastized_A = bistochastization(A)...
[ { "docstring": "Normalize the matrix A to be bistochastic", "function_declaration": "def bistochastization(A, max_iter=100, tol=1e-06):", "function_name": "bistochastization", "parameter_list": "(A, max_iter=100, tol=1e-06)" }, { "docstring": "Compute singular vectors", "function_declara...
[ 1, 0, 0, 1, 1, 0, 1, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom scipy.linalg import svd\nfrom scipy.sparse.csgraph import connected_components\nfrom sklearn.cluster import KMeans\nfrom typing import List, Se...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00046189", "row_id": 46189, "seed_ids": "[26]" }
0.483728
Docs: Scikit_46189
I
[ "bistochastization", "compute_singular_vectors", "find_best_singular_vectors", "cluster_rows_and_columns", "jaccard_index", "evaluate_biclustering" ]
6
[ [ "evaluate_biclustering", "jaccard_index" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "scipy", "sklearn" ]
false
79219fac219c7714f8c620bbb72cd0d96bf3999a
6f93cd26bc018443dd3f8c0f2f8b7d21af0c982b
v1.0
instruct
Docs
Docs: Python310_46196_I
### Asynchronous Logging System You are tasked with creating an asynchronous logging system that can log messages from different parts of an application concurrently. This system should consist of a logger that writes to a file asynchronously and a main function which generates multiple logs concurrently. #### Requi...
import asyncio async def write_log(message: str, filename: str, delay: float) -> None: """ Writes a log message to the specified file after a delay. :param message: Log message to write. :param filename: File to write the log message to. :param delay: Time in seconds to wait before writing the log...
import pytest import asyncio from solution import write_log, generate_logs import os @pytest.fixture(scope="function", autouse=True) def setup_teardown(): # Setup: create a dummy log file open('test_application.log', 'w').close() yield # Teardown: remove the dummy log file if os.path.exists('test_a...
[]
[ 1, 0, 0, 0, 1, 0, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def write_log(message: str, filename: str, delay: float) -> None:\n \"\"\"\n Writes a log message to the specified file after a delay.\n\n...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00046196", "row_id": 46196, "seed_ids": "[317]" }
0.635545
Docs: Python310_46196
I
[ "write_log", "generate_logs", "main" ]
3
[ [ "generate_logs", "write_log" ] ]
1
[]
false
[]
false
pytest
true
[]
true
aa9fe31e386bbff1eb51fced4c3ca71a79222c90
e30a34950eccd80ec414c3495c7c8ae15071ba56
v1.0
instruct
Docs
Docs: Python310_46395_I
#### Title: Custom Set Operations and Conversions #### Objective: Implement functions that demonstrate your ability to work with Python `set` and `frozenset` objects using the provided API methods. #### Problem Statement: You need to implement two functions: `create_set_from_iterable` and `custom_set_operations`. 1...
def create_set_from_iterable(iterable): """ Create a set from the given iterable. If the iterable is None, return an empty set. Raise TypeError if the input is not iterable. """ if iterable is None: return set() try: result_set = set(iterable) except TypeError: raise ...
from solution import create_set_from_iterable, custom_set_operations def test_create_set_from_iterable_with_list(): assert create_set_from_iterable([1, 2, 3]) == {1, 2, 3} def test_create_set_from_iterable_with_tuple(): assert create_set_from_iterable((1, 2, 2, 3)) == {1, 2, 3} def test_create_set_from_itera...
[ { "docstring": "Create a set from the given iterable. If the iterable is None, return an empty set.\nRaise TypeError if the input is not iterable.", "function_declaration": "def create_set_from_iterable(iterable):", "function_name": "create_set_from_iterable", "parameter_list": "(iterable)" }, {...
[ 1, 1, 1, 1, 0, 1, 0, 0, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def create_set_from_iterable(iterable):\n \"\"\"\n Takes an iterable and returns a new set containing objects from the iterable.\n If the iterable is None, ret...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00046395", "row_id": 46395, "seed_ids": "[24]" }
0.527048
Docs: Python310_46395
I
[ "create_set_from_iterable", "custom_set_operations" ]
2
[ [ "custom_set_operations", "create_set_from_iterable" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7f20fac7160823095b1a4781658cf80fe6f4c843
13d10b526c80dbd9f710be2a130c70bca46da7d3
v1.0
instruct
Docs
Docs: Pytorch_46442_I
### PyTorch Linear Algebra - QR Decomposition and Linear System Solver In this task, you will demonstrate your understanding of PyTorch's linear algebra operations by implementing two functions. 1. **QR Decomposition using PyTorch**: Implement a function `qr_decomposition` that performs the QR decomposition of a ...
import torch from typing import Tuple def qr_decomposition(matrix: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Perform QR decomposition of a given square matrix. Arguments: matrix (torch.Tensor): A square matrix of shape (n, n). Returns: Tuple[torch.Tensor, torch.Tensor]: ...
import torch from solution import qr_decomposition, solve_linear_system_qr def test_qr_decomposition(): A = torch.tensor([[12., -51., 4.], [6., 167., -68.], [-4., 24., -41.]]) Q, R = qr_decomposition(A) assert torch.allclose(torch.matmul(Q, R), A, atol=1e-6) assert torch.allclose(torch.matmul(Q.transpo...
[ { "docstring": "Perform QR decomposition of a given square matrix.\n\nArguments:\nmatrix (torch.Tensor): A square matrix of shape (n, n).\n\nReturns:\nTuple[torch.Tensor, torch.Tensor]: A tuple containing Q and R matrices.", "function_declaration": "def qr_decomposition(matrix):", "function_name": "qr_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 torch\nfrom typing import Tuple\n\ndef qr_decomposition(matrix: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Perform QR decomposition of ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00046442", "row_id": 46442, "seed_ids": "[75]" }
0.480244
Docs: Pytorch_46442
I
[ "qr_decomposition", "solve_linear_system_qr" ]
2
[ [ "solve_linear_system_qr", "qr_decomposition" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
c8a57968a55b47608347f5bdc443dc6d8490f8d4
8c68c8942b4c413000ba24bf5033fe15c623caec
v1.0
instruct
Docs
Docs: Pytorch_46450_I
#### Problem Statement You are required to demonstrate your understanding of the `torch.futures.Future` class and related utility functions by simulating a distributed computing scenario. In this exercise, you will: 1. Create a function `async_computation` that performs a simple asynchronous operation using the `torc...
import torch import asyncio from typing import List async def async_double(value: int) -> int: """ Asynchronously doubles the input value after a short delay. Args: value (int): A numerical value to double. Returns: int: The doubled value after a delay. """ await asyncio.sleep...
import pytest import torch from solution import async_computation, process_results @pytest.mark.asyncio async def test_async_computation(): future = async_computation(10) result = await future # Await the result of the async computation assert result == 20 @pytest.mark.asyncio async def test_process_resu...
[ { "docstring": "Initiates an asynchronous computation to double the input value and returns a Future.\n\nArgs:\nvalue (int): A numerical value to be used in the computation.\n\nReturns:\ntorch.futures.Future: A future object that will complete with value * 2 after a simulated delay.", "function_declaration"...
[ 1, 1, 0, 0, 1, 1, 0, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport torch\nfrom torch.futures import Future\nfrom typing import List\n\ndef async_computation(value: int) -> Future:\n \"\"\"\n Asynchronous co...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00046450", "row_id": 46450, "seed_ids": "[53]" }
0.494897
Docs: Pytorch_46450
I
[ "async_double", "async_computation", "process_results" ]
3
[ [ "async_computation", "async_double" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
f7a8fb085ba8edc63ed4f4d5c6c2841500f7ed28
176ea2cdec656a865bc64bf0dd0905c3282c74ea
v1.0
instruct
Docs
Docs: Pytorch_46459_I
### Question: Dynamo Tracing and FX Graph Generation **Objective**: To assess your understanding of TorchDynamo and its functionality in tracing Python functions and generating FX graphs. **Problem Statement**: Create a Python function that demonstrates the use of dynamic shapes with Dynamo, generating different FX...
import torch import torch._dynamo as dynamo @dynamo.optimize("eager", dynamic=True) def dynamic_shape_operations(x): """ Perform operations based on the dynamic shape of the input tensor x. If the size of the first dimension is greater than 10, multiply by 2. Otherwise, add 5 to each element. """ ...
from solution import dynamic_shape_operations import torch def test_dynamic_shape_operations_add(): x = torch.randn(8, 3) result = dynamic_shape_operations(x) expected = x + 5 assert torch.allclose(result, expected), "Test failed: Expected addition operation for x.size(0) <= 10." def test_dynamic_shap...
[ { "docstring": "Perform operations based on the dynamic shape of the input tensor x.\nIf the size of the first dimension is greater than 10, multiply by 2.\nOtherwise, add 5 to each element.", "function_declaration": "def dynamic_shape_operations(x):", "function_name": "dynamic_shape_operations", "p...
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torchdynamo as dynamo\nimport logging\n\n# Set logger to display debug messages\nlogging.basicConfig(level=logging.DEBUG)\n\n@dynamo.optimize(\"eag...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00046459", "row_id": 46459, "seed_ids": "[122]" }
0.454305
Docs: Pytorch_46459
I
[ "dynamic_shape_operations", "demonstrate_fx_graph_generation" ]
2
[ [ "demonstrate_fx_graph_generation", "dynamic_shape_operations" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
ede29edd0ef3b97d3fbf097642459c8f29c3daf4
a9124a9d44815b823c853635cb887fcae6f6a38f
v1.0
instruct
Docs
Docs: Python310_46530_I
#### Function Composability and Memoization You need to implement a function that efficiently calculates the n-th term in a custom series defined by a certain recursive relation. Use `functools` to manage caching and function composition. ### Specifications: 1. **Function Composition and Caching:** You need to im...
from functools import lru_cache, wraps # Define the base computation function @lru_cache(maxsize=None) def compute_term(n): if n == 0: return 0 elif n == 1: return 1 return compute_term(n-1) + 2 * compute_term(n-2) # Define the transformation function def apply_transformation(f): @wrap...
from solution import compute_term, apply_transformation, transformed_series def test_compute_term_base_cases(): assert compute_term(0) == 0 assert compute_term(1) == 1 def test_compute_term_recursive_cases(): assert compute_term(2) == 1 # T(2) = T(1) + 2 * T(0) = 1 + 2 * 0 = 1 assert compute_term(3) ...
[ { "docstring": null, "function_declaration": "def compute_term(n):", "function_name": "compute_term", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def apply_transformation(f):", "function_name": "apply_transformation", "parameter_list": "(f)" }, { ...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from functools import lru_cache, wraps\n\n# Define the base computation function\n@lru_cache(maxsize=None)\ndef compute_term(n):\n if n == 0:\n return 0\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046530", "row_id": 46530, "seed_ids": "[236]" }
0.636623
Docs: Python310_46530
I
[ "compute_term", "apply_transformation", "transformed_series" ]
3
[ [ "transformed_series", "apply_transformation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
455949c25d89ad7669f0f2ba21d8f909d54e4b75
a36dacf60232e81d0e98e833038211b7e9918349
v1.0
instruct
Docs
Docs: Python310_46556_I
### Challenge: Implement Secure File Integrity Verification Using the `hmac` Module **Objective:** Write a Python program to verify the integrity of files using the HMAC algorithm. You need to implement two functions: one to generate an HMAC tag for a given file and another to verify the file's integrity using the pro...
import hmac import hashlib def generate_hmac(file_path: str, key: bytes, digestmod: str) -> str: """ Generates an HMAC tag for the given file using the specified key and hash algorithm. Args: - file_path (str): The path to the file. - key (bytes): The secret key used for HMAC. - digestmod ...
import os def test_generate_hmac(): # Create a temporary file for testing test_file_path = 'test_file.txt' test_content = b'This is a test file for HMAC generation.' with open(test_file_path, 'wb') as f: f.write(test_content) try: key = b'secret_key' digestmod = 'sha256' ...
[ { "docstring": "Generates an HMAC tag for the given file using the specified key and hash algorithm.\n\nArgs:\n- file_path (str): The path to the file.\n- key (bytes): The secret key used for HMAC.\n- digestmod (str): The hash algorithm to use (e.g., \"sha256\").\n\nReturns:\n- str: The hexadecimal HMAC tag for...
[ 1, 1, 0, 1, 1, 1, 1, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hmac\nimport hashlib\n\ndef generate_hmac(file_path: str, key: bytes, digestmod: str) -> str:\n \"\"\"\n Generates an HMAC tag for the provided file using ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00046556", "row_id": 46556, "seed_ids": "[298]" }
0.722174
Docs: Python310_46556
I
[ "generate_hmac", "verify_file_integrity" ]
2
[ [ "verify_file_integrity", "generate_hmac" ] ]
1
[]
false
[]
false
pytest
false
[]
true
d85d6dfe68c8dc5a68c14cf643019324788de373
7c525290427370d08df4fde7b5dd5a6ae818734a
v1.0
instruct
Docs
Docs: Python310_46579_I
### Advanced Python Coding Assessment: Asynchronous Subprocess Management **Objective**: Assess the understanding and ability to implement asynchronous subprocess handling in Python using `asyncio`. **Problem Statement**: You are to implement a function `run_multiple_subprocesses(commands: list, timeout: int) -> dic...
import asyncio import shlex async def run_command(command: str, timeout: int): process = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) try: stdout, stderr = await asyncio.wait_for(process.communicate(), timeo...
import pytest from solution import run_multiple_subprocesses @pytest.mark.asyncio async def test_single_command_ls(): commands = ["ls /"] timeout = 5 results = await run_multiple_subprocesses(commands, timeout) assert "ls /" in results assert results["ls /"][0] == 0 assert results["ls /"][1] is...
[]
[ 1, 0, 0, 1, 0, 0, 0, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport shlex\n\nasync def run_command(command: str, timeout: int):\n process = await asyncio.create_subprocess_shell(\n command,\n stdo...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00046579", "row_id": 46579, "seed_ids": "[264]" }
0.731234
Docs: Python310_46579
I
[ "run_command", "run_multiple_subprocesses" ]
2
[ [ "run_multiple_subprocesses", "run_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
684af96b8fd4be93cb9d879cdb5d51086fdcbe17
41c4e4efada29f6caba73bd0572ed0f8c7394019
v1.0
instruct
Docs
Docs: Python310_46603_I
**Question: Asynchronous Download Manager** You are to implement an asynchronous download manager using the `asyncio` module. The download manager will perform multiple "download" tasks concurrently, each task downloading a file whose size is specified. For simplicity, assume "downloading a file" is simulated by a sle...
import asyncio from typing import Dict, List, Tuple async def download_file(file_id: int, size: int) -> int: """Simulates a file download by sleeping for 'size' seconds and returns the 'file_id'.""" await asyncio.sleep(size) return file_id async def download_manager(file_sizes: Dict[int, int], timeout: fl...
import asyncio from solution import download_file, download_manager def test_download_file(): result = asyncio.run(download_file(1, 1)) assert result == 1 def test_download_manager(): file_sizes = {1: 2, 2: 4, 3: 1} timeout = 3.0 completed, cancelled = asyncio.run(download_manager(file_sizes, time...
[]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import Dict, List, Tuple\n\nasync def download_file(file_id: int, size: int) -> int:\n \"\"\"\n Simulates a file download by sleeping ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00046603", "row_id": 46603, "seed_ids": "[317]" }
0.514636
Docs: Python310_46603
I
[ "download_file", "download_manager" ]
2
[ [ "download_manager", "download_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
be6fb07f1d59dfb53ea9cf0083d295aad1c7e30b
62141573921f10473a32f560f55ce6c17c5e281d
v1.0
instruct
Docs
Docs: Pytorch_46721_I
**Title: Distributed Matrix Multiplication using PyTorch RRef Protocol** **Objective:** The goal of this exercise is to test the student's understanding of PyTorch's distributed RPC framework, specifically focusing on the creation, usage, and lifecycle management of Remote References (RRefs). **Scenario:** You are p...
import torch import torch.distributed.rpc as rpc def setup_workers(): """ Initializes the RPC framework and sets up the workers. """ options = rpc.TensorPipeRpcBackendOptions(init_method='tcp://127.0.0.1:29500') rpc.init_rpc("worker0", rank=0, world_size=3, rpc_backend_options=options) rpc.init...
import torch from solution import generate_matrices, split_matrix, gather_results, result_storage def test_generate_matrices(): A, B = generate_matrices() assert A.shape == (1024, 1024) assert B.shape == (1024, 1024) def test_split_matrix(): matrix = torch.rand(1024, 1024) sub_matrices = split_mat...
[ { "docstring": "Initializes the RPC framework and sets up the workers.", "function_declaration": "def setup_workers():", "function_name": "setup_workers", "parameter_list": "()" }, { "docstring": "Generates two random 1024x1024 matrices on worker0.\nReturns:\n Tuple[torch.Tensor, torch.Te...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.distributed.rpc as rpc\nfrom torch.distributed.rpc import RRef\n\ndef setup_workers():\n \"\"\"\n Initializes the RPC framework and set...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00046721", "row_id": 46721, "seed_ids": "[158]" }
0.333505
Docs: Pytorch_46721
I
[ "setup_workers", "generate_matrices", "split_matrix", "create_and_share_rrefs", "process_sub_matrix", "collect_result", "gather_results" ]
7
[ [ "create_and_share_rrefs", "process_sub_matrix" ], [ "process_sub_matrix", "collect_result" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
a6234e11cf821554dd2316b6d4fc11290ed01c6f
6f08af437d07f5004fa72418195a3801762e4d11
v1.0
instruct
Docs
Docs: Python310_46739_I
### Advanced Python Coding Assessment: Design a File Transfer Service Using asyncio Streams #### Objective Create a simple file transfer service using asyncio streams. The service involves two parts: 1. A **file server** that listens on a specified TCP port and waits for a file transfer. 2. A **file client** that conn...
import asyncio import os import sys async def handle_client(reader, writer): try: # Receive file name data = await reader.read(100) file_name = data.decode().strip() # Receive file content file_data = await reader.read(10485760) # Maximum file size is 10MB ...
import asyncio import os import tempfile import pytest from solution import start_server, send_file @pytest.fixture def temp_file(): with tempfile.NamedTemporaryFile(delete=False) as tmp: tmp.write(b'This is a test file.') yield tmp.name os.remove(tmp.name) @pytest.fixture def async_server(): ...
[]
[ 1, 0, 0, 0, 1, 1, 0, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport os\nimport sys\n\nasync def handle_client(reader, writer):\n try:\n # Read filename size (first 4 bytes)\n size_data = await rea...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00046739", "row_id": 46739, "seed_ids": "[182]" }
0.588734
Docs: Python310_46739
I
[ "handle_client", "start_server", "send_file" ]
3
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3b4b645dc74a842153a1135a1ce1d741e4a2cbad
aca6fbafb5fb838d5f2a8f5acf2d98c5cef52a4e
v1.0
instruct
Docs
Docs: Python310_46743_I
### Python Coding Assessment Question **Objective:** You are to write a Python program using the `asyncio` streams functionality. The task involves creating a simple TCP chat server that can handle multiple clients simultaneously using async/await. Each client's messages should be broadcasted to all connected clients ...
import asyncio from typing import List, Tuple clients = [] async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): addr = writer.get_extra_info('peername') clients.append((reader, writer)) print(f"Connected to {addr}") try: while True: data = await rea...
import asyncio import pytest from solution import start_chat_server, clients @pytest.mark.asyncio async def test_server_communication(): host, port = '127.0.0.1', 8888 server_task = asyncio.create_task(start_chat_server(host, port)) await asyncio.sleep(1) # Give the server a moment to start reader1...
[]
[ 1, 1, 1, 1, 0, 1, 1, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\n\nclients = []\n\nasync def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):\n addr = write...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00046743", "row_id": 46743, "seed_ids": "[182]" }
0.595634
Docs: Python310_46743
I
[ "handle_client", "start_chat_server" ]
2
[ [ "start_chat_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7526ef2f93db39c694e64d4d6ad445cae8c4e4b1
ebde1ab7f6d780c5d08f8a127cd3ba5b1d1af606
v1.0
instruct
Docs
Docs: Python310_46861_I
### Advanced Python Coding Assessment: Concurrent Task Management Using the shared documentation on the "concurrent.futures" module, solve the following problem that assesses your understanding of concurrent task management in Python. #### Problem Statement: You are required to implement a function `process_urls(urls...
from typing import List, Tuple import concurrent.futures import urllib.request def fetch_url(url: str, timeout: int) -> bool: try: with urllib.request.urlopen(url, timeout=timeout) as response: return response.status == 200 except Exception: return False def process_urls(ur...
from solution import process_urls import urllib.error from unittest import mock def mock_urlopen(url, timeout): """ Mock response for urllib.request.urlopen based on the URL. """ class MockResponse: def __init__(self, url): self.url = url self.status = 200 if "example" in url el...
[ { "docstring": null, "function_declaration": "def fetch_url(url, timeout):", "function_name": "fetch_url", "parameter_list": "(url, timeout)" }, { "docstring": null, "function_declaration": "def process_urls(urls, timeout):", "function_name": "process_urls", "parameter_list": "(u...
[ 0, 0, 0, 1, 0, 0, 1, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nimport concurrent.futures\nimport urllib.request\n\ndef fetch_url(url: str, timeout: int) -> bool:\n try:\n with urllib.reques...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00046861", "row_id": 46861, "seed_ids": "[347]" }
0.584863
Docs: Python310_46861
I
[ "fetch_url", "process_urls" ]
2
[ [ "process_urls", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[]
true
734a7cf21ccb33a3bad4c832320391c85de7f3d6
6da8bf689f452989c6df476b8c051a29092c18ab
v1.0
instruct
Docs
Docs: Python310_46891_I
### Problem Description You are required to implement a Python program that uses the `signal` module to set up a signal handler for `SIGUSR1` and manage an interval timer using `signal.setitimer`. Your program should handle the `SIGUSR1` signal by printing a message indicating the signal was received, and it should us...
import signal import time import sys def handle_sigusr1(signum, frame): print("Received SIGUSR1") def handle_sigalrm(signum, frame): print("Terminating the task") sys.exit(0) def register_signal_handler(): signal.signal(signal.SIGUSR1, handle_sigusr1) def setup_interval_timer(interval): signal.s...
import subprocess import os import signal import time # We need to run the script in a separate process to test signal handling effectively def test_signal_handling(): p = subprocess.Popen(['python3', 'solution.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) time.sleep(1) # Allow some time for the proce...
[ { "docstring": null, "function_declaration": "def handle_sigusr1(signum, frame):", "function_name": "handle_sigusr1", "parameter_list": "(signum, frame)" }, { "docstring": null, "function_declaration": "def handle_sigalrm(signum, frame):", "function_name": "handle_sigalrm", "para...
[ 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import signal\nimport time\nimport sys\n\ndef signal_handler_usr1(signum, frame):\n print(\"Received SIGUSR1\")\n\ndef signal_handler_alrm(signum, frame):\n print...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046891", "row_id": 46891, "seed_ids": "[253]" }
0.562939
Docs: Python310_46891
I
[ "handle_sigusr1", "handle_sigalrm", "register_signal_handler", "setup_interval_timer", "long_running_task", "main" ]
6
[ [ "register_signal_handler", "handle_sigusr1" ], [ "setup_interval_timer", "handle_sigalrm" ] ]
2
[]
false
[]
false
pytest
false
[]
true
43e383f5596319c00810c07e00e401776bae4cd0
57af892aa16f77b244f0c7f2cabcd97c2b88ae45
v1.0
instruct
Docs
Docs: Python310_46950_I
## Question: Web Scraper and Data Fetcher Using the `urllib` and `http.client` modules, implement a Python function that performs the following tasks: 1. **Fetch URLs**: Given a list of URLs, fetch the content of each URL. 2. **Parse Links**: From the fetched content, extract all hyperlinks (`<a>` tags with `href` at...
import urllib.request import http.client from concurrent.futures import ThreadPoolExecutor from typing import List, Dict, Union from urllib.parse import urlparse import re def fetch_url(url: str) -> Union[str, str]: """ Fetch a URL and return the content or an error message. """ try: with urlli...
from solution import fetch_and_parse_urls def test_fetch_and_parse_urls_empty_list(): assert fetch_and_parse_urls([]) == {} def test_fetch_and_parse_urls_valid_urls(): # Mock responses for testing from unittest.mock import patch html_example = """ <html> <head><title>Example</title></head...
[ { "docstring": "Fetch a URL and return the content or an error message.", "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_list": "(url)" }, { "docstring": "Parse HTML content and extract all hyperlinks.", "function_declaration": "def parse_links(ht...
[ 0, 1, 1, 0, 1, 1, 0, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import urllib.request\nfrom urllib.error import URLError, HTTPError\nimport re\nimport concurrent.futures\nfrom typing import List, Dict, Union\n\ndef fetch_url_content...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00046950", "row_id": 46950, "seed_ids": "[160]" }
0.742174
Docs: Python310_46950
I
[ "fetch_url", "parse_links", "fetch_and_parse_urls" ]
3
[ [ "fetch_and_parse_urls", "fetch_url" ], [ "fetch_and_parse_urls", "parse_links" ] ]
2
[]
false
[]
false
pytest
true
[]
true
bf981a60ee8ff1f27eb01d996cd590762fe3b90d
16e1c0b2f34dbdd64fbdf39437492b8e27d14a96
v1.0
instruct
Docs
Docs: Pytorch_46970_I
## Custom Pytorch Function Implementation and Verification ### Objective Implement a custom PyTorch function using the `torch.autograd.Function` class to evaluate forward and backward passes for a simple operation. Verify the correctness of your implementation by comparing the gradients computed by your backward metho...
import torch from torch.autograd import Function from torch.autograd import gradcheck class MyExpFunction(Function): @staticmethod def forward(ctx, input): # Compute the exponential of the input tensor exp_input = torch.exp(input) # Save necessary tensors for the backward pass c...
import torch from torch.autograd import gradcheck from solution import my_exp, validate_gradcheck # Validate custom exported operations def test_my_exp_forward(): input = torch.tensor([1.0, 2.0, 3.0], requires_grad=True) output = my_exp(input) expected_output = torch.exp(input) assert torch.allclose(ou...
[]
[ 1, 0, 0, 1, 1, 0, 1, 0, 1, 1 ]
6
medium
0.6
{ "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.autograd import gradcheck\n\nclass MyExpFunction(Function):\n @staticmethod\n def forward(ctx, input...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00046970", "row_id": 46970, "seed_ids": "[172]" }
0.489185
Docs: Pytorch_46970
I
[ "my_exp", "validate_gradcheck" ]
2
[ [ "validate_gradcheck", "my_exp" ] ]
1
[]
false
[ "MyExpFunction" ]
true
pytest
true
[ "torch" ]
false
9bbc1185343a73af09a0c65f2cf1a5567e8b86b7
a355b681b9f2d353376024f4cf801a963c6f7fab
v1.0
instruct
Docs
Docs: Python310_46990_I
<|Analysis Begin|> The provided documentation describes the event loop in Python's asyncio package in detail. It explains how to obtain the event loop, run and stop it, schedule callbacks, create Futures and Tasks, manage network connections, servers, and subprocesses, and work with sockets. It also details the APIs f...
import asyncio import json tasks = [] async def schedule_task(delay: int, name: str): await asyncio.sleep(delay) print(f'Task {name} executed') for task in tasks: if task["name"] == name: task["status"] = "Completed" async def handle_client(reader, writer): data = json.dumps(tasks...
import asyncio import json import socket import pytest from solution import tasks, schedule_task, handle_client, tcp_server @pytest.fixture def setup_tasks(): tasks.clear() tasks.append({"name": "Task1", "delay": 2, "status": "Scheduled"}) tasks.append({"name": "Task2", "delay": 5, "status": "Scheduled"}) ...
[]
[ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport json\n\ntasks = []\n\nasync def schedule_task(delay: int, name: str):\n await asyncio.sleep(delay)\n print(f'Task {name} executed')\n fo...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00046990", "row_id": 46990, "seed_ids": "[267]" }
0.5762
Docs: Python310_46990
I
[ "schedule_task", "handle_client", "tcp_server", "main" ]
4
[ [ "tcp_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e6e798d2963a813290d518b1d823fc64c7138e90
6e9cb8e431f50455781e5ecddc20a2e3c0911648
v1.0
instruct
Docs
Docs: Python310_47012_I
### Problem Description In this coding assessment, you will implement a Python function that utilizes the `asyncio` library to perform asynchronous web scraping tasks. The primary task is to scrape multiple web pages concurrently and return the combined results. ### Task Implement the function `async scrape_urls(urls...
import asyncio from typing import List, Dict, Any import aiohttp async def fetch(url: str, timeout: int) -> str: """ Fetches the content of a URL within the defined timeout. Returns the content of the URL or an error message if failed. """ try: async with aiohttp.ClientSession() as session:...
import pytest import asyncio from solution import scrape_urls @pytest.mark.asyncio async def test_scrape_urls_success(): urls = ["https://jsonplaceholder.typicode.com/posts/1", "https://jsonplaceholder.typicode.com/posts/2"] timeout = 2 result = await scrape_urls(urls, timeout) assert isin...
[]
[ 1, 1, 1, 0, 0, 1, 1, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Dict, Any\nimport aiohttp\n\nasync def fetch(url: str, timeout: int) -> str:\n \"\"\"\n Fetches the content of a URL with...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00047012", "row_id": 47012, "seed_ids": "[317]" }
0.669389
Docs: Python310_47012
I
[ "fetch", "scrape_urls" ]
2
[ [ "scrape_urls", "fetch" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
cf92cc00da6a901c3aeb06532d6763c05307b2d3
c4d0d8f2914f7247001a2162a7ef565f720721d0
v1.0
instruct
Docs
Docs: Python310_47070_I
**Objective:** Demonstrate your understanding of Python's high-level data types, file I/O, and modular programming by implementing a complex data processing task. #### Problem Statement You are given a text file `library_database.txt` that contains library records. Each record is on a new line, and each field within ...
import os def read_library_database(file_name='library_database.txt'): """ Reads the library records from a text file and returns them as a list of dictionaries. Each dictionary represents a book's record with the following keys: 'title', 'author', 'year', 'genre', 'shelf'. """ if not os.path....
import os import pytest from solution import display_books_by_genre, search_book_by_title, add_new_record # Mock data for testing mock_data = """The Great Gatsby;F. Scott Fitzgerald;1925;Fiction;A1 To Kill a Mockingbird;Harper Lee;1960;Fiction;A2 A Brief History of Time;Stephen Hawking;1988;Science;B1 The Art of Compu...
[ { "docstring": "Reads the library records from a text file and returns them as a list of dictionaries.\nEach dictionary represents a book's record with the following keys: \n'title', 'author', 'year', 'genre', 'shelf'.", "function_declaration": "def read_library_database(file_name='library_database.txt'):",...
[ 1, 1, 1, 0, 1, 0, 1, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\n\ndef read_library_records(filepath='library_database.txt'):\n \"\"\"\n Reads library records from the given file and returns a list of dictionaries.\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00047070", "row_id": 47070, "seed_ids": "[421]" }
0.483257
Docs: Python310_47070
I
[ "read_library_database", "display_books_by_genre", "search_book_by_title", "add_new_record" ]
4
[ [ "display_books_by_genre", "read_library_database" ], [ "search_book_by_title", "read_library_database" ] ]
2
[]
false
[]
false
pytest
true
[]
true
45f768a2969838f7fa52fd3e664c028c393dba58
5ab690725758f70079318d0067e8681cecec909d
v1.0
instruct
Docs
Docs: Python310_47231_I
User Management with pwd Module Given the Unix `pwd` module, you are required to write a Python script that performs the following tasks: 1. **Get User Information by Username**: Implement a function `get_user_by_name(username: str) -> dict` that takes a username as input and returns a dictionary containing the user'...
import pwd from typing import List, Optional, Dict def get_user_by_name(username: str) -> Optional[Dict[str, str]]: try: pw_record = pwd.getpwnam(username) user_info = { "pw_name": pw_record.pw_name, "pw_passwd": pw_record.pw_passwd, "pw_uid": pw_record.pw_uid, ...
from solution import get_user_by_name, list_all_users, has_root_access import pytest import pwd def test_get_user_by_name_existing_user(): user_info = get_user_by_name('root') assert user_info is not None assert user_info['pw_name'] == 'root' assert user_info['pw_uid'] == 0 def test_get_user_by_name_n...
[ { "docstring": null, "function_declaration": "def get_user_by_name(username):", "function_name": "get_user_by_name", "parameter_list": "(username)" }, { "docstring": null, "function_declaration": "def list_all_users():", "function_name": "list_all_users", "parameter_list": "()" ...
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pwd\n\ndef get_user_by_name(username: str) -> dict:\n \"\"\"\n Returns user information for a given username.\n If the user is not found, returns None.\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00047231", "row_id": 47231, "seed_ids": "[281]" }
0.450798
Docs: Python310_47231
I
[ "get_user_by_name", "list_all_users", "has_root_access" ]
3
[ [ "has_root_access", "get_user_by_name" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2a86af6d7bc8a7e324cb1727b941174d0a52fad1
7ce89563cc46821d46f17f73aee59a8d2938ecd7
v1.0
instruct
Docs
Docs: Python310_47236_I
### Asynchronous Web Scraper You are tasked with building an asynchronous web scraper using the `asyncio` library in Python 3.10. The scraper should be able to fetch and parse a list of URLs concurrently and extract certain data from the fetched HTML content. #### Problem Statement 1. You have a list of URLs that yo...
import asyncio import aiohttp from bs4 import BeautifulSoup async def fetch_url(session, url): """ Fetch the HTML content of a given URL asynchronously. Parameters: session (aiohttp.ClientSession): The aiohttp session to use for the request. url (str): The URL to fetch. Returns: ...
import pytest import asyncio from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop from aiohttp import web from solution import fetch_url, extract_links, main class TestWebScraper(AioHTTPTestCase): async def get_application(self): async def handler(request): return web.Response(tex...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nfrom bs4 import BeautifulSoup\n\nasync def fetch_url(session, url):\n \"\"\"\n Fetch the HTML content of a given URL asynchronousl...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00047236", "row_id": 47236, "seed_ids": "[270]" }
0.661942
Docs: Python310_47236
I
[ "fetch_url", "extract_links", "worker", "main" ]
4
[ [ "worker", "extract_links" ], [ "worker", "fetch_url" ] ]
2
[]
false
[]
false
pytest
true
[ "aiohttp", "bs4" ]
false
fe3d7ffca95464c4f53d28769fb93acb3076074c
122798e4445e460a6d86fcdb293da7f0c9902bb3
v1.0
instruct
Docs
Docs: Pytorch_47251_I
In this assignment, you will demonstrate your proficiency in managing devices, streams, and the random number generator in PyTorch's `torch.xpu` module. You will write functions that: 1. Initialize the XPU devices. 2. Set a specific random seed for reproducibility across all devices. 3. Create and manage streams for pa...
import torch def initialize_devices(): """ Initializes the XPU devices and checks if any devices are available. Returns: A list of available device IDs (integers). """ if torch.xpu.is_available(): num_devices = torch.xpu.device_count() return list(range(num_devices)) ...
import pytest import torch from solution import initialize_devices, set_global_seed, parallel_computation, optimize_memory def test_initialize_devices(): device_ids = initialize_devices() if torch.xpu.is_available(): assert len(device_ids) > 0 assert all(isinstance(id, int) for id in device_ids...
[ { "docstring": "Initializes the XPU devices and checks if any devices are available.\n\nReturns:\n A list of available device IDs (integers).", "function_declaration": "def initialize_devices():", "function_name": "initialize_devices", "parameter_list": "()" }, { "docstring": "Sets the sa...
[ 0, 0, 1, 1, 0, 1, 1, 1, 1 ]
6
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom typing import List, Dict\n\ndef initialize_devices():\n \"\"\"\n Initializes the XPU devices and checks if any devices are available.\n \"\"...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00047251", "row_id": 47251, "seed_ids": "[140]" }
0.451369
Docs: Pytorch_47251
I
[ "initialize_devices", "set_global_seed", "parallel_computation", "optimize_memory" ]
4
[ [ "set_global_seed", "initialize_devices" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
926ea9515c64c4d1dc8855a60c41ff6f567cf3e5
0128347eac40ab228a5af9c4477ce8e9e654fabf
v1.0
instruct
Docs
Docs: Python310_47252_I
### Question: Parallel Task Execution Using ThreadPoolExecutor #### Objective: Write a Python function that processes a list of URLs concurrently to fetch the content using the `concurrent.futures.ThreadPoolExecutor`. Use this function to compute the total size of the combined content of all URLs. #### Function Signa...
from typing import List import concurrent.futures import urllib.request def fetch_url_content_size(url: str) -> int: try: with urllib.request.urlopen(url) as response: content = response.read() return len(content) except Exception as e: # In case of an exception, conside...
import pytest from unittest.mock import patch from solution import fetch_urls_total_size, fetch_url_content_size def fake_urlopen(url): """ This function simulates the behavior of urllib.request.urlopen for different URLs. """ class FakeResponse: def __init__(self, content): self.co...
[ { "docstring": null, "function_declaration": "def fetch_url_content_size(url):", "function_name": "fetch_url_content_size", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def fetch_urls_total_size(urls):", "function_name": "fetch_urls_total_size", "par...
[ 0, 1, 0, 0, 0, 1, 1, 1, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ThreadPoolExecutor\nfrom typing import List\nimport urllib.request\n\ndef fetch_url_content_length(url: str) -> int:\n try:\n w...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00047252", "row_id": 47252, "seed_ids": "[206]" }
0.527776
Docs: Python310_47252
I
[ "fetch_url_content_size", "fetch_urls_total_size" ]
2
[ [ "fetch_urls_total_size", "fetch_url_content_size" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8b4fd02defdad1ca32aa6d93a7d9a765497b8484
fa9356c44c738cff55b73aeebdbb2bb2d325d0bf