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_34217_I
### Coding Assessment: Custom Traceback Handling and Formatting #### Objective: To demonstrate your understanding of the `traceback` module in Python, you will implement a custom error handling and logging mechanism that formats stack traces and exception information in a specific manner. #### Task: 1. **Function `c...
import traceback import sys def custom_traceback_formatter(limit=None, capture_locals=False): """ Captures a formatted traceback of any exception that occurs within its scope. Parameters: limit (Optional[int]): Maximum number of stack trace entries to show. If None, show all entries. c...
import pytest from solution import custom_traceback_formatter def test_traceback_no_limit_no_locals(): output = custom_traceback_formatter() assert "ValueError: An intentional error!" in output assert "File" in output def test_traceback_with_limit_no_locals(): output = custom_traceback_formatter(limit...
[ { "docstring": "Captures a formatted traceback of any exception that occurs within its scope.\n\nParameters:\n limit (Optional[int]): Maximum number of stack trace entries to show. If None, show all entries.\n capture_locals (bool): Determines whether to capture local variables in the stack trace.\n\nRetu...
[ 0, 0, 0, 0, 0, 1, 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": "def custom_traceback_formatter(limit=None, capture_locals=False):\n import traceback\n import sys\n\n try:\n # Example code to intentionally raise an ex...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00034217", "row_id": 34217, "seed_ids": "[335]" }
0.522056
Docs: Python310_34217
I
[ "custom_traceback_formatter", "test_custom_traceback_formatter" ]
2
[ [ "test_custom_traceback_formatter", "custom_traceback_formatter" ] ]
1
[]
false
[]
false
pytest
true
[]
true
58d2048ce4257f8671ec43e7aa00c4c5cce90dd9
32affb5b1f390272844ba677036ae48bdfb5bee0
v1.0
instruct
Docs
Docs: Python310_34242_I
### Python Built-in Functions Assessment **Objective:** To demonstrate your understanding and ability to integrate Python's built-in functions in solving a given problem. **Problem Statement:** You are provided with a list of tuples, each containing a student's name and their respective scores in multiple subjects. ...
def calculate_averages(students): """ Returns a dictionary with student names as keys and their average scores as values. """ return {name: round(sum(scores) / len(scores), 2) for name, scores in students} def top_scorers_by_subject(students): """ Returns a dictionary with subject indices as ke...
from solution import calculate_averages, top_scorers_by_subject, overall_top_scorer, score_threshold_check def test_calculate_averages(): students = [("Alice", [95, 80, 87]), ("Bob", [75, 85, 90]), ("Charlie", [80, 85, 80])] expected_output = {"Alice": 87.33, "Bob": 83.33, "Charlie": 81.67} assert calculat...
[ { "docstring": "Returns a dictionary with student names as keys and their average scores as values.", "function_declaration": "def calculate_averages(students):", "function_name": "calculate_averages", "parameter_list": "(students)" }, { "docstring": "Returns a dictionary with subject indice...
[ 1, 0, 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": "def calculate_averages(students):\n \"\"\"\n Returns the average score for each student.\n \"\"\"\n return {name: round(sum(scores) / len(scores), 2) for na...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00034242", "row_id": 34242, "seed_ids": "[105]" }
0.70344
Docs: Python310_34242
I
[ "calculate_averages", "top_scorers_by_subject", "overall_top_scorer", "score_threshold_check" ]
4
[ [ "overall_top_scorer", "calculate_averages" ], [ "score_threshold_check", "calculate_averages" ] ]
2
[]
false
[]
false
pytest
true
[]
true
876101f01a3a3a44b847e45cfdfb24ff3f0c843e
91d820262026256832e954fbbc1de4f0220b126c
v1.0
instruct
Docs
Docs: Python310_34263_I
<|Analysis Begin|> The provided documentation focuses on Python's `socket` module, which is a low-level networking interface that allows Python programs to communicate over networks using the BSD socket interface. The module provides functions for creating socket objects, binding them to addresses, listening for conne...
import socket import threading clients = [] def broadcast(message, client_socket): for client in clients: if client != client_socket: try: client.send(message) except: remove(client) def handle_client(client_socket): while True: try: ...
import threading import socket import time from solution import start_server, start_client # To avoid actual network use during tests, we'll need to mock networking. # However, we'll provide a simple pattern for testing with real sockets for integration testing. def test_start_server(): server_thread = threading....
[ { "docstring": null, "function_declaration": "def broadcast(message, client_socket):", "function_name": "broadcast", "parameter_list": "(message, client_socket)" }, { "docstring": null, "function_declaration": "def handle_client(client_socket):", "function_name": "handle_client", ...
[ 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 socket\nimport threading\n\nclients = []\n\ndef broadcast_message(message, sender_socket):\n for client in clients:\n if client != sender_socket:\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00034263", "row_id": 34263, "seed_ids": "[319]" }
0.657337
Docs: Python310_34263
I
[ "broadcast", "handle_client", "remove", "start_server", "start_client" ]
5
[ [ "broadcast", "remove" ], [ "handle_client", "broadcast" ], [ "handle_client", "remove" ] ]
3
[]
false
[]
false
pytest
true
[]
true
2c9988b6eb30f048a72e067d91f67b78554fe9da
8748f69852475bae8f58e26ce114711461f07fe2
v1.0
instruct
Docs
Docs: Python310_34268_I
#### Problem Statement You are tasked with creating a command-line utility using the `argparse` module in Python. This utility will be called `dbtool` and it will manage a simple key-value store in a JSON file. The utility should support the following sub-commands: 1. **add**: Adds a new key-value pair to the store. ...
import argparse import json import os def load_store(file): if not os.path.exists(file): return {} with open(file, 'r') as f: return json.load(f) def save_store(file, store): with open(file, 'w') as f: json.dump(store, f, indent=4) def add_entry(file, key, value): store = load...
import os import json import pytest from solution import add_entry, remove_entry, update_entry, get_entry def setup_function(function): """ Set up a clean slate for each test function by creating a fresh JSON file. """ initial_data = {"name": "Alice"} with open('test_store.json', 'w') as f: json.du...
[ { "docstring": null, "function_declaration": "def load_store(file):", "function_name": "load_store", "parameter_list": "(file)" }, { "docstring": null, "function_declaration": "def save_store(file, store):", "function_name": "save_store", "parameter_list": "(file, store)" }, ...
[ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import argparse\nimport json\nimport os\n\ndef add_entry(file, key, value):\n if os.path.exists(file):\n with open(file, 'r') as f:\n data = json.l...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00034268", "row_id": 34268, "seed_ids": "[139]" }
0.552319
Docs: Python310_34268
I
[ "load_store", "save_store", "add_entry", "remove_entry", "update_entry", "get_entry", "dbtool" ]
7
[ [ "add_entry", "load_store" ], [ "add_entry", "save_store" ], [ "dbtool", "add_entry" ], [ "dbtool", "get_entry" ], [ "dbtool", "remove_entry" ], [ "dbtool", "update_entry" ], [ "get_entry", "load_store" ], [ "remove_entry", ...
11
[]
false
[]
false
pytest
true
[]
true
90d595bb757efc0f31c22cfdc25e3674b035bfd1
95d5f1cdb6bf24bc192793d8c48c5325759cbfe8
v1.0
instruct
Docs
Docs: Python310_34282_I
Internationalizing an Application #### Problem Statement You are tasked with designing a Python application that supports multiple languages. Your application should allow the user to select a preferred language and display messages in that language. Implement the following functionalities using the `gettext` module:...
import gettext # Dictionary to simulate the translation files (.mo files) translations = { 'fr': { 'greeting': 'Bonjour', 'farewell': 'Au revoir', 'thanks': 'Merci' }, 'es': { 'greeting': 'Hola', 'farewell': 'Adiós', 'thanks': 'Gracias' } } # Define a va...
import pytest from solution import set_language, display_message, get_deferred_translation def test_display_message_french(): assert display_message('fr', 'greeting') == 'Bonjour' assert display_message('fr', 'farewell') == 'Au revoir' assert display_message('fr', 'thanks') == 'Merci' def test_display_mes...
[ { "docstring": "Sets the current language of the application.", "function_declaration": "def set_language(language_code):", "function_name": "set_language", "parameter_list": "(language_code)" }, { "docstring": "Returns the translated message for the given language code and message ID.", ...
[ 1, 0, 1, 0, 0, 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 gettext\nimport os\n\n# Simulate translation files by creating dictionaries\ntranslations = {\n 'en': {\n 'greeting': 'Hello',\n 'farewell': 'Go...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00034282", "row_id": 34282, "seed_ids": "[231]" }
0.48426
Docs: Python310_34282
I
[ "set_language", "display_message", "get_deferred_translation" ]
3
[ [ "get_deferred_translation", "display_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0861ad1c57e1b8ea30c99c35d735cc7752f7b5f7
f07ba9daf98af43e78b717893c5e6b2b6a9e8ab7
v1.0
instruct
Docs
Docs: Python310_34378_I
#### Objective: This coding question assesses the understanding and application of the `sqlite3` module's core functionalities, including database connections, executing SQL, and creating custom SQL functions. #### Problem Statement: Assume you are developing a personal library management system that stores details a...
import sqlite3 def setup_database(file_path): """ Set up the SQLite database with the required 'books' table. """ conn = sqlite3.connect(file_path) cursor = conn.cursor() create_table_query = """ CREATE TABLE IF NOT EXISTS books ( id INTEGER PRIMARY KEY, title TEXT, ...
import os import pytest from solution import setup_database, insert_books, fetch_highly_rated_books, register_uppercase_function DATABASE_PATH = 'test_library.db' def setup_module(module): # Setup database setup_database(DATABASE_PATH) def teardown_module(module): # Clean up test database file os.rem...
[ { "docstring": "Set up the SQLite database with the required 'books' table.", "function_declaration": "def setup_database(file_path):", "function_name": "setup_database", "parameter_list": "(file_path)" }, { "docstring": "Insert multiple book records into the 'books' table.", "function_d...
[ 1, 1, 1, 1, 1, 1, 0, 1, 0, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sqlite3\n\ndef setup_database(file_path):\n conn = sqlite3.connect(file_path)\n cursor = conn.cursor()\n cursor.execute('''\n CREATE TABLE books ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00034378", "row_id": 34378, "seed_ids": "[103]" }
0.626456
Docs: Python310_34378
I
[ "setup_database", "insert_books", "fetch_highly_rated_books", "uppercase", "register_uppercase_function" ]
5
[ [ "register_uppercase_function", "uppercase" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7fbff12f9992eb7dea33dc404503665608efabbf
754acf59c9641735df76fbe8a4f00382b0aac739
v1.0
instruct
Docs
Docs: Pytorch_34393_I
### Masked Tensor Sum with PyTorch Using the PyTorch library and the given block mask utilities from `torch.nn.attention.flex_attention`, write a function `masked_tensor_sum` that computes the sum of elements in a tensor subject to a complex masking condition. #### Function Signature: ```python def masked_tensor_sum(...
import torch # Placeholder functions to mock the behavior of mask creation utilities def create_block_mask(tensor): return torch.ones_like(tensor, dtype=torch.bool) def create_nested_block_mask(tensor): return torch.ones_like(tensor, dtype=torch.bool) def noop_mask(tensor): return torch.ones_like(tensor,...
from solution import masked_tensor_sum import torch def test_masked_tensor_sum(): tensor = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) # Test BLOCK condition: Here, we'll assume all elements are included based on the mock create_block...
[ { "docstring": null, "function_declaration": "def create_block_mask(tensor):", "function_name": "create_block_mask", "parameter_list": "(tensor)" }, { "docstring": null, "function_declaration": "def create_nested_block_mask(tensor):", "function_name": "create_nested_block_mask", ...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.nn.attention.flex_attention import create_block_mask, create_nested_block_mask, and_masks, or_masks, noop_mask\n\ndef masked_tensor_sum(tensor:...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00034393", "row_id": 34393, "seed_ids": "[0]" }
0.503856
Docs: Pytorch_34393
I
[ "create_block_mask", "create_nested_block_mask", "noop_mask", "and_masks", "or_masks", "masked_tensor_sum" ]
6
[ [ "masked_tensor_sum", "and_masks" ], [ "masked_tensor_sum", "create_block_mask" ], [ "masked_tensor_sum", "create_nested_block_mask" ], [ "masked_tensor_sum", "noop_mask" ], [ "masked_tensor_sum", "or_masks" ] ]
5
[]
false
[]
false
pytest
true
[ "torch" ]
false
1f4eb80646a106fdec4b77ca23fd180b39516348
b313bb6613a5aef43cfcfdcfcc3761baffef52c2
v1.0
instruct
Docs
Docs: Scikit_34427_I
**Title**: Implementing and Comparing Feature Extraction Techniques **Objective**: The goal of this assessment is to evaluate your understanding of feature extraction techniques provided by `scikit-learn` and your ability to implement and compare different methods on a text dataset. **Problem Statement**: You are pro...
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, HashingVectorizer def extract_features(reviews, vectorizer_type): if vectorizer_type == "CountVectorizer": vectorizer = CountVectorizer() elif vectorizer_type == "TfidfVectorizer": vectorizer = TfidfVectorizer() e...
import pytest from solution import extract_features, compare_vectorizers reviews = [ "The movie was fantastic! I loved it.", "Quite dull and boring. Not my type.", "An average movie with decent performances.", ] def test_extract_features_countvectorizer(): features, feature_names = extract_features(re...
[ { "docstring": null, "function_declaration": "def extract_features(reviews, vectorizer_type):", "function_name": "extract_features", "parameter_list": "(reviews, vectorizer_type)" }, { "docstring": null, "function_declaration": "def compare_vectorizers(reviews):", "function_name": "c...
[ 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": "from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, HashingVectorizer\n\ndef extract_features(reviews, vectorizer_type):\n if vectorizer_ty...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00034427", "row_id": 34427, "seed_ids": "[40]" }
0.682876
Docs: Scikit_34427
I
[ "extract_features", "compare_vectorizers" ]
2
[ [ "compare_vectorizers", "extract_features" ] ]
1
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
a16da3233cdd4f9ece6d8d45f8ddaadfd7acc8d3
421da94e836855782837dc98cf79dec61c70036a
v1.0
instruct
Docs
Docs: Python310_34436_I
#### Title: Advanced Data Processing with Generators and Comprehensions #### Objective: To assess the student's ability to utilize comprehensions, generators, and asynchronous generators to process and manipulate data efficiently in Python. #### Problem Statement: You are given a large dataset represented as a list o...
import asyncio async def process_data(data): for person in data: if person['age'] > 25 and person['score'] >= 70: yield {'name': person['name'].upper(), 'email': person['email'].lower()} async def fetch_results(data): results = [] async for result in process_data(data): results...
import asyncio from solution import process_data, fetch_results def test_process_data(): data = [ {'name': 'Alice', 'age': 30, 'email': 'Alice@example.com', 'score': 85}, {'name': 'Bob', 'age': 22, 'email': 'Bob@example.com', 'score': 90}, {'name': 'Charlie', 'age': 27, 'email': 'Charlie@ex...
[]
[ 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\n\nasync def process_data(data):\n \"\"\"\n Asynchronous generator that processes the dataset based on given conditions.\n Yields a dictionary w...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00034436", "row_id": 34436, "seed_ids": "[98]" }
0.582355
Docs: Python310_34436
I
[ "process_data", "fetch_results" ]
2
[ [ "fetch_results", "process_data" ] ]
1
[ "process_data" ]
false
[]
false
pytest
true
[]
true
7dd9d6ce7fed8f639b63e8bfc980ef01ec627ee3
ddb8fb9041e62b24f4086046596bd08ac29a9367
v1.0
instruct
Docs
Docs: Pytorch_34471_I
### PyTorch Coding Assessment: Distributed Training with Control Plane #### Objective You are given the task to implement a distributed training process in PyTorch that leverages the control plane module for debug and control handler functionalities. #### Task Create a function `distributed_training` that sets up and...
import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim from torch.multiprocessing import Process def setup(rank, world_size): """ Setup the distributed environment. """ dist.init_process_group( backend='gloo', init_method='tcp://127.0.0.1:29500',...
import pytest from solution import distributed_training def test_distributed_training(): """ Test case to validate the distributed training function runs without errors. """ try: distributed_training(world_size=2, num_epochs=5) except Exception as e: pytest.fail(f"Distributed traini...
[]
[ 0, 1, 0, 0, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom t...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00034471", "row_id": 34471, "seed_ids": "[146]" }
0.566216
Docs: Pytorch_34471
I
[ "setup", "cleanup", "train", "distributed_training" ]
4
[ [ "train", "cleanup" ], [ "train", "setup" ] ]
2
[]
false
[ "SimpleModel" ]
true
pytest
true
[ "torch" ]
false
d1d85851ea72d0e4a1caeb3b767d7e5416f38e2a
865418c2863e94360f054fdba79c9819d3a2722d
v1.0
instruct
Docs
Docs: Python310_34497_I
### Internationalization with `gettext` in Python **Objective:** Develop a Python module that supports multiple languages using the GNU `gettext` and its class-based API. Create application logic that dynamically switches between two languages: English and Spanish. **Problem Statement:** Your task is to create a p...
import gettext from gettext import NullTranslations # Since we cannot create actual .mo files in this environment, we will simulate it with in-memory translations def prepare_translation_files(): """ Simulate the creation of .mo files by using dictionaries to represent translations. """ translations_e...
import io from contextlib import redirect_stdout from solution import prepare_translation_files, load_translations, main_language_program def test_prepare_translation_files(): en, es = prepare_translation_files() assert en == {"Hello World!": "Hello World!", "Welcome to the program.": "Welcome to the program."...
[]
[ 1, 0, 1, 1, 1, 1, 0, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import gettext\n\ndef prepare_translation_files():\n \"\"\"\n Dummy function to simulate creating .mo files.\n \"\"\"\n pass\n\ndef load_translations(langua...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00034497", "row_id": 34497, "seed_ids": "[161]" }
0.492677
Docs: Python310_34497
I
[ "prepare_translation_files", "load_translations", "main_language_program" ]
3
[ [ "load_translations", "prepare_translation_files" ], [ "main_language_program", "load_translations" ] ]
2
[]
false
[]
false
pytest
true
[]
true
afbc3aa1894f0bed32868f128f97036182702638
5c8d00febb83a70affe427d9ae4cbfaf55355f65
v1.0
instruct
Docs
Docs: Python310_34568_I
Password Management System You are required to implement a simple password management system that allows users to register with a hashed password and later verify their login credentials. Your task is to create three functions using the `crypt` module: 1. **`register_user(username: str, password: str) -> dict`**: This...
import crypt import hmac def register_user(username: str, password: str) -> dict: """ Registers a user by hashing the password and storing it in a dictionary. """ salt = generate_salt(crypt.METHOD_SHA512) hashed_password = crypt.crypt(password, salt) return {username: hashed_password} def veri...
import pytest from solution import register_user, verify_user, generate_salt, crypt def test_register_user(): user_db = register_user("john_doe", "securepassword123") assert "john_doe" in user_db assert user_db["john_doe"].startswith("$6$") # SHA-512 identifier def test_verify_user_correct_password(): ...
[ { "docstring": "Registers a user by hashing the password and storing it in a dictionary.", "function_declaration": "def register_user(username, password):", "function_name": "register_user", "parameter_list": "(username, password)" }, { "docstring": "Verifies a user's password against the st...
[ 1, 1, 1, 1, 0, 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 crypt\nimport hmac\n\ndef register_user(username: str, password: str) -> dict:\n \"\"\"Register a user with a hashed password.\"\"\"\n salt = crypt.mksalt(...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00034568", "row_id": 34568, "seed_ids": "[185]" }
0.644142
Docs: Python310_34568
I
[ "register_user", "verify_user", "generate_salt" ]
3
[ [ "register_user", "generate_salt" ] ]
1
[]
false
[]
false
pytest
true
[]
true
aa7ad86201fc8857a8de1521817da7e7168e2c6b
577095157853badf702f985a21b017268adbcc04
v1.0
instruct
Docs
Docs: Python310_34619_I
### Secure File Integrity Checker using HMAC You are required to implement a secure file integrity checker using the `hmac` module in Python. This program should read multiple files, compute their HMACs using a secret key and a specified hash algorithm, and verify if these files have been tampered with by comparing th...
import hmac import hashlib def compute_hmac(filepath, key, digestmod): """ Computes the HMAC of a file. Args: filepath (str): The path to the file. key (bytes): The secret key used for HMAC computation. digestmod (str): The hash algorithm to use (e.g., "sha256"). Returns: ...
import tempfile import os from solution import compute_hmac, check_file_integrity def test_compute_hmac(): key = b'secret_key' digestmod = 'sha256' # Create a temporary file with tempfile.NamedTemporaryFile(delete=False) as temp_file: temp_file.write(b'Hello, this is a test file.') ...
[ { "docstring": "Computes the HMAC of a file.\n\nArgs:\n filepath (str): The path to the file.\n key (bytes): The secret key used for HMAC computation.\n digestmod (str): The hash algorithm to use (e.g., \"sha256\").\n\nReturns:\n str: The computed HMAC as a hexadecimal string.", "function_declar...
[ 0, 1, 0, 0, 0, 1, 0, 1, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hmac\nimport hashlib\n\ndef compute_hmac(filepath, key, digestmod):\n \"\"\"\n Compute the HMAC of a file using a given key and hash algorithm.\n\n Args...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00034619", "row_id": 34619, "seed_ids": "[298]" }
0.691646
Docs: Python310_34619
I
[ "compute_hmac", "check_file_integrity" ]
2
[ [ "check_file_integrity", "compute_hmac" ] ]
1
[]
false
[]
false
pytest
true
[]
true
30ca9eabfb4ac9ca738ab55abf63f90b30d427c7
9333fd2368c1736d3be4acad6133a08509945d8e
v1.0
instruct
Docs
Docs: Python310_34684_I
### Question: Analyzing and Optimizing Code with Python Profiling and Debugging Tools You are given a function `compute_heavy_math` that performs extensive mathematical computations. This function is suspected of being inefficient and potentially having memory leaks. Your task is to use Python's debugging and profilin...
import cProfile import tracemalloc import math from functools import lru_cache from time import time def compute_heavy_math(n): result = [] for i in range(1, n+1): val = math.factorial(i) ** 2 / math.sqrt(i) result.append(val) return result def profile_and_optimize(n): # Profiling the ...
import pytest from solution import compute_heavy_math, profile_and_optimize def test_compute_heavy_math(): results = compute_heavy_math(5) expected = [ math.factorial(1) ** 2 / math.sqrt(1), math.factorial(2) ** 2 / math.sqrt(2), math.factorial(3) ** 2 / math.sqrt(3), math.facto...
[ { "docstring": null, "function_declaration": "def compute_heavy_math(n):", "function_name": "compute_heavy_math", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def profile_and_optimize(n):", "function_name": "profile_and_optimize", "parameter_list": "(n...
[ 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 cProfile\nimport tracemalloc\nimport math\nfrom functools import lru_cache\nimport time\n\n# Original function\ndef compute_heavy_math(n):\n result = []\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00034684", "row_id": 34684, "seed_ids": "[364]" }
0.584615
Docs: Python310_34684
I
[ "compute_heavy_math", "profile_and_optimize" ]
2
[ [ "profile_and_optimize", "compute_heavy_math" ] ]
1
[]
false
[]
false
pytest
true
[]
true
da0ddb3d32425fe4c733dec8f2516656c41edc2d
e3c209f9cdea722655dda065a7034a2b91f8d3d6
v1.0
instruct
Docs
Docs: Python310_34712_I
**Title:** Implementing and Interacting with SystemTap/DTrace Probes in a Python Script **Problem Statement:** You are a developer tasked with analyzing the performance of a Python application using SystemTap or DTrace. The goal is to write a Python script that utilizes static markers to track and log the execution o...
def main(): """Main function to start the program.""" print("Entering main") function_1() function_2() print("Exiting main") def function_1(): """ Function 1 does a task """ print("Entering function_1") # Simulate a task print("Exiting function_1") def function_2(): """ Functio...
def test_main(capsys): main() captured = capsys.readouterr() assert "Entering main" in captured.out assert "Exiting main" in captured.out def test_function_1(capsys): function_1() captured = capsys.readouterr() assert "Entering function_1" in captured.out assert "Exiting function_1" in ...
[ { "docstring": "Main function to start the program.", "function_declaration": "def main():", "function_name": "main", "parameter_list": "()" }, { "docstring": "Function 1 does a task ", "function_declaration": "def function_1():", "function_name": "function_1", "parameter_list": ...
[ 0, 1, 0, 0, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def main():\n \"\"\"Main function to start the program.\"\"\"\n print(\"Main Function Start\")\n function_1()\n function_2()\n print(\"Main Function End\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00034712", "row_id": 34712, "seed_ids": "[79]" }
0.508619
Docs: Python310_34712
I
[ "main", "function_1", "function_2", "function_3" ]
4
[ [ "function_2", "function_3" ] ]
1
[]
false
[]
false
pytest
false
[]
true
b9b625accea106a29fe54833acbe8d07cdec5ba3
96780e006d5bea1b3b9e98a66543c3837f0c99d1
v1.0
instruct
Docs
Docs: Python310_34748_I
#### **Title**: Implementing and Managing Asynchronous Tasks with `asyncio` in Python #### **Objective**: To assess the student's ability to use the `asyncio` library in Python to manage multiple asynchronous tasks, interact with the event loop, and handle task results efficiently. #### **Problem Statement**: You are...
import asyncio import random from typing import List, Dict async def fetch_content(url: str) -> str: """ Simulates fetching content from a URL by introducing a random network delay. """ # Simulate network delay await asyncio.sleep(random.randint(1, 3)) return f"Content of {url}" async def fetc...
import asyncio import pytest from solution import fetch_content, fetch_all_contents @pytest.mark.asyncio async def test_fetch_content(): url = "http://example.com/page1" result = await fetch_content(url) assert result == f"Content of {url}" @pytest.mark.asyncio async def test_fetch_all_contents_success():...
[]
[ 1, 1, 1, 0, 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\nimport random\nfrom typing import List, Dict\n\nasync def fetch_content(url: str) -> str:\n \"\"\"\n Simulates fetching content from a URL by slee...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00034748", "row_id": 34748, "seed_ids": "[101]" }
0.564597
Docs: Python310_34748
I
[ "fetch_content", "fetch_all_contents" ]
2
[ [ "fetch_all_contents", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ff5443f66c10a0f9c904b52d85c809380ee9d9c2
2a40403b0391fa6f5a3bce982d37a159629d6103
v1.0
instruct
Docs
Docs: Pytorch_34752_I
**Title: Solving Linear Systems and Matrix Decompositions with PyTorch** #### Objective: You are required to implement several functions to demonstrate your understanding of PyTorch's linear algebra capabilities, focusing on solving linear systems, and performing matrix decompositions and inverses. #### Problem State...
import torch from typing import Tuple def lu_decomposition(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Perform LU Decomposition of matrix A using simple Doolittle's method. Args: A (torch.Tensor): A square matrix of shape (n, n). Returns: Tuple[torch.Tensor, torch.Tenso...
import torch from solution import lu_decomposition, solve_system_lu, inverse_qr def test_lu_decomposition(): A = torch.tensor([[3.0, 2.0], [1.0, 4.0]]) L, U = lu_decomposition(A) # Reconstruct A from L and U A_reconstructed = torch.matmul(L, U) assert torch.allclose(A, A_reconstructed, atol=1e-4) ...
[ { "docstring": "Perform LU Decomposition of matrix A using simple Doolittle's method.\n\nArgs:\nA (torch.Tensor): A square matrix of shape (n, n).\n\nReturns:\nTuple[torch.Tensor, torch.Tensor]: Lower and Upper triangular matrices L and U.", "function_declaration": "def lu_decomposition(A):", "function_...
[ 0, 0, 0, 0, 0, 1, 0, 1, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import torch\nfrom typing import Tuple\n\ndef lu_decomposition(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Performs...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00034752", "row_id": 34752, "seed_ids": "[75]" }
0.48021
Docs: Pytorch_34752
I
[ "lu_decomposition", "solve_system_lu", "inverse_qr" ]
3
[ [ "solve_system_lu", "lu_decomposition" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
58a3498bb606ad05697bed4f09e4d03f4031f7a1
a8f847aec7c93324c243535e1abfd090bf16e17d
v1.0
instruct
Docs
Docs: Pytorch_34756_I
### Problem: Implementing and Verifying Numerically Stable Linear Algebra Operations with PyTorch In this assignment, you are required to implement functions that perform linear algebra operations using PyTorch and demonstrate the difference in results when using different floating-point precisions (float32, float64, ...
import torch def matmul_and_svd(matrix_a, matrix_b, precision): """ Performs matrix multiplication and SVD decomposition with specified precision. Parameters: - matrix_a: torch.Tensor - matrix_b: torch.Tensor - precision: str Returns: - dict: containing 'product', 'u', 's', 'v...
import torch from solution import matmul_and_svd, compare_precisions def test_matmul_and_svd(): matrix_a = torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtype=torch.float32) matrix_b = torch.tensor([[5.0, 6.0], [7.0, 8.0]], dtype=torch.float32) result = matmul_and_svd(matrix_a, matrix_b, 'float32') # Che...
[ { "docstring": "Performs matrix multiplication and SVD decomposition with specified precision.\n\nParameters:\n- matrix_a: torch.Tensor\n- matrix_b: torch.Tensor\n- precision: str\n\nReturns:\n- dict: containing 'product', 'u', 's', 'v'", "function_declaration": "def matmul_and_svd(matrix_a, matrix_b, preci...
[ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef matmul_and_svd(matrix_a, matrix_b, precision):\n \"\"\"\n Perform matrix multiplication and Singular Value Decomposition (SVD) \n on the re...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00034756", "row_id": 34756, "seed_ids": "[165]" }
0.595705
Docs: Pytorch_34756
I
[ "matmul_and_svd", "compare_precisions" ]
2
[ [ "compare_precisions", "matmul_and_svd" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
f7eb28a141de66e5fb4eaa7a61ef8f7ab4309ff6
338797149db44a731175186f7f547ae7217109de
v1.0
instruct
Docs
Docs: Pytorch_34758_I
### PyTorch MPS Memory Management and Profiling Task #### Objective Implement a PyTorch-based training loop for a simple neural network on an MPS device. The task is designed to assess your understanding of memory management, profiling, and handling random states in the context of Apple's MPS backend in PyTorch. ####...
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.utils.data as data import time def setup_mps_device(seed: int) -> torch.device: """ Sets up the MPS device if available and sets the seed for reproducibility. Args: seed (int): The seed ...
from solution import setup_mps_device, query_memory, empty_cache, train_network import torch import torch.nn as nn import torch.utils.data as data def test_setup_mps_device(): if torch.has_mps: device = setup_mps_device(42) assert device.type == "mps" else: try: setup_mps_de...
[ { "docstring": "Sets up the MPS device if available and sets the seed for reproducibility.\n\nArgs:\n seed (int): The seed for random number generation.\n\nReturns:\n torch.device: The MPS device object.\n\nRaises:\n RuntimeError: If MPS device is not available.", "function_declaration": "def setup...
[ 1, 1, 0, 1, 1, 0, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data\n\ndef setup_mps_device(seed: int) -> torch.device:\n \"\"\"\n Sets ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00034758", "row_id": 34758, "seed_ids": "[60]" }
0.473396
Docs: Pytorch_34758
I
[ "setup_mps_device", "query_memory", "empty_cache", "train_network" ]
4
[ [ "train_network", "empty_cache" ], [ "train_network", "query_memory" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
9a0f3575d7f452b3caac510c04fa37ede407199f
24a2cb320a91f72467e1ac3934440c26ac3ba160
v1.0
instruct
Docs
Docs: Python310_34763_I
## Question: Implementing Advanced Garbage Collection Control and Analysis You are tasked with creating a utility in Python that leverages the `gc` module to provide advanced control over garbage collection and analysis of object memory usage. This utility should expose functionalities to enable/disable garbage collec...
import gc def enable_gc() -> None: """ Enables garbage collection. """ gc.enable() def disable_gc() -> None: """ Disables garbage collection. """ gc.disable() def is_gc_enabled() -> bool: """ Returns True if garbage collection is enabled, otherwise False. """ return gc...
import gc from solution import enable_gc, disable_gc, is_gc_enabled, collect_garbage, get_gc_stats, get_tracked_objects, memory_usage_report def test_enable_disable_gc(): disable_gc() assert not is_gc_enabled() enable_gc() assert is_gc_enabled() def test_collect_garbage(): assert collect_garbage()...
[ { "docstring": "Enables garbage collection.", "function_declaration": "def enable_gc():", "function_name": "enable_gc", "parameter_list": "()" }, { "docstring": "Disables garbage collection.", "function_declaration": "def disable_gc():", "function_name": "disable_gc", "parameter_...
[ 0, 0, 0, 1, 1, 1, 0, 1, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import gc\n\ndef enable_gc() -> None:\n \"\"\"\n Enable the garbage collector.\n \"\"\"\n gc.enable()\n\ndef disable_gc() -> None:\n \"\"\"\n Disable ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00034763", "row_id": 34763, "seed_ids": "[216]" }
0.435605
Docs: Python310_34763
I
[ "enable_gc", "disable_gc", "is_gc_enabled", "collect_garbage", "get_gc_stats", "get_tracked_objects", "memory_usage_report" ]
7
[ [ "memory_usage_report", "collect_garbage" ], [ "memory_usage_report", "get_gc_stats" ], [ "memory_usage_report", "get_tracked_objects" ] ]
3
[]
false
[]
false
pytest
true
[]
true
fdf8c8f69acd69a20a3f16fc1b18c6ae81d33bf6
2fba8d83256ea93825f08948cfca4ac2ed30dfba
v1.0
instruct
Docs
Docs: Python310_34842_I
### Question: Dynamic Class and Type Management in Python In this task, you will leverage the `types` module in Python 3.10 to dynamically create and manage classes and their interactions. #### Task Overview 1. **Dynamic Class Creation**: Create two new classes dynamically: - `Animal`: Base class with a method `sp...
import types def create_animal_classes(): """ Dynamically creates Animal and its subclasses Dog and Cat. Returns the Animal, Dog, and Cat classes. """ # Create the Animal base class dynamically def animal_exec(ns): def speak(self): raise NotImplementedError("Subclasses must ...
def test_create_animal_classes(): Animal, Dog, Cat = create_animal_classes() assert issubclass(Dog, Animal) assert issubclass(Cat, Animal) assert Dog().speak() == "Woof!" assert Cat().speak() == "Meow!" try: Animal().speak() except NotImplementedError: assert T...
[]
[ 1, 1, 0, 1, 0, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import types\n\ndef create_animal_classes():\n # Step 1: Creating the Animal base class dynamically\n def animal_exec(ns):\n def speak(self):\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00034842", "row_id": 34842, "seed_ids": "[372]" }
0.489807
Docs: Python310_34842
I
[ "create_animal_classes", "interact_with_animals" ]
2
[ [ "interact_with_animals", "create_animal_classes" ] ]
1
[]
false
[]
false
pytest
false
[]
true
7b99cd53e88882307fce563f5377e780d41ae0f1
1f13edaa8e77021603d0e0a0dbc3aa508351c141
v1.0
instruct
Docs
Docs: Python310_34866_I
### Advanced Python 3.10 asyncio Programming Assessment In this assessment, you will demonstrate your understanding of the asyncio library and advanced asynchronous programming concepts in Python. Specifically, you will need to implement an asynchronous solution that involves running tasks concurrently, using correct ...
import asyncio import logging import random from concurrent.futures import ThreadPoolExecutor # Setup logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) # Enable debug mode for asyncio asyncio.get_event_loop().set_debug(True) async def io_task(task_id): logger.debug(f"Starting ...
import asyncio import logging from unittest.mock import patch from solution import io_task, cpu_task, process_tasks # Enable logging for unit tests logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) def test_io_task_event_loop(): async def test_coroutine(): with patch('asyncio.s...
[ { "docstring": null, "function_declaration": "def cpu_task(task_id):", "function_name": "cpu_task", "parameter_list": "(task_id)" } ]
[ 0, 0, 0, 1, 1, 1, 1, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport logging\nimport random\nfrom concurrent.futures import ThreadPoolExecutor\n\n# Setup logging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00034866", "row_id": 34866, "seed_ids": "[200]" }
0.526674
Docs: Python310_34866
I
[ "io_task", "cpu_task", "process_tasks" ]
3
[ [ "process_tasks", "cpu_task" ], [ "process_tasks", "io_task" ] ]
2
[]
false
[]
false
pytest
true
[]
true
0237f23944ae4def31c87b06b4ef6c5c41a6ebd0
05952eda7ef280f1c7d08eefe18f03284e3cd93e
v1.0
instruct
Docs
Docs: Python310_34881_I
**Asynchronous Execution with Coroutines** **Objective:** Implement a function that simulates asynchronous tasks using Python's coroutine and asyncio features. This task will assess the understanding of coroutines and the ability to work with asynchronous programming. **Instructions:** 1. Create a coroutine function...
import asyncio import random async def async_fetch_data(identifier): """ Simulates fetching data for a given identifier. """ print(f"Fetching data for id {identifier}") await asyncio.sleep(random.uniform(0.1, 3)) data = {"id": identifier, "data": random.randint(100, 1000)} return data asyn...
import asyncio import pytest from solution import async_fetch_data, async_process_data @pytest.mark.asyncio async def test_async_fetch_data(): """ Tests the async_fetch_data for a given identifier. """ result = await async_fetch_data(1) assert "id" in result assert "data" in result assert r...
[ { "docstring": "Sets up the asyncio event loop to run the async_process_data function with a sample list of identifiers.", "function_declaration": "def main():", "function_name": "main", "parameter_list": "()" } ]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\n\nasync def async_fetch_data(identifier):\n \"\"\"\n Coroutine to fetch data for given identifier.\n Simulates asynchronous I/O ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00034881", "row_id": 34881, "seed_ids": "[8]" }
0.513404
Docs: Python310_34881
I
[ "async_fetch_data", "async_process_data", "main" ]
3
[ [ "async_process_data", "async_fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4aa559616deacaa11191bf78b2ae2a642e4ec043
48704e5d73fce6498e7dd9432a6b9a2cc5093321
v1.0
instruct
Docs
Docs: Python310_34896_I
Design a function that utilizes Python async/await syntax to perform asynchronous computations. The function should fetch data from multiple URLs concurrently, process this data, and return the results. This question will assess your understanding of Python's asynchronous programming facilities and your ability to work...
import asyncio async def fetch_data(url: str) -> dict: """ Simulate an asynchronous network call to fetch data from a URL. Parameters: url (str): The URL to fetch data from. Returns: dict: A dictionary with the URL as the key and the fetched data as the value. """ await asynci...
import asyncio from solution import fetch_data, gather_data async def test_fetch_data(): url = "http://example.com/api/resource1" expected_output = {url: f"data from {url}"} assert await fetch_data(url) == expected_output async def test_gather_data(): urls = [ "http://example.com/api/resource1...
[]
[ 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\n\nasync def fetch_data(url: str) -> dict:\n \"\"\"\n Simulates an asynchronous network call to fetch data from a URL.\n \n Args:\n - url ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00034896", "row_id": 34896, "seed_ids": "[8]" }
0.589651
Docs: Python310_34896
I
[ "fetch_data", "gather_data" ]
2
[ [ "gather_data", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
aa33258db4e4d39be66cc56dbfa6d7045c51006b
d0d75008f28bc7cfe1f0527c20df4a1fd5d73b99
v1.0
instruct
Docs
Docs: Python310_34947_I
### Question **Profiling and Analysis of a Function** You are provided with a function `process_data()` which performs several computations on a dataset. Your task is to profile `process_data()` using the `cProfile` module to gather detailed execution statistics. You need to save the profiling results to a file and t...
import cProfile import pstats from pstats import SortKey # Provided function to profile def process_data(data): result = [] for item in data: processed = compute(item) result.append(processed) return aggregate(result) def compute(item): return item ** 2 # Example computation def aggr...
import os import pstats from solution import process_data, profile_and_analyze def read_analysis_file(): with open("analysis_output.txt", "r") as file: return file.read() def test_profiling_results_file_exists(): profile_and_analyze() assert os.path.exists('profiling_results'), "Profiling results ...
[ { "docstring": null, "function_declaration": "def process_data(data):", "function_name": "process_data", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def compute(item):", "function_name": "compute", "parameter_list": "(item)" }, { "docstring...
[ 0, 1, 0, 0, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cProfile\nimport pstats\nfrom pstats import SortKey\n\n# Provided function to profile\ndef process_data(data):\n result = []\n for item in data:\n p...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00034947", "row_id": 34947, "seed_ids": "[142]" }
0.534988
Docs: Python310_34947
I
[ "process_data", "compute", "aggregate", "profile_and_analyze" ]
4
[ [ "process_data", "aggregate" ], [ "process_data", "compute" ], [ "profile_and_analyze", "process_data" ] ]
3
[ "process_data" ]
false
[]
false
pytest
true
[]
true
46e0ca46b40dfe782239d0736e6d1cacf800aa58
04217316b2319562143bfcd418beb38db919c1d0
v1.0
instruct
Docs
Docs: Python310_34987_I
#### Objective: You are required to implement a cross-platform Python function using the `asyncio` module. The function should demonstrate your understanding of event loops and platform-specific constraints as highlighted in the provided documentation. #### Task: Write a Python function `run_platform_specific_tasks()`...
import asyncio import platform async def run_periodic_task(interval, message): while True: print(message) await asyncio.sleep(interval) def run_platform_specific_tasks(interval, message): # Configure the event loop based on the platform if platform.system() == 'Windows': loop = asy...
import asyncio import pytest import platform from solution import run_platform_specific_tasks @pytest.mark.asyncio async def test_run_platform_specific_tasks(): async def test_task(): run_platform_specific_tasks(1, "Test message") if platform.system() == 'Windows': loop = asyncio.ProactorE...
[ { "docstring": null, "function_declaration": "def run_platform_specific_tasks(interval, message):", "function_name": "run_platform_specific_tasks", "parameter_list": "(interval, message)" } ]
[ 1, 0, 1, 1, 1, 0, 1, 0, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\n\nasync def run_platform_specific_tasks(interval, message):\n \"\"\"\n Runs a simple I/O-bound task that periodically prints a me...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00034987", "row_id": 34987, "seed_ids": "[370]" }
0.566241
Docs: Python310_34987
I
[ "run_periodic_task", "run_platform_specific_tasks" ]
2
[ [ "run_platform_specific_tasks", "run_periodic_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3f495d266b074135fa83134fbf57e82e184baf4d
3cc5e61115ef21f9592bf0d274fc55afd80fd57a
v1.0
instruct
Docs
Docs: Python310_34994_I
### Question: Caching and Functional Programming with `functools` You are given a function `expensive_calculation()` that performs an expensive calculation and a list of numbers. Implement two functions, `cached_factorial()` to compute and cache the factorial of numbers using `functools.cache`, and `sum_of_factorials(...
import functools @functools.cache def cached_factorial(n): """ Computes and caches the factorial of number n using recursion. Parameters: n (int): The number to compute the factorial of. Returns: int: The factorial of n. """ if n == 0: return 1 else: return...
from solution import cached_factorial, sum_of_factorials def test_cached_factorial_base_case(): assert cached_factorial(0) == 1 def test_cached_factorial_small_numbers(): assert cached_factorial(1) == 1 assert cached_factorial(2) == 2 assert cached_factorial(3) == 6 assert cached_factorial(4) == 2...
[ { "docstring": "Computes and caches the factorial of number n using recursion.\n\nParameters:\nn (int): The number to compute the factorial of.\n\nReturns:\nint: The factorial of n.", "function_declaration": "def cached_factorial(n):", "function_name": "cached_factorial", "parameter_list": "(n)" }...
[ 0, 1, 1, 0, 1, 0, 1, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import functools\n\n@functools.cache\ndef cached_factorial(n: int) -> int:\n \"\"\"\n Compute the factorial of a number using recursion and cache the results.\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00034994", "row_id": 34994, "seed_ids": "[236]" }
0.678212
Docs: Python310_34994
I
[ "cached_factorial", "sum_of_factorials" ]
2
[ [ "sum_of_factorials", "cached_factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
21952c5e155dd300782e269e557dd354a3c4382a
c99a41681a553fc34976f5d9d4d9d700a257c9a0
v1.0
instruct
Docs
Docs: Python310_35067_I
### Garbage Collection Management and Analysis #### Problem Statement: You are tasked with writing a Python function that analyzes and reports memory usage patterns using the `gc` module. This function should: 1. **Disable automatic garbage collection** to take full control of memory management. 2. **Register a callb...
import gc def log_collection(phase, info): if phase == "start": print(f"Garbage collection started for generation {info['generation']}") elif phase == "stop": print(f"Garbage collection finished: Collected: {info['collected']}, Uncollectable: {info['uncollectable']}") def analyze_memory_usage(...
def test_analyze_memory_usage(capsys): # Run the analysis analyze_memory_usage() # Capture the printed output captured = capsys.readouterr() # Check if the mandatory output lines are present assert "Garbage collection started" in captured.out assert "Garbage collection finished" in cap...
[ { "docstring": null, "function_declaration": "def log_collection(phase, info):", "function_name": "log_collection", "parameter_list": "(phase, info)" }, { "docstring": null, "function_declaration": "def analyze_memory_usage():", "function_name": "analyze_memory_usage", "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 gc\n\ndef log_collection(phase, info):\n if phase == \"start\":\n print(f\"Garbage collection started for generation {info['generation']}\")\n elif ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00035067", "row_id": 35067, "seed_ids": "[216]" }
0.487559
Docs: Python310_35067
I
[ "log_collection", "analyze_memory_usage" ]
2
[ [ "analyze_memory_usage", "log_collection" ] ]
1
[]
false
[]
false
pytest
false
[]
true
79e60bca3da1dd0b90585e4b91dcdee86d1a9018
d124181f14bd092630d376b19a09f0c4eb465499
v1.0
instruct
Docs
Docs: Pytorch_35167_I
**Objective:** Design a PyTorch program that utilizes the MPS backend for high-performance training on a MacOS device. Your program will create a neural network model, move it to the MPS device, and perform a series of tensor operations exclusively on the GPU. The program should also handle scenarios where the MPS bac...
import torch import torch.nn as nn def check_mps_availability(): if not torch.backends.mps.is_available(): if not torch.backends.mps.is_built(): message = "MPS not available because the current PyTorch install was not built with MPS enabled." else: message = "MPS not availab...
import pytest import torch from solution import check_mps_availability, tensor_operations_on_mps, run_neural_network_on_mps def test_check_mps_availability(): try: device = check_mps_availability() assert str(device) == "mps" except EnvironmentError: assert True # If not available, the...
[]
[ 0, 0, 1, 0, 0, 1, 0, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\n\n# Step 1: Check for MPS Availability and set device\nif not torch.backends.mps.is_available():\n if not torch.backends.mps.is_...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00035167", "row_id": 35167, "seed_ids": "[167]" }
0.437175
Docs: Pytorch_35167
I
[ "check_mps_availability", "tensor_operations_on_mps", "run_neural_network_on_mps" ]
3
[ [ "run_neural_network_on_mps", "check_mps_availability" ], [ "tensor_operations_on_mps", "check_mps_availability" ] ]
2
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
50c15edaf0deed81079b27ce5797515cd7aeea69
1d16ca255091cbd75445980e64a093e53cc6feae
v1.0
instruct
Docs
Docs: Python310_35253_I
**Question**: Implement a TCP server using asyncio's low-level event loop APIs, capable of handling multiple clients concurrently. The server should: - Start listening on a specified host and port. - Accept new client connections. - Read messages from clients and echo back the received messages. - Shutdown gracefully w...
import asyncio import logging async def handle_client(reader, writer): addr = writer.get_extra_info('peername') logging.info(f"Connection from {addr}") while True: data = await reader.read(100) message = data.decode() logging.info(f"Received {message} from {addr}") if mess...
import asyncio import pytest from solution import start_server async def client_task(host, port, messages): reader, writer = await asyncio.open_connection(host, port) responses = [] for msg in messages: writer.write(msg.encode()) await writer.drain() data = await reader.read(100)...
[]
[ 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\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00035253", "row_id": 35253, "seed_ids": "[267]" }
0.594319
Docs: Python310_35253
I
[ "handle_client", "start_server" ]
2
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8b037b3ed426832f692052c0d594f703d47a0bc2
1c10c93ea531d387d62666864b6d781cb4298983
v1.0
instruct
Docs
Docs: Python310_35283_I
### SQLite3 Database Interaction and Custom Python Types **Objective:** Implement a Python function to interact with an SQLite database. This function should perform the following operations: 1. Create a new SQLite database file (`students.db`). 2. Create a table named `students` with three columns: `id` (integer prim...
import sqlite3 import json from typing import List, Tuple def adapt_list(lst): return json.dumps(lst) def convert_list(txt): return json.loads(txt) def manage_student_records(students: List[Tuple[int, str, List[int]]]) -> List[Tuple[int, str, List[int]]]: # Register adapters and converters to handle list...
import sqlite3 import os from solution import manage_student_records # assuming the function resides in solution.py import pytest def test_manage_student_records(): # Test data students = [ (1, "Alice", [85, 90, 88]), (2, "Bob", [78, 82, 85]), (3, "Charlie", [92, 85, 87]) ] ...
[ { "docstring": null, "function_declaration": "def adapt_list(lst):", "function_name": "adapt_list", "parameter_list": "(lst)" }, { "docstring": null, "function_declaration": "def convert_list(txt):", "function_name": "convert_list", "parameter_list": "(txt)" }, { "docstri...
[ 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 sqlite3\nfrom typing import List, Tuple\n\n\ndef adapt_list(lst):\n return ','.join(map(str, lst))\n\n\ndef convert_to_list(scores_str):\n if scores_str:\n...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00035283", "row_id": 35283, "seed_ids": "[140]" }
0.599582
Docs: Python310_35283
I
[ "adapt_list", "convert_list", "manage_student_records" ]
3
[ [ "manage_student_records", "adapt_list" ], [ "manage_student_records", "convert_list" ] ]
2
[]
false
[]
false
pytest
true
[]
true
8c00c94bab6b46ff232c9d34397d8430ba25a329
16ead8148cc8aaa8143ff49762d52eb774b2a217
v1.0
instruct
Docs
Docs: Python310_35350_I
#### Objective: Your task is to implement a function that utilizes `asyncio.Future` objects to concurrently download multiple URLs and gather their responses. The function should handle any exceptions that occur during the downloads and ensure that all results or exceptions are properly collected and returned. #### Fu...
import asyncio import aiohttp from typing import List, Dict, Union async def download(url: str) -> str: async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.text() async def fetch_all(urls: List[str]) -> Dict[str, Union[str, Exception]]:...
import asyncio import pytest from unittest.mock import patch, MagicMock from aiohttp import ClientError from solution import fetch_all @pytest.mark.asyncio async def test_fetch_all_success(): urls = ["http://example.com"] expected_content = "Example Domain" with patch('aiohttp.ClientSession.get') as m...
[]
[ 1, 1, 0, 0, 1, 0, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nfrom typing import List, Dict, Union\n\nasync def download(url: str) -> str:\n async with aiohttp.ClientSession() as session:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00035350", "row_id": 35350, "seed_ids": "[113]" }
0.570263
Docs: Python310_35350
I
[ "download", "fetch_all" ]
2
[ [ "fetch_all", "download" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
610536be27f09a3df1fff457262125a300ff8bee
a473ffcf352d21ba9b1b9f6a640c5ef55b673436
v1.0
instruct
Docs
Docs: Pytorch_35361_I
**Asynchronous Computations with PyTorch Futures** **Objective:** Your task is to implement two functions using the `torch.futures` module to handle asynchronous computations. This will assess your understanding of managing futures and synchronizing their results. **Problem Statement:** 1. **Implement the `compute_...
import torch import torch.futures def compute_async(x: int) -> torch.futures.Future: """ Simulates an asynchronous computation that squares the input number. Args: x (int): The input number to be squared. Returns: torch.futures.Future: A future object that will hold the result of the ...
import pytest from solution import compute_async, aggregate_futures def test_compute_async(): future = compute_async(3) assert future.wait() == 9 def test_aggregate_futures_single(): result = aggregate_futures([3]) assert result == 9 def test_aggregate_futures_multiple(): result = aggregate_futur...
[ { "docstring": "Simulates an asynchronous computation that squares the input number.\n\nArgs:\nx (int): The input number to be squared.\n\nReturns:\ntorch.futures.Future: A future object that will hold the result of the computation.", "function_declaration": "def compute_async(x):", "function_name": "co...
[ 1, 0, 0, 0, 0, 1, 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 torch\nimport torch.futures\n\ndef compute_async(x: int) -> torch.futures.Future:\n \"\"\"\n Simulates an asynchronous computation that squares the input n...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00035361", "row_id": 35361, "seed_ids": "[53]" }
0.502453
Docs: Pytorch_35361
I
[ "compute_async", "aggregate_futures" ]
2
[ [ "aggregate_futures", "compute_async" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
ea2490039a863d1a315554a53d1779392fbb9bcc
a6c4b138c709107de0feceb62973560a3c4f1f12
v1.0
instruct
Docs
Docs: Python310_35371_I
### Python Debugger (pdb) Coding Assessment #### Objective: Demonstrate your understanding and practical skills of using the Python Debugger (`pdb` module) by debugging a given piece of code to analyze its flow, detect, and resolve an issue. #### Problem Statement: You are provided with a faulty Python script. Your t...
def calculate_sum(numbers): """ Returns the sum of the numbers in the input list. """ total = 0 for num in numbers: total += num return total def mean_of_list(number_list): """ Returns the mean of the numbers in the input list. Raises ValueError if the list is empty. """...
from solution import calculate_sum, mean_of_list def test_calculate_sum(): assert calculate_sum([1, 2, 3, 4]) == 10 assert calculate_sum([0]) == 0 assert calculate_sum([-1, -2, -3, -4]) == -10 def test_mean_of_list(): assert mean_of_list([1, 2, 3, 4]) == 2.5 assert mean_of_list([10, 20, 30, 40, 50...
[ { "docstring": "Returns the sum of the numbers in the input list.", "function_declaration": "def calculate_sum(numbers):", "function_name": "calculate_sum", "parameter_list": "(numbers)" }, { "docstring": "Returns the mean of the numbers in the input list.\nRaises ValueError if the list is e...
[ 1, 1, 0, 0, 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": "def calculate_sum(numbers):\n total = 0\n for num in numbers:\n total += num\n return total\n\ndef mean_of_list(number_list):\n if not number_list:\n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00035371", "row_id": 35371, "seed_ids": "[342]" }
0.51665
Docs: Python310_35371
I
[ "calculate_sum", "mean_of_list", "main" ]
3
[ [ "mean_of_list", "calculate_sum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cb4a5236830af7db7848b4c85d3be18f65c0b0d8
0d5f5021e2e95cac5e58fd0955c79a3c8548ad81
v1.0
instruct
Docs
Docs: Python310_35378_I
## Problem Statement: Efficient Prime Factorization Sum ### Objective Write a Python function `prime_factorization_sum(n: int) -> int` that calculates the sum of the greatest common divisors (GCDs) of all unique pairs of the prime factors of a given integer `n`. The function should utilize relevant mathematical funct...
from math import gcd def prime_factors(n): """ Return the prime factors of the given integer n. """ i = 2 factors = set() while i * i <= n: while (n % i) == 0: factors.add(i) n //= i i += 1 if n > 1: factors.add(n) return factors def prim...
import pytest from solution import prime_factorization_sum def test_prime_factorization_sum_basic(): assert prime_factorization_sum(18) == 1 # Prime factors: {2, 3}, GCD(2, 3) = 1 assert prime_factorization_sum(28) == 1 # Prime factors: {2, 7}, GCD(2, 7) = 1 assert prime_factorization_sum(100) == 1 # Pr...
[ { "docstring": "Return the prime factors of the given integer n.", "function_declaration": "def prime_factors(n):", "function_name": "prime_factors", "parameter_list": "(n)" }, { "docstring": "Calculate the sum of the greatest common divisors (GCDs)\nof all unique pairs of the prime factors ...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from math import gcd\n\ndef prime_factors(n):\n factors = []\n # Checking for number of 2s that divide n\n while n % 2 == 0:\n if 2 not in factors:\n ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00035378", "row_id": 35378, "seed_ids": "[274]" }
0.734501
Docs: Python310_35378
I
[ "prime_factors", "prime_factorization_sum" ]
2
[ [ "prime_factorization_sum", "prime_factors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2a264b020444decca47dc16364408f8ef97e8580
a37ecd8d60e89c03a62a69b942c649c035d1cf1a
v1.0
instruct
Docs
Docs: Python310_35379_I
Parallel Web Scraping #### Context: You are tasked with extracting specific data from multiple web pages concurrently. Each page contains items with structured data including `title`, `price`, and `availability`. You will use the `concurrent.futures` module to fetch and parse this data asynchronously to improve perfor...
from typing import List, Dict, Any import concurrent.futures import requests def fetch_data(url: str, timeout: int) -> Dict[str, Any]: try: response = requests.get(url, timeout=timeout) response.raise_for_status() data = response.json() return { "url": url, "...
import pytest from solution import parallel_web_scraping from unittest.mock import patch import requests def mock_fetch_data(url: str, timeout: int): if "timeout" in url: raise requests.exceptions.Timeout() elif "error" in url: raise requests.exceptions.RequestException("General error") el...
[ { "docstring": null, "function_declaration": "def fetch_data(url, timeout):", "function_name": "fetch_data", "parameter_list": "(url, timeout)" }, { "docstring": null, "function_declaration": "def parallel_web_scraping(urls, timeout):", "function_name": "parallel_web_scraping", "...
[ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Dict, Any\nimport concurrent.futures\nimport requests\n\ndef fetch_data(url: str, timeout: int) -> Dict[str, Any]:\n \"\"\"\n Fetches dat...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00035379", "row_id": 35379, "seed_ids": "[347]" }
0.590931
Docs: Python310_35379
I
[ "fetch_data", "parallel_web_scraping" ]
2
[ [ "parallel_web_scraping", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
94205eed805d379c270f963d97c544f6f808b835
1bf103ca37921e694f10ce1d3526757006bc6bc9
v1.0
instruct
Docs
Docs: Seaborn_35415_I
### Question: Customize and Compare Plot Aesthetics using Seaborn You are provided with a dataset and asked to create several plots to illustrate different aesthetic styles and figure contexts using the seaborn package. Your task is to demonstrate your understanding by implementing a function `customize_and_compare_pl...
import numpy as np import seaborn as sns import matplotlib.pyplot as plt def sinplot(n=10, flip=1): x = np.linspace(0, 14, 100) for i in range(1, n + 1): plt.plot(x, np.sin(x + i * .5) * (n + 2 - i) * flip) def customize_and_compare_plots(data: np.ndarray) -> None: # Default plot sns.set_theme...
import os import numpy as np from solution import customize_and_compare_plots def test_customize_and_compare_plots(): data = np.random.rand(10, 3) # Call the function to generate plots customize_and_compare_plots(data) # Check if all the required files are created files = [ "default_plot....
[ { "docstring": null, "function_declaration": "def sinplot(n=10, flip=1):", "function_name": "sinplot", "parameter_list": "(n=10, flip=1)" }, { "docstring": null, "function_declaration": "def customize_and_compare_plots(data):", "function_name": "customize_and_compare_plots", "par...
[ 0, 1, 0, 0, 0, 1, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef sinplot(n=10, flip=1):\n x = np.linspace(0, 14, 100)\n for i in range(1, n + 1):...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00035415", "row_id": 35415, "seed_ids": "[2]" }
0.687249
Docs: Seaborn_35415
I
[ "sinplot", "customize_and_compare_plots" ]
2
[ [ "customize_and_compare_plots", "sinplot" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "seaborn" ]
false
b269fde38c9dc6214e662619979e5dbe85e04f01
406b6051395072c8ea8815c37c194261dc547182
v1.0
instruct
Docs
Docs: Python310_35490_I
#### Objective Demonstrate your understanding of Python 3.10's `asyncio` package by implementing an asynchronous TCP server and client that can communicate with each other. This will test your ability to manage event loops, create tasks, handle async networking, and properly use transports and protocols. #### Requirem...
import asyncio # Function to handle client connections async def handle_client(reader, writer): addr = writer.get_extra_info('peername') print(f"Connected with {addr}") while True: data = await reader.read(100) message = data.decode() if not data: break print(f"...
import pytest import asyncio from solution import handle_client, run_server, run_client @pytest.mark.asyncio async def test_server_client_interaction(): host = '127.0.0.1' port = 8888 # Start the server server_coroutine = run_server(host, port) server_task = asyncio.create_task(server_coroutine) ...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\n# Function to handle client connections\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"Connecte...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00035490", "row_id": 35490, "seed_ids": "[101]" }
0.646063
Docs: Python310_35490
I
[ "handle_client", "run_server", "run_client" ]
3
[ [ "run_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
13f0cfe3c65257af467b5ea63f427136a2e01a15
5480041e5679ee740475157e2fefdcce5682e799
v1.0
instruct
Docs
Docs: Python310_35507_I
#### Objective: Implement a simple text-based user interface using the `curses` module in Python. The interface should allow a user to navigate through a menu, display current date and time, and enable text input. #### Requirements: 1. **Main Menu:** - Create a main menu with three options: 1. Show Date and Ti...
import curses from datetime import datetime def main_menu(stdscr): curses.curs_set(0) options = ["Show Date and Time", "Enter Text", "Exit"] current_option = 0 while True: stdscr.clear() height, width = stdscr.getmaxyx() for idx, option in enumerate(options): x = w...
import curses import pytest from datetime import datetime # As python `curses` module is used for terminal/console UI, # direct unit tests for curses UI might not be viable through standard pytest interface. # However, testing of the logic without dependency on `curses` can be done by creating mocks and simulating th...
[ { "docstring": null, "function_declaration": "def main_menu(stdscr):", "function_name": "main_menu", "parameter_list": "(stdscr)" }, { "docstring": null, "function_declaration": "def show_date_time(stdscr):", "function_name": "show_date_time", "parameter_list": "(stdscr)" }, ...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import curses\nimport time\nfrom datetime import datetime\n\ndef print_menu(stdscr, selected_idx):\n stdscr.clear()\n menu_items = [\"Show Date and Time\", \"Ente...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00035507", "row_id": 35507, "seed_ids": "[74]" }
0.413877
Docs: Python310_35507
I
[ "main_menu", "show_date_time", "enter_text", "main" ]
4
[ [ "main_menu", "enter_text" ], [ "main_menu", "show_date_time" ] ]
2
[]
false
[]
false
pytest
false
[]
true
fd4de7016438ab2459fc04d76b2c5c68b0d5adc5
470e81a9c641f10b5dcd5971c1ca66cc4bad8d7a
v1.0
instruct
Docs
Docs: Pytorch_35519_I
## Problem Statement In this assessment, you are required to implement a flexible attention mechanism using PyTorch's `torch.nn.attention.flex_attention` module. Specifically, your task is to dynamically create and manipulate attention masks using block mask utilities. This will demonstrate your understanding of creat...
import torch # Assuming the following utilities exist and have been correctly imported # from torch.nn.attention.flex_attention import create_mask, and_masks, or_masks # Mock implementations of the `create_mask`, `and_masks`, and `or_masks` functions # as they do not exist in the actual PyTorch library def create_mas...
import torch from solution import generate_attention_masks, apply_attention def test_generate_attention_masks(): tensor_a = torch.tensor([[1.0, 0.0], [3.0, 4.0]]) tensor_b = torch.tensor([[1.0, 2.0], [0.0, 0.0]]) basic_mask, and_mask, or_mask = generate_attention_masks(tensor_a, tensor_b) expected_ba...
[ { "docstring": "Mock function to create a simple mask from the input tensor.\nFor simplicity, we assume the mask is 1 where tensor values are non-zero and 0 otherwise.", "function_declaration": "def create_mask(tensor):", "function_name": "create_mask", "parameter_list": "(tensor)" }, { "doc...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef create_mask(tensor):\n \"\"\" Simple example of creating a mask based on positive values in tensor\"\"\"\n return (tensor > 0).float()\n\ndef ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00035519", "row_id": 35519, "seed_ids": "[0]" }
0.435935
Docs: Pytorch_35519
I
[ "create_mask", "and_masks", "or_masks", "generate_attention_masks", "apply_attention" ]
5
[ [ "generate_attention_masks", "and_masks" ], [ "generate_attention_masks", "create_mask" ], [ "generate_attention_masks", "or_masks" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
9ab86e520a46c8a2e5ce60c97a9be4b30372b70f
05fb654801b19a6e017e537de8d97a30cc08ae85
v1.0
instruct
Docs
Docs: Python310_35556_I
<|Analysis Begin|> The provided documentation for the `asyncio` queues module outlines the functionality and usage of FIFO Queue, PriorityQueue, and LifoQueue for asynchronous programming in Python. The `asyncio.Queue` class is designed for tasks that require queueing operations and synchronization amongst concurrent ...
import asyncio from typing import List from time import time async def worker(queue: asyncio.Queue): while True: task = await queue.get() if task is None: break await asyncio.sleep(task) queue.task_done() async def process_tasks(task_list: List[float], worker_count: int...
import pytest import asyncio from time import time from solution import process_tasks def test_process_tasks_single_worker(): tasks = [1.5, 2.0, 0.5, 3.0] workers = 1 expected_min_time = sum(tasks) total_time = asyncio.run(process_tasks(tasks, workers)) assert total_time >= expected_min_time def t...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List\nfrom time import time\n\nasync def worker(queue: asyncio.Queue):\n while True:\n task = await queue.get()\n if...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00035556", "row_id": 35556, "seed_ids": "[111]" }
0.552739
Docs: Python310_35556
I
[ "worker", "process_tasks" ]
2
[ [ "process_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bd16e94f79eba4c6e5c98e7259ea8f26f86e9a30
d35345d155a30fd4426b6672e45a1f65244ad54b
v1.0
instruct
Docs
Docs: Python310_35559_I
#### Objective: Demonstrate proficiency in debugging, profiling, and tracing Python code using the provided tools and modules. #### Task: You are provided with a piece of Python code that has multiple functions performing various tasks. Some functions might be bottlenecks due to inefficient code, and others might have...
import time import random import cProfile import timeit import tracemalloc import trace def optimized_inefficient_function(): """ Optimized version of inefficient_function. Uses generator instead of list comprehension to save memory and improve speed. """ result = sum(i for i in range(10000)) ...
from solution import optimized_inefficient_function, optimized_memory_intensive_function def test_optimized_inefficient_function_runtime(): import timeit result = timeit.timeit('optimized_inefficient_function()', globals=globals(), number=10) assert result < 1.0, f"Function took too long: {result} seconds"...
[ { "docstring": "Optimized version of inefficient_function. \nUses generator instead of list comprehension to save memory and improve speed.", "function_declaration": "def optimized_inefficient_function():", "function_name": "optimized_inefficient_function", "parameter_list": "()" }, { "docst...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cProfile\nimport timeit\nimport trace\nimport tracemalloc\nimport random\n\ndef inefficient_function():\n result = sum(range(10000))\n return result\n\ndef...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00035559", "row_id": 35559, "seed_ids": "[364]" }
0.514464
Docs: Python310_35559
I
[ "optimized_inefficient_function", "optimized_memory_intensive_function", "profile_functions", "measure_optimization", "memory_allocation_analysis", "display_top", "main" ]
7
[ [ "memory_allocation_analysis", "display_top" ], [ "memory_allocation_analysis", "optimized_memory_intensive_function" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f7076e0a38db51ac3c95277c813bff7b484958e8
d580a2fa1e6658ea896bb2158f03de8a08c620aa
v1.0
instruct
Docs
Docs: Python310_35564_I
**Objective:** Assess the student's understanding and ability to utilize the `concurrent.futures` module to manage parallel execution of tasks. **Problem Statement:** You are tasked with processing a list of URLs to fetch their contents concurrently. Each URL must be fetched and its content length should be printed. ...
from typing import List import requests from concurrent.futures import ThreadPoolExecutor, as_completed def fetch_content_length(url: str) -> str: """ Fetch the content of the URL and return the URL with its content length. Returns a string "URL: length" or "URL: Error occurred". """ try: r...
from solution import fetch_urls_concurrently, fetch_content_length import requests import pytest from unittest.mock import patch def test_fetch_content_length_success(): url = "http://example.com" # Mock requests.get to return a response with content with patch("requests.get") as mock_get: mo...
[ { "docstring": "Fetch the content of the URL and return the URL with its content length.\nReturns a string \"URL: length\" or \"URL: Error occurred\".", "function_declaration": "def fetch_content_length(url):", "function_name": "fetch_content_length", "parameter_list": "(url)" }, { "docstrin...
[ 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 concurrent.futures\nimport requests\nfrom typing import List\n\ndef fetch_url(url: str) -> str:\n try:\n response = requests.get(url)\n response...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00035564", "row_id": 35564, "seed_ids": "[224]" }
0.494305
Docs: Python310_35564
I
[ "fetch_content_length", "fetch_urls_concurrently" ]
2
[ [ "fetch_urls_concurrently", "fetch_content_length" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
4dbd0575d576e5c76ff377bedb4b18c2c43011a6
602868795084c1103d2d1b7c30bf8b46844e22bd
v1.0
instruct
Docs
Docs: Python310_35573_I
#### Objective Demonstrate your understanding and practical usage of the `contextlib` module from Python's standard library. Specifically, focus on creating custom context managers and using `ExitStack` to manage multiple resources. #### Problem Statement You are tasked with writing a custom context manager and using...
import os from contextlib import contextmanager, ExitStack import logging # Setup a logger logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.ad...
import os import pytest from solution import process_files, logger def test_process_files_all_success(tmpdir): file_paths = [os.path.join(tmpdir, f"file{i}.txt") for i in range(3)] data = "Hello, World!" process_files(file_paths, data, logger) for file_path in file_paths: with open(file_path, ...
[ { "docstring": "A custom context manager to handle file operations.", "function_declaration": "def FileManager(file_path, mode, logger):", "function_name": "FileManager", "parameter_list": "(file_path, mode, logger)" }, { "docstring": "Opens multiple files and writes data to them using ExitS...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nfrom contextlib import contextmanager, ExitStack\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n@context...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00035573", "row_id": 35573, "seed_ids": "[177]" }
0.480607
Docs: Python310_35573
I
[ "FileManager", "process_files" ]
2
[ [ "process_files", "FileManager" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0a625a134054b06fe8668615bc1a34916f93f7f3
75c0aa2081616a4a9232acfe0395914fc2289395
v1.0
instruct
Docs
Docs: Python310_35595_I
**Python Coding Assessment Question** **Objective:** Implement a function that launches multiple tasks in parallel to process a list of URLs concurrently, fetch their content, and return the results. Handle potential exceptions gracefully and ensure optimal performance. **Problem Statement:** You are provided a list...
from typing import List, Tuple, Union import concurrent.futures import requests def fetch_url(url: str) -> Tuple[str, Union[str, None]]: try: response = requests.get(url, timeout=5) response.raise_for_status() # Check if the request was successful return (url, response.text) except req...
import pytest from solution import fetch_urls_concurrently def mock_requests_get(url, timeout): if url == "https://example.com": class MockResponse: def raise_for_status(self): pass @property def text(self): return "Example Do...
[ { "docstring": null, "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def fetch_urls_concurrently(urls):", "function_name": "fetch_urls_concurrently", "parameter_list": "(urls)"...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple, Union\nimport concurrent.futures\nimport requests\n\ndef fetch_url(url: str) -> Tuple[str, Union[str, None]]:\n try:\n respons...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00035595", "row_id": 35595, "seed_ids": "[224]" }
0.623938
Docs: Python310_35595
I
[ "fetch_url", "fetch_urls_concurrently" ]
2
[ [ "fetch_urls_concurrently", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
089693e09a36f88aeb1a9fa0af2ac7a2713988f4
e8b09d2bc69b277857c065c32d9589a878f0defc
v1.0
instruct
Docs
Docs: Python310_35599_I
#### Asynchronous File Processing **Objective:** Implement a function that processes a list of file paths in parallel to count the frequency of a specific word in each file. The function should use the `concurrent.futures` module to achieve parallelism, ensuring efficient processing. **Function Signature:** ```pyt...
import concurrent.futures from typing import List, Dict def count_word_in_file(word: str, file_path: str) -> int: """ Helper function to count occurrences of a word in a single file. """ try: with open(file_path, 'r') as file: content = file.read() return content.lower()...
import pytest from solution import count_word_in_files def test_count_word_in_files_single_file(): with open('test1.txt', 'w') as f: f.write("example test example") assert count_word_in_files("example", ["test1.txt"]) == {"test1.txt": 2} def test_count_word_in_files_multiple_files(): with open...
[ { "docstring": "Helper function to count occurrences of a word in a single file.", "function_declaration": "def count_word_in_file(word, file_path):", "function_name": "count_word_in_file", "parameter_list": "(word, file_path)" }, { "docstring": "Count the occurrences of a word in a list of ...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import concurrent.futures\nfrom typing import List, Dict\n\ndef count_word_in_file(word: str, file_path: str) -> int:\n \"\"\"\n Helper function to count occurren...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00035599", "row_id": 35599, "seed_ids": "[224]" }
0.675038
Docs: Python310_35599
I
[ "count_word_in_file", "count_word_in_files" ]
2
[ [ "count_word_in_files", "count_word_in_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e55125736670f77ec6272826cbe858c3e5543c04
d18eea22c8679374ca7e372627b3e8d0eede6977
v1.0
instruct
Docs
Docs: Python310_35630_I
<|Analysis Begin|> The provided documentation is an extensive and detailed description of the `argparse` module, which is a Python library used for creating command-line interfaces. It includes explanations and examples of various functions and methods such as creating a parser, adding arguments, parsing arguments, ha...
import argparse import sys from functools import reduce import operator def arithmetic_tool(): parser = argparse.ArgumentParser( description='Command-Line Arithmetic Tool. Perform basic arithmetic operations on a list of numbers from either command-line or a file.' ) parser.add_argument( ...
from solution import calculate_sum, calculate_prod, calculate_max, calculate_min def test_calculate_sum(): assert calculate_sum([1, 2, 3, 4]) == 10 assert calculate_sum([0, 0, 0, 0]) == 0 assert calculate_sum([-1, -2, -3, -4]) == -10 assert calculate_sum([1, -1, 1, -1]) == 0 def test_calculate_prod():...
[ { "docstring": null, "function_declaration": "def arithmetic_tool():", "function_name": "arithmetic_tool", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def calculate_sum(numbers):", "function_name": "calculate_sum", "parameter_list": "(numbers)" }, ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import argparse\nimport sys\nfrom functools import reduce\nimport operator\n\ndef arithmetic_tool():\n parser = argparse.ArgumentParser(\n description='Comman...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00035630", "row_id": 35630, "seed_ids": "[139]" }
0.519934
Docs: Python310_35630
I
[ "arithmetic_tool", "calculate_sum", "calculate_prod", "calculate_max", "calculate_min" ]
5
[ [ "arithmetic_tool", "calculate_max" ], [ "arithmetic_tool", "calculate_min" ], [ "arithmetic_tool", "calculate_prod" ], [ "arithmetic_tool", "calculate_sum" ] ]
4
[]
false
[]
false
pytest
true
[]
true
d6f73accd1caa3722f8e8969b6193bc8258fdd22
09612148838db5dfb3b2ff955fa66a9ac856d544
v1.0
instruct
Docs
Docs: Python310_35698_I
**Objective:** Demonstrate understanding and practical usage of the `plistlib` module for reading, writing, and manipulating property list files in both XML and binary formats. #### Problem Statement You are tasked with writing functions to process property list files used by Apple. Write a set of functions to accomp...
import plistlib def load_plist(file_path, fmt=None): """ Read a property list file from a given file path and return the content as a dictionary. :param file_path: Path to the plist file to read. :param fmt: Format of the plist file. Default is None (autodetect format). :return: Dictionary contain...
import os import plistlib import datetime from solution import load_plist, save_plist, convert_plist def test_load_plist(): data = { "name": "John Doe", "age": 30, "is_student": False, "exam_results": { "math": 95, "science": 88 }, "graduatio...
[ { "docstring": "Read a property list file from a given file path and return the content as a dictionary.\n\n:param file_path: Path to the plist file to read.\n:param fmt: Format of the plist file. Default is None (autodetect format).\n:return: Dictionary containing the content of the plist file.", "function...
[ 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 plistlib\n\ndef load_plist(file_path, fmt=None):\n \"\"\"\n Read a property list file from a given file path and return the content as a dictionary.\n\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00035698", "row_id": 35698, "seed_ids": "[349]" }
0.355208
Docs: Python310_35698
I
[ "load_plist", "save_plist", "convert_plist" ]
3
[ [ "convert_plist", "load_plist" ], [ "convert_plist", "save_plist" ] ]
2
[]
false
[]
false
pytest
true
[]
true
db2f00795c048073c27b068ea339f30e2a362d3f
5424488e4cccff7036b615bacdb6151f0d638896
v1.0
instruct
Docs
Docs: Python310_35743_I
### Question: #### Background: You are developing a task scheduling system using the `asyncio` module in Python 3.10. You need to perform multiple asynchronous computations where results depend on each other in a complex manner. To achieve this, you need to effectively utilize `asyncio.Future` objects for handling asy...
import asyncio from typing import List, Tuple async def _complete_future(future: asyncio.Future, delay: int, value: int): """ Helper function to simulate a delay and set the value for a Future object. """ await asyncio.sleep(delay) future.set_result(value) async def schedule_tasks(tasks: List[Tupl...
import asyncio from solution import schedule_tasks async def test_schedule_tasks_single_task(): tasks = [(1, 42)] result = await schedule_tasks(tasks) assert result == [42] async def test_schedule_tasks_multiple_tasks(): tasks = [(1, 10), (2, 20), (3, 30)] result = await schedule_tasks(tasks) ...
[]
[ 1, 0, 1, 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\nfrom typing import List, Tuple\n\nasync def set_future_value(future: asyncio.Future, delay: int, value: int):\n await asyncio.sleep(delay)\n futur...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00035743", "row_id": 35743, "seed_ids": "[113]" }
0.63291
Docs: Python310_35743
I
[ "_complete_future", "schedule_tasks" ]
2
[ [ "schedule_tasks", "_complete_future" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7bea49fe17a8b7e7cdce609199ea9e70a3dc159f
cf942a511515a0a2cbf802c06c676da1c0d7103e
v1.0
instruct
Docs
Docs: Python310_35799_I
**Python Coding Assessment: Implementing Command-Line History and Custom Auto-Completion** ### Objective: You are to implement a Python script that utilizes the `readline` module to achieve the following: 1. Manage the command-line history. 2. Implement a custom auto-completion function. ### Requirements: 1. **Histor...
import os import readline import atexit # User-defined list of words for auto-completion completion_words = ["apple", "banana", "grape", "orange", "watermelon"] def setup_history(): """ Sets up the command-line history management. Loads the history from the .my_python_history file and ensures the history ...
import os import readline import pytest from solution import setup_history, setup_completion, completer def test_setup_history(monkeypatch): histfile = os.path.join(os.path.expanduser("~"), ".my_python_history") if os.path.exists(histfile): os.remove(histfile) setup_history() readline.add_...
[ { "docstring": "Sets up the command-line history management.\nLoads the history from the .my_python_history file and ensures the history is saved on exit.", "function_declaration": "def setup_history():", "function_name": "setup_history", "parameter_list": "()" }, { "docstring": "Custom comp...
[ 0, 0, 0, 1, 1, 1, 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 readline\nimport os\nimport atexit\n\nHISTORY_FILE = os.path.join(os.path.expanduser(\"~\"), \".my_python_history\")\nCOMPLETION_LIST = [\"apple\", \"banana\", \...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00035799", "row_id": 35799, "seed_ids": "[362]" }
0.433492
Docs: Python310_35799
I
[ "setup_history", "completer", "setup_completion" ]
3
[ [ "setup_completion", "completer" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7036b8cd18fdf4e051763b5a41decf39b5c01b07
150e46ab9c799c8ffe9f4bce6f48d6098dc1e208
v1.0
instruct
Docs
Docs: Python310_35847_I
You are required to implement a non-blocking, multithreaded chat server using Python sockets. This server should handle multiple clients simultaneously, allowing them to send messages to the server, which will then broadcast the message to all other connected clients. Each client should receive messages from other clie...
import socket import threading from select import select # Dictionary to keep track of client sockets and addresses clients = {} # Broadcasts a message to all clients except the sender def broadcast(message, sender_socket): for client_socket in clients: if client_socket != sender_socket: try: ...
import socket import threading import time # Start the server in a separate thread to test it def start_test_server(): server_thread = threading.Thread(target=lambda: start_server(12345), daemon=True) server_thread.start() time.sleep(1) # Allow server to start up return server_thread # Connects to th...
[ { "docstring": null, "function_declaration": "def broadcast(message, sender_socket):", "function_name": "broadcast", "parameter_list": "(message, sender_socket)" }, { "docstring": null, "function_declaration": "def handle_client(client_socket, client_address):", "function_name": "han...
[ 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": "import socket\nimport threading\nimport select\nimport sys\n\n# List to keep track of connected client sockets\nclients = []\n\ndef broadcast(message, source_socket):\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00035847", "row_id": 35847, "seed_ids": "[63]" }
0.62097
Docs: Python310_35847
I
[ "broadcast", "handle_client", "start_server" ]
3
[ [ "handle_client", "broadcast" ] ]
1
[]
false
[]
false
pytest
false
[]
true
77bfa9651693df9caf03a2492d85dde6e5beefbf
5759a49522de7775ba20a6e840c6dbe09c6a4391
v1.0
instruct
Docs
Docs: Python310_35914_I
### Optimizing a Web Scraping Tool with `functools` **Problem Statement:** You are required to implement a web scraping tool that fetches the content of several web pages. However, to optimize performance and avoid repeated fetches of the same web pages, you should utilize the caching features provided by the `functo...
from functools import lru_cache from typing import List, Dict @lru_cache(maxsize=32) def fetch_content(url: str) -> str: """ Fetch the content of the web page at the given URL. Uses caching to avoid repeated fetches of the same URL. :param url: URL of the web page to fetch. :return: Content of...
from solution import fetch_content, fetch_multiple_contents def test_fetch_content(): assert fetch_content('https://example.com/page_a') == 'Content of page A' assert fetch_content('https://example.com/page_b') == 'Content of page B' assert fetch_content('https://example.com/unknown_page') == 'Content of o...
[ { "docstring": "Fetch the content of the web page at the given URL.\nUses caching to avoid repeated fetches of the same URL.\n\n:param url: URL of the web page to fetch.\n:return: Content of the web page.", "function_declaration": "def fetch_content(url):", "function_name": "fetch_content", "paramet...
[ 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": "from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef fetch_content(url: str) -> str:\n \"\"\"\n Fetches the content of the web page at the given URL.\...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00035914", "row_id": 35914, "seed_ids": "[236]" }
0.634932
Docs: Python310_35914
I
[ "fetch_content", "fetch_multiple_contents" ]
2
[ [ "fetch_multiple_contents", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cff2e0893a7b11061ace61916e30a1d9467d591a
c29413fc246b9adb8b47c9268554c000bf7c5b2a
v1.0
instruct
Docs
Docs: Python310_36029_I
### Advanced Coding Assessment: Geometric and Statistical Computations #### Objective: You will implement a function that computes several geometric and statistical properties of a given dataset. #### Problem Statement: Given a list of tuples representing points in a 2D plane, implement a function `analyze_points(poi...
import math def euclidean_distance(p1, p2): return math.dist(p1, p2) def analyze_points(points): if len(points) < 2: raise ValueError("At least two points are required to compute distances.") # Compute distances n = len(points) distances = [[0.0] * n for _ in range(n)] min_distance = ...
from solution import analyze_points import math def test_analyze_points_basic(): points = [(0, 0), (3, 4)] result = analyze_points(points) assert result['closest_pair'] == ((0, 0), (3, 4)) assert result['centroid'] == (1.5, 2.0) expected_distance = math.dist(points[0], points[1]) assert math.is...
[ { "docstring": null, "function_declaration": "def euclidean_distance(p1, p2):", "function_name": "euclidean_distance", "parameter_list": "(p1, p2)" }, { "docstring": null, "function_declaration": "def analyze_points(points):", "function_name": "analyze_points", "parameter_list": ...
[ 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 math\nimport itertools\n\ndef analyze_points(points):\n def euclidean_distance(p1, p2):\n return math.dist(p1, p2)\n \n # Compute distances\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00036029", "row_id": 36029, "seed_ids": "[274]" }
0.677402
Docs: Python310_36029
I
[ "euclidean_distance", "analyze_points" ]
2
[ [ "analyze_points", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dac7d9b89fb5ef8eb3fdf4f730ffa880f7a14854
0a2ce7dc99212816c2b4403c0acf7cd7cea2194f
v1.0
instruct
Docs
Docs: Python310_36035_I
### Advanced Coding Challenge #### Background In Python, coroutines are functions that use the `async` keyword. When called, these functions return a coroutine object. Coroutines are primarily used to run asynchronous code, allowing for non-blocking operations. Handling coroutines effectively requires understanding h...
import asyncio import inspect def is_coroutine(func): """ Checks if the given function is a coroutine. :param func: Function to be checked :return: True if the function is a coroutine, False otherwise """ return inspect.iscoroutinefunction(func) async def simple_coroutine(num, value): ...
from solution import is_coroutine, run_coroutine def test_is_coroutine(): async def sample_coroutine(): await asyncio.sleep(1) def normal_function(): return "I'm just a regular function" assert is_coroutine(sample_coroutine) == True assert is_coroutine(normal_function) == Fals...
[ { "docstring": "Checks if the given function is a coroutine.\n\n:param func: Function to be checked\n:return: True if the function is a coroutine, False otherwise", "function_declaration": "def is_coroutine(func):", "function_name": "is_coroutine", "parameter_list": "(func)" }, { "docstring"...
[ 1, 1, 1, 1, 1, 0, 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 inspect\n\ndef is_coroutine(func):\n \"\"\"\n Check if a given function is a coroutine function.\n \n Parameters: \n - func: a Pyt...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00036035", "row_id": 36035, "seed_ids": "[8]" }
0.562297
Docs: Python310_36035
I
[ "is_coroutine", "simple_coroutine", "run_coroutine" ]
3
[ [ "run_coroutine", "simple_coroutine" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4ee872d5081af76fa6c37e7fa163cedb0d399dd6
e81f17af781941259a2f74ea79455ee40347becb
v1.0
instruct
Docs
Docs: Python310_36086_I
#### Objective: Demonstrate your understanding of asyncio synchronization primitives by solving a problem that coordinates multiple tasks using `Lock`, `Event`, and `Semaphore`. #### Problem Statement: You are required to implement a task orchestrator that schedules the execution of multiple tasks with specific constr...
import asyncio async def task(worker_id, duration, start_event, semaphore, lock, result): await start_event.wait() # Wait until the orchestrator allows to start async with semaphore: # Ensure no more than 3 concurrent tasks await asyncio.sleep(duration) # Simulate work async with lock: # En...
import asyncio from solution import task_manager def test_task_manager(): task_times = [2, 3, 1, 4, 2] expected_results = {'Task 0 finished', 'Task 1 finished', 'Task 2 finished', 'Task 3 finished', 'Task 4 finished'} result = asyncio.run(task_manager(task_times)) assert set(result) == expected_r...
[]
[ 1, 1, 1, 1, 1, 0, 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\n\nasync def task_manager(task_times):\n lock = asyncio.Lock()\n event = asyncio.Event()\n semaphore = asyncio.Semaphore(3)\n result = []\n\n...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00036086", "row_id": 36086, "seed_ids": "[247]" }
0.539249
Docs: Python310_36086
I
[ "task", "task_manager" ]
2
[ [ "task_manager", "task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ef637dc101f4726748df2c00a102863c8fa8a7e5
cc9549008f44b6d845a7533c7e67ebca664f9176
v1.0
instruct
Docs
Docs: Python310_36091_I
### Python Socket Programming Assessment #### Objective: You are tasked with writing a Python program that demonstrates your understanding of socket programming, including both blocking and non-blocking sockets, as well as handling multiple client connections concurrently. #### Problem Statement: Write a Python progr...
import socket import select def chat_server(): """ Chat server using non-blocking sockets and select for handling multiple clients. """ server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(("0.0....
import socket import threading from time import sleep # the server should be run in a separate thread to be able to test the client def run_server(): import chat_server chat_server.chat_server() def run_client(message): client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.c...
[ { "docstring": "Chat server using non-blocking sockets and select for handling multiple clients.", "function_declaration": "def chat_server():", "function_name": "chat_server", "parameter_list": "()" }, { "docstring": "Broadcast a message to all clients\n:param sender_socket: The socket that...
[ 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 socket\nimport select\n\ndef chat_server():\n \"\"\"\n Chat server using non-blocking sockets and select for handling multiple clients.\n \"\"\"\n se...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00036091", "row_id": 36091, "seed_ids": "[63]" }
0.700636
Docs: Python310_36091
I
[ "chat_server", "broadcast_message", "disconnect_socket" ]
3
[ [ "chat_server", "broadcast_message" ], [ "chat_server", "disconnect_socket" ] ]
2
[]
false
[]
false
pytest
false
[ "chat_server" ]
false
9a569d61f253e532f53725fe4816a50794c8d296
3b4903910f1169573917be86bdd0ad33e0fb8bd1
v1.0
instruct
Docs
Docs: Python310_36118_I
### Asynchronous Web Scraping and Prime Number Calculation #### Problem Description You are tasked with creating two functions that demonstrate the use of concurrency features in the `concurrent.futures` module: one for web scraping and one for prime number calculation. #### Part 1: Web Scraping Write a function `as...
import urllib.request from typing import List, Tuple, Optional from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor def asynchronous_web_scraper(urls: List[str]) -> List[Tuple[str, Optional[bytes]]]: def fetch(url: str) -> Tuple[str, Optional[bytes]]: try: with urllib.request....
import pytest from unittest.mock import patch from solution import asynchronous_web_scraper, asynchronous_prime_calculator def test_asynchronous_web_scraper_success(): urls = ['http://example.com', 'http://example.org'] contents = [b"<html>Example.com</html>", b"<html>Example.org</html>"] def mock_urlopen...
[ { "docstring": null, "function_declaration": "def asynchronous_web_scraper(urls):", "function_name": "asynchronous_web_scraper", "parameter_list": "(urls)" }, { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }...
[ 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": "from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed\nfrom urllib.request import urlopen\nfrom typing import List, Tuple, Optional\n\nde...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00036118", "row_id": 36118, "seed_ids": "[347]" }
0.518961
Docs: Python310_36118
I
[ "asynchronous_web_scraper", "is_prime", "asynchronous_prime_calculator" ]
3
[ [ "asynchronous_prime_calculator", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a0dc12c6c751d0c553bfb346ac814a4abe952aa5
6e8533b335d0097b6a071d1861f6787747e17ff4
v1.0
instruct
Docs
Docs: Python310_36154_I
**Objective**: Implement a secure message signing and verification system using the HMAC algorithm described in the provided documentation. ### Problem Statement You are required to create two functions: `sign_message` and `verify_message` to sign messages using a secret key and verify them. #### Function 1: `sign_m...
import hmac import hashlib def sign_message(key: bytes, message: str, digestmod: str) -> str: """ Sign the message with the given key using the specified digest module. """ if not key or not isinstance(key, (bytes, bytearray)): raise ValueError("Key must be a non-empty bytes or bytearray object...
from solution import sign_message, verify_message import pytest def test_sign_message_valid(): key = b'secret_key' message = 'This is a test message' digestmod = 'sha256' signed_message = sign_message(key, message, digestmod) assert isinstance(signed_message, str) assert len(signed_message) == ...
[ { "docstring": "Sign the message with the given key using the specified digest module.", "function_declaration": "def sign_message(key, message, digestmod):", "function_name": "sign_message", "parameter_list": "(key, message, digestmod)" }, { "docstring": "Verify the message with the provide...
[ 1, 1, 1, 0, 1, 0, 1, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hmac\nimport hashlib\n\ndef sign_message(key: bytes, message: str, digestmod: str) -> str:\n \"\"\"\n Sign the message with the provided key using HMAC and...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00036154", "row_id": 36154, "seed_ids": "[298]" }
0.846575
Docs: Python310_36154
I
[ "sign_message", "verify_message" ]
2
[ [ "verify_message", "sign_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4bc4062beb4a805f23638f4967f61931ba1a5bd7
e91d675c4cff4c4c43d2baba734e5e22f85f0faf
v1.0
instruct
Docs
Docs: Python310_36178_I
### Question: Parallel Matrix Multiplication In this task, you are required to implement a function for matrix multiplication using the "multiprocessing" module. The function should leverage multiple processes to parallelize the computation and improve performance. ### Function Specification - **Function Name:** `pa...
from multiprocessing import Pool def matrix_multiply_worker(args): i, j, matrix_a, matrix_b = args return sum(matrix_a[i][k] * matrix_b[k][j] for k in range(len(matrix_b))) def parallel_matrix_multiplication(matrix_a, matrix_b): # Get dimensions of input matrices m = len(matrix_a) # Number of rows...
from solution import parallel_matrix_multiplication def test_parallel_matrix_multiplication_basic(): matrix_a = [ [1, 2], [3, 4] ] matrix_b = [ [5, 6], [7, 8] ] result = parallel_matrix_multiplication(matrix_a, matrix_b) expected = [ [19, 22], [43...
[ { "docstring": null, "function_declaration": "def matrix_multiply_worker(args):", "function_name": "matrix_multiply_worker", "parameter_list": "(args)" }, { "docstring": null, "function_declaration": "def parallel_matrix_multiplication(matrix_a, matrix_b):", "function_name": "paralle...
[ 1, 1, 0, 1, 1, 1, 1, 0, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import multiprocessing as mp\n\ndef multiply_row_by_matrix(row, matrix_b):\n result_row = []\n num_columns_b = len(matrix_b[0])\n for j in range(num_columns_b)...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00036178", "row_id": 36178, "seed_ids": "[338]" }
0.54506
Docs: Python310_36178
I
[ "matrix_multiply_worker", "parallel_matrix_multiplication" ]
2
[ [ "parallel_matrix_multiplication", "matrix_multiply_worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
28cda8d12355ab6535311e450ca5575c1f6fe71f
f510cf006567be029500ec8a752c3a1d2ce649ba
v1.0
instruct
Docs
Docs: Python310_36233_I
### Custom Exception Handling and Propagation In this coding assignment, you need to create a Python module that simulates a simplified file processing system. This system should be able to read from a 'file', process the input data, and handle various types of potential errors using Python's exception handling mechan...
class CustomFileError(Exception): """Custom exception class for file-related errors.""" def __init__(self, message): super().__init__(message) def read_file(file_content: str) -> str: """ Simulates reading from a file. Args: - file_content (str): The simulated content of the file. R...
from solution import CustomFileError, read_file, process_data, main_function def test_read_file_non_empty_content(): content = "This is some content" assert read_file(content) == content def test_read_file_empty_content(): try: read_file("") except CustomFileError as error: assert str(...
[]
[ 1, 0, 0, 0, 0, 1, 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": "class CustomFileError(Exception):\n pass\n\ndef read_file(file_content: str) -> str:\n try:\n if not file_content:\n raise CustomFileError(\"Fil...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00036233", "row_id": 36233, "seed_ids": "[33]" }
0.563489
Docs: Python310_36233
I
[ "read_file", "process_data", "main_function" ]
3
[ [ "main_function", "process_data" ], [ "main_function", "read_file" ] ]
2
[ "process_data" ]
false
[ "CustomFileError" ]
true
pytest
true
[]
true
9550de2aa3211124080aae1204225b4eb939d47b
df3024fd10cdefc16abb5aa9fab3b38bbea15537
v1.0
instruct
Docs
Docs: Python310_36292_I
### Asynchronous Task Management with Network I/O in Python asyncio **Objective:** Write a Python function that demonstrates the use of asyncio for managing tasks and handling network I/O operations concurrently. **Problem Statement:** You are required to implement a server-client model using asyncio where: 1. The se...
import asyncio async def handle_client(reader, writer): data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message} from {addr}") response = f"Received: {message}" writer.write(response.encode()) await writer.drain() w...
import asyncio import pytest from solution import start_server, client_send_message @pytest.fixture(scope="module") def event_loop(): loop = asyncio.new_event_loop() yield loop loop.close() @pytest.fixture(scope="module") async def server(event_loop): host = '127.0.0.1' port = 8888 server_task...
[]
[ 1, 1, 0, 1, 1, 1, 1, 0, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n data = await reader.read(100)\n message = data.decode()\n addr = writer.get_extra_info('peername')...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00036292", "row_id": 36292, "seed_ids": "[360]" }
0.621584
Docs: Python310_36292
I
[ "handle_client", "start_server", "client_send_message", "main" ]
4
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c9e5e81a1ffe9ac3da9b1cfd0fe744fa5c6191dd
043ad3b3109a60fab0ea4dd9439fefa736e41393
v1.0
instruct
Docs
Docs: Pytorch_36296_I
### Gradient Checking in PyTorch **Objective:** Implement a custom loss function using PyTorch, and verify the correctness of its gradient computations using `torch.autograd.gradcheck` and `torch.autograd.gradgradcheck`. **Instructions:** 1. **Implement a Custom Loss Function:** - Define a function `custom_loss` ...
import torch from torch.autograd import gradcheck, gradgradcheck # Step 1: Implement the custom loss function def custom_loss(x): """ Compute the custom loss function. Args: x (torch.Tensor): Input tensor of size (N,). Returns: torch.Tensor: Scalar tensor representing the loss. ...
from solution import custom_loss, verify_gradcheck, verify_gradgradcheck def test_custom_loss(): x = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float64, requires_grad=True) expected_loss = sum(xi**2 + torch.sin(xi) for xi in x) assert custom_loss(x).item() == expected_loss.item() def test_gradcheck(): ...
[ { "docstring": "Compute the custom loss function.\n\nArgs:\n x (torch.Tensor): Input tensor of size (N,).\n\nReturns:\n torch.Tensor: Scalar tensor representing the loss.", "function_declaration": "def custom_loss(x):", "function_name": "custom_loss", "parameter_list": "(x)" }, { "docs...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.autograd import gradcheck, gradgradcheck\n\n# Step 1: Implement the custom loss function\ndef custom_loss(x):\n \"\"\"\n Compute the cust...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00036296", "row_id": 36296, "seed_ids": "[179]" }
0.534296
Docs: Pytorch_36296
I
[ "custom_loss", "verify_gradcheck", "verify_gradgradcheck" ]
3
[ [ "verify_gradcheck", "custom_loss" ], [ "verify_gradgradcheck", "custom_loss" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
10c65086e77b968e54e75524e120a9ac155e58ac
79f2d5a0cd3a5ccefe6b6d5694b91c5f316a4cac
v1.0
instruct
Docs
Docs: Scikit_36330_I
**Objective**: Assess the understanding and application of linear models using scikit-learn, focusing on model training, regularization, and evaluation. **Problem Statement**: You are given a dataset represented by feature matrix `X` and target vector `y`. Your task is to implement functions that train and evaluate th...
import numpy as np from sklearn.linear_model import LinearRegression, Ridge, Lasso from sklearn.model_selection import cross_val_score def train_ols(X_train, y_train): """ Train Ordinary Least Squares (OLS) model on the training data. """ model = LinearRegression() model.fit(X_train, y_train) r...
from solution import train_ols, train_ridge, train_lasso, select_best_model, fit_and_predict_best_model, main import numpy as np from sklearn.datasets import make_regression from sklearn.linear_model import LinearRegression, Ridge, Lasso # Generate synthetic data for testing def generate_data(): X_train, y_train =...
[ { "docstring": "Train Ordinary Least Squares (OLS) model on the training data.", "function_declaration": "def train_ols(X_train, y_train):", "function_name": "train_ols", "parameter_list": "(X_train, y_train)" }, { "docstring": "Train Ridge Regression model on the training data with given al...
[ 1, 1, 1, 1, 0, 0, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso\nfrom sklearn.model_selection import cross_val_score\n\ndef train_ols(X_train, y_tra...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00036330", "row_id": 36330, "seed_ids": "[53]" }
0.622609
Docs: Scikit_36330
I
[ "train_ols", "train_ridge", "train_lasso", "select_best_model", "fit_and_predict_best_model", "main" ]
6
[ [ "fit_and_predict_best_model", "select_best_model" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
2969d2083166f969e97adba6aa076d171c1c488a
64e80cab131e96c34cd11fc0e947b413b541d623
v1.0
instruct
Docs
Docs: Python310_36369_I
### Python Signal Handling Exercise #### Problem Statement You are tasked with building a simplified watchdog timer system to monitor and manage a long-running task. The watchdog should be able to: 1. Start a task and set a timeout using an alarm. 2. Handle custom signals to pause, resume, and stop the task. 3. Gracef...
import signal import time import os # Global variable to control the task state task_paused = False task_running = True def timeout_handler(signum, frame): print("Timeout! Task taking too long.") raise TimeoutError("Task exceeded the allowed time limit.") def pause_handler(signum, frame): global task_pau...
import os import signal import subprocess import time # NOTE: Due to the nature of signal handling, these tests will need to run in a separate process context. def test_task_timeout(): process = subprocess.Popen(['python', 'solution.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) process.wait(15) # Wai...
[ { "docstring": null, "function_declaration": "def timeout_handler(signum, frame):", "function_name": "timeout_handler", "parameter_list": "(signum, frame)" }, { "docstring": null, "function_declaration": "def pause_handler(signum, frame):", "function_name": "pause_handler", "para...
[ 1, 1, 1, 0, 0, 1, 1, 0, 0 ]
5
medium
0.556
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import signal\nimport time\nimport os\n\n# global flag to control the paused state\npaused = False\n\ndef timeout_handler(signum, frame):\n print(\"Timeout! Task tak...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00036369", "row_id": 36369, "seed_ids": "[253]" }
0.550956
Docs: Python310_36369
I
[ "timeout_handler", "pause_handler", "resume_handler", "interrupt_handler", "start_task" ]
5
[ [ "start_task", "interrupt_handler" ], [ "start_task", "pause_handler" ], [ "start_task", "resume_handler" ], [ "start_task", "timeout_handler" ] ]
4
[]
false
[]
false
pytest
false
[]
true
eb9eeaf35a9c2cc6a3d6c37dfc4025f60a1ba5a2
a463ab17f9cb07393f3ee12cd9eec98ae990d0f6
v1.0
instruct
Docs
Docs: Python310_36378_I
### Advanced Python Coding Assessment: Working with the Random Module You have been given the task to simulate a simplistic version of a dice-based board game. In this game, each player rolls two six-sided dice per turn and moves forward by the sum of the dice values. The first player to reach or exceed a specified sc...
import random def roll_dice() -> int: """ Simulate rolling two six-sided dice and return the sum of the rolls. Returns: int: The sum of the two dice rolls. """ dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) return dice1 + dice2 def play_game(target_score: int, num_player...
from solution import roll_dice, play_game def test_roll_dice(): random.seed(0) result = roll_dice() assert 2 <= result <= 12 def test_roll_dice_distribution(): random.seed(0) results = [roll_dice() for _ in range(1000)] assert all(2 <= result <= 12 for result in results) assert sum(results...
[ { "docstring": "Simulate rolling two six-sided dice and return the sum of the rolls.\nReturns:\n int: The sum of the two dice rolls.", "function_declaration": "def roll_dice():", "function_name": "roll_dice", "parameter_list": "()" }, { "docstring": "Simulate a dice game where players rol...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef roll_dice() -> int:\n \"\"\"\n Simulate rolling two six-sided dice and return the sum of the rolls.\n Returns:\n int: The sum of th...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00036378", "row_id": 36378, "seed_ids": "[119]" }
0.569753
Docs: Python310_36378
I
[ "roll_dice", "play_game" ]
2
[ [ "play_game", "roll_dice" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8aa58e7422079b2f17eb40548a40eeabaafa660a
2a5ac6bf1c0bf32fd476424f1ed3f62926125e01
v1.0
instruct
Docs
Docs: Python310_36427_I
**Objective**: Assess the understanding of asyncio Future objects and their manipulation in an asynchronous context. **Problem Statement**: You are required to implement an asynchronous task scheduler using asyncio.Future objects. The scheduler will handle multiple asynchronous tasks and ensure that all tasks are com...
import asyncio async def create_task(fut, delay, value): """ Coroutine that takes a Future object `fut`, sleeps for `delay` seconds, and then sets `value` as the result of `fut`. Parameters: - fut (asyncio.Future): Future object to set the result for. - delay (int): Number of seconds to sleep ...
import pytest import asyncio from solution import create_task, task_scheduler, main @pytest.mark.asyncio async def test_create_task(): fut = asyncio.Future() await create_task(fut, 1, 'Test Task') assert fut.result() == 'Test Task' @pytest.mark.asyncio async def test_task_scheduler_all_completed(): lo...
[]
[ 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": "import asyncio\n\nasync def create_task(fut, delay, value):\n \"\"\"\n Coroutine that takes a Future object `fut`, sleeps for `delay` seconds,\n and then sets ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00036427", "row_id": 36427, "seed_ids": "[113]" }
0.550363
Docs: Python310_36427
I
[ "create_task", "task_scheduler", "main" ]
3
[ [ "task_scheduler", "create_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
94e4eaf62aade1802223046965a4fa2a042c3459
597dda1c1b919f1b7fafa5af15ad0693f079f5da
v1.0
instruct
Docs
Docs: Python310_36455_I
#### Objective: To test your understanding of the essential `asyncio` concepts, event loops, task scheduling, and network communication using Python's `asyncio` library. #### Problem: Write an asynchronous function `async def echo_server(host: str, port: int) -> None` that implements a simple TCP echo server. The serv...
import asyncio import signal class EchoServerProtocol(asyncio.Protocol): def __init__(self): self.transport = None def connection_made(self, transport): self.transport = transport def data_received(self, data): message = data.decode() echo_message = f"Echo: {message}" ...
import asyncio import signal import pytest from contextlib import contextmanager from solution import echo_server, EchoServerProtocol @contextmanager def does_not_raise(): yield @pytest.fixture async def start_echo_server(): server_task = asyncio.create_task(echo_server('127.0.0.1', 8888)) await asyncio....
[]
[ 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport signal\n\nclass EchoServerProtocol(asyncio.Protocol):\n def connection_made(self, transport):\n self.transport = transport\n\n def d...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00036455", "row_id": 36455, "seed_ids": "[101]" }
0.697287
Docs: Python310_36455
I
[ "echo_server", "shutdown" ]
2
[ [ "echo_server", "shutdown" ] ]
1
[]
false
[ "EchoServerProtocol" ]
true
pytest
true
[]
true
03ab36503ac95d4b17dee9e7d0d3ea27882304ab
b01c39dc42178414182190cb31df3e8af6b84767
v1.0
instruct
Docs
Docs: Python310_36488_I
**Coding Assessment Question: Advanced Task Scheduling and Error Handling in asyncio** ### Objective Implement a Python function using the `asyncio` package to create and manage multiple asynchronous tasks, handle scheduling of callbacks, and incorporate custom error handling in an asyncio event loop. ### Problem Sta...
import asyncio async def task(number, delay): await asyncio.sleep(delay) print(f"Task {number} completed after {delay} seconds") def all_tasks_done_callback(): print("All tasks completed!") def custom_exception_handler(loop, context): exception = context.get('exception') print(f"Custom Exception ...
import asyncio import time from solution import run_event_loop_with_task_handling def test_run_event_loop_with_task_handling(capfd): start_time = time.time() run_event_loop_with_task_handling() out, _ = capfd.readouterr() end_time = time.time() # Ensure output contains the expected m...
[ { "docstring": null, "function_declaration": "def all_tasks_done_callback():", "function_name": "all_tasks_done_callback", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def custom_exception_handler(loop, context):", "function_name": "custom_exception_handler...
[ 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def async_task(task_number, delay):\n await asyncio.sleep(delay)\n print(f\"Task {task_number} completed after {delay} seconds\")\n\ndef a...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00036488", "row_id": 36488, "seed_ids": "[267]" }
0.563463
Docs: Python310_36488
I
[ "task", "all_tasks_done_callback", "custom_exception_handler", "run_event_loop_with_task_handling" ]
4
[ [ "run_event_loop_with_task_handling", "all_tasks_done_callback" ], [ "run_event_loop_with_task_handling", "custom_exception_handler" ], [ "run_event_loop_with_task_handling", "task" ] ]
3
[]
false
[]
false
pytest
true
[]
true
f8398abd44585a3afd9df7f18c0ed39110d6ab98
b9491389d2ed5ee847b5b9b8106a6cfa05a5a927
v1.0
instruct
Docs
Docs: Python310_36515_I
**Cryptographic Services Assessment** You are required to implement a secure authentication system using Python's cryptographic services. The system needs to perform the following tasks: 1. **Password Hashing and Verification**: - Implement a function to securely hash a user's password using the `hashlib` module. ...
import hashlib import secrets import hmac def hash_password(password: str) -> str: """ Hash the given password using SHA256. """ hash_object = hashlib.sha256(password.encode()) hashed_password = hash_object.hexdigest() return hashed_password def verify_password(password: str, hashed_password: ...
from solution import hash_password, verify_password, generate_token, authenticate_message, verify_message def test_hash_password(): password = "secure_password" hashed = hash_password(password) assert isinstance(hashed, str) assert len(hashed) == 64 # Length of SHA-256 hash in hexadecimal def test_ve...
[ { "docstring": "Hash the given password using SHA256.", "function_declaration": "def hash_password(password):", "function_name": "hash_password", "parameter_list": "(password)" }, { "docstring": "Verify the given password against the hashed password.", "function_declaration": "def verify...
[ 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": "import hashlib\nimport hmac\nimport secrets\n\ndef hash_password(password: str) -> str:\n \"\"\"\n Hashes a password using SHA-256 algorithm.\n \"\"\"\n ret...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00036515", "row_id": 36515, "seed_ids": "[394]" }
0.733976
Docs: Python310_36515
I
[ "hash_password", "verify_password", "generate_token", "authenticate_message", "verify_message" ]
5
[ [ "verify_message", "authenticate_message" ], [ "verify_password", "hash_password" ] ]
2
[]
false
[]
false
pytest
true
[]
true
284adce08137d030c25e669b3a7d86830aa4f0ff
24d88a4a54c17f7becf6e2023037a5c5c17d9fc0
v1.0
instruct
Docs
Docs: Scikit_36525_I
**Objective**: Demonstrate your understanding of scikit-learn's `SGDClassifier`, feature scaling, pipelines, and model evaluation. ### Problem Statement You are provided with a dataset containing features and class labels. Your task is to: 1. Load and preprocess the data. 2. Implement a machine learning pipeline usi...
import pandas as pd from sklearn.linear_model import SGDClassifier from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline from sklearn.metrics import accuracy_score def load_and_preprocess_data(file_path): """ Loads the d...
import pytest from solution import load_and_preprocess_data, create_pipeline, train_and_evaluate_model @pytest.fixture def sample_data(tmp_path): # Create a sample dataset data = """label,feature1,feature2,feature3 0,1.0,2.0,3.0 1,4.0,5.0,6.0 0,7.0,8.0,9.0 ...
[ { "docstring": "Loads the dataset and preprocesses it by splitting into train and test sets\nand scaling the feature values.", "function_declaration": "def load_and_preprocess_data(file_path):", "function_name": "load_and_preprocess_data", "parameter_list": "(file_path)" }, { "docstring": "C...
[ 0, 1, 0, 0, 0, 1, 0, 1, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardSca...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00036525", "row_id": 36525, "seed_ids": "[44]" }
0.599045
Docs: Scikit_36525
I
[ "load_and_preprocess_data", "create_pipeline", "train_and_evaluate_model" ]
3
[ [ "train_and_evaluate_model", "create_pipeline" ], [ "train_and_evaluate_model", "load_and_preprocess_data" ] ]
2
[]
false
[]
false
pytest
true
[ "pandas", "sklearn" ]
false
c48a6e00c8295c4c113cf425e71499369af83884
1a024b189859a3bfa795abd8b1714f748998195f
v1.0
instruct
Docs
Docs: Python310_36534_I
You are required to implement a small concurrent application that fetches data from multiple URLs and processes it asynchronously. The goal is to efficiently handle multiple HTTP requests and aggregate the results using asyncio. #### Requirements: 1. Implement an asynchronous function `fetch_url(session, url)` that t...
import asyncio import aiohttp import random async def fetch_url(session, url): """ Asynchronously fetches the content of a URL. """ try: async with session.get(url) as response: return await response.text() except Exception as e: print(f"Failed to fetch {url}: {e}") ...
import pytest import asyncio from unittest.mock import AsyncMock import aiohttp from solution import fetch_url, process_data, fetch_and_process @pytest.mark.asyncio async def test_fetch_url(): session = AsyncMock(aiohttp.ClientSession) url = "http://example.com" session.get.return_value.__aenter__.re...
[]
[ 1, 1, 1, 1, 1, 0, 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\nimport aiohttp\nimport random\n\nasync def fetch_url(session, url):\n \"\"\"\n Takes an aiohttp client session and a URL string to perform an HTTP...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00036534", "row_id": 36534, "seed_ids": "[270]" }
0.53956
Docs: Python310_36534
I
[ "fetch_url", "process_data", "fetch_and_process" ]
3
[ [ "fetch_and_process", "fetch_url" ], [ "fetch_and_process", "process_data" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[ "aiohttp" ]
false
f48f83106d73cbc078ee0a3be3b4dac52d84e633
6553ed4d801884c26ebc8c51fa5da8125b900771
v1.0
instruct
Docs
Docs: Python310_36561_I
You are given a list of tasks, each with a priority and a description. Your task is to implement a priority queue using the `heapq` module, which supports the following operations: 1. Adding a new task with a given priority. 2. Removing a task with a given description. 3. Pop and return the task with the highest priori...
import heapq def add_task(priority_queue, task, priority): """ Adds a new task with a given priority. """ entry = [priority, task] heapq.heappush(priority_queue, entry) def remove_task(priority_queue, task, task_finder, removed_marker): """ Marks a task as removed in the priority queue by ...
import pytest import heapq from solution import add_task, remove_task, pop_task, change_task_priority REMOVED = '<removed-task>' @pytest.fixture def setup_priority_queue(): priority_queue = [] task_finder = {} return priority_queue, task_finder def test_add_task(setup_priority_queue): priority_queue...
[ { "docstring": "Adds a new task with a given priority.", "function_declaration": "def add_task(priority_queue, task, priority):", "function_name": "add_task", "parameter_list": "(priority_queue, task, priority)" }, { "docstring": "Marks a task as removed in the priority queue by using a uniq...
[ 0, 0, 1, 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 heapq\n\ndef add_task(priority_queue, task, priority):\n \"\"\"\n Add a new task to the priority queue.\n \"\"\"\n entry = [priority, task]\n heap...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00036561", "row_id": 36561, "seed_ids": "[241]" }
0.589754
Docs: Python310_36561
I
[ "add_task", "remove_task", "pop_task", "change_task_priority" ]
4
[ [ "change_task_priority", "add_task" ], [ "change_task_priority", "remove_task" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2ad630fe350902e87b9ad48ddfa9b7c822b82088
7dfc7ae4dc5a2a2115f14ddfd98a83b544e1d4b6
v1.0
instruct
Docs
Docs: Pytorch_36623_I
#### Objective Implement a custom PyTorch transformation using `torch.fx`, where the goal is to replace every instance of a `torch.nn.ReLU` activation in a model with a custom-defined function `custom_relu`. #### Problem Statement You are provided with a base PyTorch model that may contain several ReLU activation func...
import torch import torch.fx from torch.fx import Tracer def custom_relu(x): """ Custom ReLU activation function. Returns element-wise maximum between x and 0, plus a small epsilon. """ epsilon = 1e-6 return torch.max(x, torch.tensor(0.0)) + epsilon def replace_relu_with_custom_relu(model: tor...
import torch import pytest from solution import custom_relu, replace_relu_with_custom_relu class BaseModel(torch.nn.Module): def __init__(self): super(BaseModel, self).__init__() self.layer1 = torch.nn.Linear(10, 10) self.relu = torch.nn.ReLU() self.layer2 = torch.nn.Linear(10, 10) ...
[]
[ 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.fx\nfrom torch.fx import Tracer\n\n\ndef custom_relu(x):\n epsilon = 1e-6\n return torch.max(x, torch.tensor(0.0, device=x.device)) + e...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00036623", "row_id": 36623, "seed_ids": "[42]" }
0.482435
Docs: Pytorch_36623
I
[ "custom_relu", "replace_relu_with_custom_relu" ]
2
[ [ "replace_relu_with_custom_relu", "custom_relu" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
5e7125131f4b113373b49224e2730748ce61dc4e
20899086d6e7c515a6e14cb0e642b2396c8c86b4
v1.0
instruct
Docs
Docs: Seaborn_36682_I
### Question In this task, you are going to demonstrate and implement seaborn functionality to customize plot contexts. #### Requirements You need to implement the following functions: 1. `set_plot_context(context_name, font_scale, rc_params)`: This function should set the plotting context using seaborn and apply th...
import seaborn as sns def set_plot_context(context_name, font_scale=1, rc_params=None): """ Sets the plotting context using seaborn. :param context_name: The name of the context to set. It can be one of the following: 'paper', 'notebook', 'talk', 'poster'. :param font_sca...
from solution import set_plot_context, create_custom_plot import pytest def test_set_plot_context_valid(): set_plot_context('notebook', 1, {'lines.linewidth': 2}) def test_set_plot_context_invalid_name(): with pytest.raises(ValueError): set_plot_context('invalid_context', 1, {'lines.linewidth': 2}) d...
[ { "docstring": "Sets the plotting context using seaborn.\n\n:param context_name: The name of the context to set. \n It can be one of the following: 'paper', 'notebook', 'talk', 'poster'.\n:param font_scale: A value for scaling the size of the fonts relative to the default size.\n:param rc_pa...
[ 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 seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef set_plot_context(context_name, font_scale, rc_params):\n \"\"\"\n Sets the plotting context using se...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00036682", "row_id": 36682, "seed_ids": "[21]" }
0.617143
Docs: Seaborn_36682
I
[ "set_plot_context", "create_custom_plot" ]
2
[ [ "create_custom_plot", "set_plot_context" ] ]
1
[]
false
[]
false
pytest
true
[ "seaborn" ]
false
695f65788cb6fd18fa82ddf32a6a02f09b30cde7
1191e03a691895c99f3054830728c73295c84546
v1.0
instruct
Docs
Docs: Pytorch_36701_I
#### Objective The objective of this question is to assess the student's understanding of PyTorch's attention mechanisms and the use of block masks within these mechanisms. The tasks involve creating block masks and integrating them into a simplified attention layer. #### Problem Statement You are required to implemen...
import torch import torch.nn as nn def create_block_mask(size): # This is a simplified placeholder for the create_block_mask utility function. # In a real scenario, you would import this from the utility module. return torch.ones(size) def generate_block_mask(shape: tuple) -> torch.Tensor: """ Gen...
from solution import generate_block_mask, SimpleAttention def test_generate_block_mask(): mask = generate_block_mask((3, 3)) assert mask.size() == (3, 3) assert torch.all(mask == 1) def test_SimpleAttention(): embed_dim = 4 attention_layer = SimpleAttention(embed_dim=embed_dim) query = ke...
[]
[ 1, 0, 1, 1, 1, 1, 1, 1, 0, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\n\ndef create_block_mask(height: int, width: int) -> torch.Tensor:\n \"\"\"\n Utility function to create a block mask.\n \n...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00036701", "row_id": 36701, "seed_ids": "[0]" }
0.416677
Docs: Pytorch_36701
I
[ "create_block_mask", "generate_block_mask" ]
2
[ [ "generate_block_mask", "create_block_mask" ] ]
1
[]
false
[ "SimpleAttention" ]
true
pytest
true
[ "torch" ]
false
16cdfae946df74894fb958f0637fd4b17a8d6467
5b00e13108e0405f69f248a347973c5d390b32bf
v1.0
instruct
Docs
Docs: Pandas_36706_I
### Time Series Analysis with Pandas #### Objective Implement a set of functions to demonstrate your mastery of pandas time series manipulation, focusing on creating time series, applying time zones, resampling data, and handling custom business days. #### Problem Statement You are given sales data for a company whi...
import pandas as pd import numpy as np from pandas.tseries.offsets import CustomBusinessDay from typing import List def generate_time_series(start: str, end: str, freq: str, tz: str) -> pd.Series: """ Create a time series with random sales data from `start` to `end` at a specified frequency and time zone. ...
import pandas as pd import numpy as np from solution import generate_time_series, resample_and_aggregate, apply_custom_business_days, analyze_sales def test_generate_time_series(): ts = generate_time_series("2023-01-01", "2023-01-07", "1H", "America/New_York") assert len(ts) == 145, "Time series length should ...
[ { "docstring": "Create a time series with random sales data from `start` to `end` at a specified frequency and time zone.", "function_declaration": "def generate_time_series(start, end, freq, tz):", "function_name": "generate_time_series", "parameter_list": "(start, end, freq, tz)" }, { "doc...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport numpy as np\n\ndef generate_time_series(start: str, end: str, freq: str, tz: str) -> pd.Series:\n \"\"\"\n Create a time series with r...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00036706", "row_id": 36706, "seed_ids": "[17]" }
0.733904
Docs: Pandas_36706
I
[ "generate_time_series", "resample_and_aggregate", "apply_custom_business_days", "analyze_sales" ]
4
[ [ "analyze_sales", "resample_and_aggregate" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "pandas" ]
false
76d19d7f47ee601a591beb3757fd08960de913bf
439c6d79edd4c514ef0f9c1ce09a1a94804638f3
v1.0
instruct
Docs
Docs: Python310_36742_I
**Objective:** Design a function to demonstrate the comprehension of handling various asyncio exceptions. This question focuses on simulating realistic scenarios in asynchronous operations and managing the exceptions raised effectively. **Question:** You are required to implement an asynchronous function `fetch_data...
from typing import List import aiohttp import asyncio async def fetch_url(session, url, timeout): try: async with session.get(url, timeout=timeout) as response: return await response.text() except asyncio.TimeoutError: return f"TimeoutError: Operation exceeded the given deadline" ...
import pytest import asyncio from solution import fetch_data @pytest.mark.asyncio async def test_fetch_data_success(): urls = ["https://httpbin.org/get"] result = await fetch_data(urls, 3) assert "url" in result[0], "URL content expected in response" @pytest.mark.asyncio async def test_fetch_data_timeout(...
[]
[ 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport aiohttp\nimport asyncio\n\nasync def fetch_data(urls: List[str], timeout: float) -> List[str]:\n async def fetch(url: str):\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00036742", "row_id": 36742, "seed_ids": "[396]" }
0.536752
Docs: Python310_36742
I
[ "fetch_url", "fetch_data" ]
2
[ [ "fetch_data", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
01d5376da598d2721e005ad58c037458b497dbfb
0be7aa30b0a344044f26302de218662a2a87d06e
v1.0
instruct
Docs
Docs: Python310_36763_I
### Parallel Data Processing with `concurrent.futures` You have been provided with a large dataset consisting of URLs. Each URL points to a file that needs to be downloaded, processed, and summarized. Processing each file involves reading its contents and calculating the number of words. You need to design a Python f...
import concurrent.futures from typing import List, Dict import random import time def download_url(url: str) -> str: # Simulate network delay time.sleep(random.uniform(0.1, 0.3)) # Simulate file content return "This is the content of the file at " + url def count_words(content: str) -> int: """ ...
import pytest from solution import parallel_url_processing def test_parallel_url_processing_single_url(): urls = ["http://example.com/file1.txt"] result = parallel_url_processing(urls) assert result["http://example.com/file1.txt"] > 0 # Simple check for a valid word count def test_parallel_url_processing...
[ { "docstring": null, "function_declaration": "def download_url(url):", "function_name": "download_url", "parameter_list": "(url)" }, { "docstring": "Given the content of a file as a string, return the number of words.", "function_declaration": "def count_words(content):", "function_n...
[ 1, 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import concurrent.futures\nfrom typing import List, Dict\nimport random\nimport time\n\ndef download_url(url: str) -> str:\n # Simulate network delay\n time.sleep...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00036763", "row_id": 36763, "seed_ids": "[224]" }
0.561509
Docs: Python310_36763
I
[ "download_url", "count_words", "process_url", "parallel_url_processing" ]
4
[ [ "parallel_url_processing", "process_url" ], [ "process_url", "count_words" ], [ "process_url", "download_url" ] ]
3
[]
false
[]
false
pytest
true
[]
true
d5273efaa985a434c63f7a496911e6f701e8b977
eaebab73eb8fe8de7c098ba01678936ef7a1cc7e
v1.0
instruct
Docs
Docs: Scikit_36779_I
### Out-of-Core Learning Challenge **Objective:** Implement an out-of-core learning system for a text classification task using scikit-learn. **Problem Statement:** You are given a large dataset of text documents and their associated labels. The dataset is too large to fit into memory, so you must process it in mini-...
from typing import List, Tuple from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(batch_size: int, num_batches: int) -> Tuple[List[str], List[int]]: """ Simulates streaming data by yielding mini...
import pytest from solution import stream_data, train_incremental_classifier def test_stream_data(): batch_size = 10 num_batches = 3 data_batches = list(stream_data(batch_size, num_batches)) assert len(data_batches) == num_batches for texts, labels in data_batches: assert len(texts) ==...
[ { "docstring": "Simulates streaming data by yielding mini-batches of text documents and labels.", "function_declaration": "def stream_data(batch_size, num_batches):", "function_name": "stream_data", "parameter_list": "(batch_size, num_batches)" }, { "docstring": "Trains an incremental classi...
[ 1, 1, 0, 1, 1, 0, 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": "from sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\nfrom typing i...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00036779", "row_id": 36779, "seed_ids": "[63]" }
0.512677
Docs: Scikit_36779
I
[ "stream_data", "train_incremental_classifier" ]
2
[ [ "train_incremental_classifier", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
feac475a2b7e71e4c0b65bf80e55667f36dab43d
00e51a317289a3706e41292833f2f5ee23aafecb
v1.0
instruct
Docs
Docs: Python310_36835_I
## Problem Statement You are given a list of students with their scores in multiple subjects. Your task is to perform various operations such as adding new scores, updating existing scores, calculating the average score for each student, and performing some advanced queries and transformations. **Objective:** Impleme...
def add_score(data, student, subject, score): if student not in data: data[student] = {} data[student][subject] = score def update_score(data, student, subject, score): if student in data and subject in data[student]: data[student][subject] = score def delete_score(data, student, subject):...
import pytest from solution import add_score, update_score, delete_score, average_score, top_student, subject_topper, students_with_minimum_score, transpose_scores def test_add_score(): data = {"Alice": {"Math": 90}} add_score(data, "Alice", "Science", 95) assert data["Alice"]["Science"] == 95 add_sco...
[ { "docstring": null, "function_declaration": "def add_score(data, student, subject, score):", "function_name": "add_score", "parameter_list": "(data, student, subject, score)" }, { "docstring": null, "function_declaration": "def update_score(data, student, subject, score):", "functio...
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def add_score(data, student, subject, score):\n if student not in data:\n data[student] = {}\n data[student][subject] = score\n\ndef update_score(data, stu...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00036835", "row_id": 36835, "seed_ids": "[411]" }
0.68433
Docs: Python310_36835
I
[ "add_score", "update_score", "delete_score", "average_score", "top_student", "subject_topper", "students_with_minimum_score", "transpose_scores" ]
8
[ [ "top_student", "average_score" ] ]
1
[]
false
[]
false
pytest
true
[]
true
288742e39ae87978df829ebaae5a3c760dcbcf6b
6c88c5a2678ebe589c809a2ba7ce413b57a4a2ca
v1.0
instruct
Docs
Docs: Pytorch_36838_I
**Objective:** Demonstrate your understanding of tensor operations and interoperability by utilizing PyTorch and DLPack. **Problem Statement:** You are provided with a function that generates a DLPack tensor. Your task is to define two functions: 1. `convert_to_pytorch(dlpack_tensor: "dlpack") -> "torch.Tensor"`: Thi...
import torch from torch.utils.dlpack import from_dlpack, to_dlpack def convert_to_pytorch(dlpack_tensor: "dlpack") -> torch.Tensor: """ Converts a DLPack tensor to a PyTorch tensor. """ return from_dlpack(dlpack_tensor) def convert_to_dlpack(pytorch_tensor: torch.Tensor) -> "dlpack": """ Conve...
import torch from torch.utils.dlpack import to_dlpack from solution import convert_to_pytorch, convert_to_dlpack, verify_conversion def test_convert_to_pytorch(): torch_tensor = torch.tensor([1, 2, 3, 4], dtype=torch.float32) dlpack_tensor = to_dlpack(torch_tensor) converted_tensor = convert_to_pytorch(dlp...
[ { "docstring": "Converts a DLPack tensor to a PyTorch tensor.", "function_declaration": "def convert_to_pytorch(dlpack_tensor):", "function_name": "convert_to_pytorch", "parameter_list": "(dlpack_tensor)" }, { "docstring": "Converts a PyTorch tensor to a DLPack tensor.", "function_declar...
[ 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": "import torch\nfrom torch.utils.dlpack import from_dlpack, to_dlpack\n\ndef convert_to_pytorch(dlpack_tensor):\n \"\"\"\n Converts a DLPack tensor to a PyTorch ten...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00036838", "row_id": 36838, "seed_ids": "[73]" }
0.520377
Docs: Pytorch_36838
I
[ "convert_to_pytorch", "convert_to_dlpack", "verify_conversion" ]
3
[ [ "verify_conversion", "convert_to_dlpack" ], [ "verify_conversion", "convert_to_pytorch" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
d5cbea821fc4c86f2a205bb3db36014f3e45de52
d7792100bc6df569b32ca48087431dcc3b817132
v1.0
instruct
Docs
Docs: Python310_36928_I
**Title:** Implementing an Asynchronous Data Processing Pipeline with Comprehensions. **Objective:** To assess the understanding of asynchronous operations, comprehensions, and generator expressions in Python. **Task:** You are tasked with implementing a complex data processing pipeline that processes a stream of ...
import asyncio from typing import AsyncGenerator, List, Generator async def async_gen_squares(max_num: int) -> AsyncGenerator[int, None]: for i in range(1, max_num + 1): await asyncio.sleep(0.1) # Simulating asynchronous operation yield i ** 2 def filter_even_numbers(sequence: List[int]) -> List[...
import pytest import asyncio from solution import async_gen_squares, filter_even_numbers, gen_cumulative_sum, async_sum_cumulative @pytest.mark.asyncio async def test_async_gen_squares(): expected_output = [1, 4, 9, 16, 25] result = [num async for num in async_gen_squares(5)] assert result == expected_out...
[ { "docstring": null, "function_declaration": "def filter_even_numbers(sequence):", "function_name": "filter_even_numbers", "parameter_list": "(sequence)" }, { "docstring": null, "function_declaration": "def gen_cumulative_sum(sequence):", "function_name": "gen_cumulative_sum", "p...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def async_gen_squares(max_num: int):\n \"\"\"\n Asynchronous generator that yields squares of numbers from 1 to max_num inclusive.\n \"...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00036928", "row_id": 36928, "seed_ids": "[98]" }
0.554779
Docs: Python310_36928
I
[ "async_gen_squares", "filter_even_numbers", "gen_cumulative_sum", "async_sum_cumulative" ]
4
[ [ "async_sum_cumulative", "async_gen_squares" ] ]
1
[]
false
[]
false
pytest
true
[]
true
891572af06c43e134d008b36098eb54fd1fd56c2
d3e1c5f152b6f29de01658b75d0756877ec6fe6e
v1.0
instruct
Docs
Docs: Python310_36929_I
#### Objective: Implement an asynchronous task management system using Python's `asyncio.Future` objects. Your task is to create an asynchronous task that processes multiple tasks, manages future results, and handles exceptions appropriately. #### Problem Statement: You are given a list of URLs. Some URLs may fail to ...
import asyncio import random from typing import List class FetchError(Exception): pass async def fetch_url(fut: asyncio.Future, url: str): try: # Simulate network delay await asyncio.sleep(random.uniform(0.1, 0.5)) # Randomly fail if random.choice([True, False]): ra...
import asyncio import pytest from solution import process_urls, FetchError @pytest.mark.asyncio async def test_fetch_success(): urls = ["http://example.com/success1", "http://example.com/success2"] # Mock fetch_url to always succeed async def mock_fetch_url(fut, url): await asyncio.sleep(0.1) ...
[]
[ 0, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\nfrom typing import List\n\nclass FetchError(Exception):\n pass\n\nasync def fetch_url(fut: asyncio.Future, url: str):\n try:\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00036929", "row_id": 36929, "seed_ids": "[113]" }
0.541696
Docs: Python310_36929
I
[ "fetch_url", "on_fetch_complete", "process_urls" ]
3
[ [ "process_urls", "fetch_url" ], [ "process_urls", "on_fetch_complete" ] ]
2
[]
false
[ "FetchError" ]
true
pytest
true
[]
true
c02527b8122dc848ddd9d214c73f8f9e3c85cf08
25032d96a0b5df9a1551228106e8f56f285fb6be
v1.0
instruct
Docs
Docs: Python310_36942_I
Parallel Merge Sort with Multiprocessing #### Objective: Implement a parallel version of the merge sort algorithm using the `multiprocessing` module. Your implementation should demonstrate the use of process pools to divide sorting tasks among multiple processes and correctly merge the sorted subarrays. #### Task: 1....
import multiprocessing as mp def merge(left, right): """ Merge two sorted lists into a single sorted list. """ result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(...
from solution import parallel_merge_sort def test_parallel_merge_sort_single_element(): assert parallel_merge_sort([1], 2) == [1] def test_parallel_merge_sort_empty_list(): assert parallel_merge_sort([], 2) == [] def test_parallel_merge_sort_sorted_list(): assert parallel_merge_sort([1, 2, 3, 4, 5], 2) =...
[ { "docstring": "Merge two sorted lists into a single sorted list. ", "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" }, { "docstring": "Sequential merge sort function. ", "function_declaration": "def merge_sort(arr):", "f...
[ 0, 0, 0, 1, 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 multiprocessing\n\ndef merge(left, right):\n result = []\n left_idx, right_idx = 0, 0\n\n while left_idx < len(left) and right_idx < len(right):\n ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00036942", "row_id": 36942, "seed_ids": "[338]" }
0.554408
Docs: Python310_36942
I
[ "merge", "merge_sort", "parallel_merge_sort" ]
3
[ [ "merge_sort", "merge" ], [ "parallel_merge_sort", "merge" ], [ "parallel_merge_sort", "merge_sort" ] ]
3
[]
false
[]
false
pytest
true
[]
true
42558e0dfae977b6904a7dfdb719b37c63e95cde
a23c0a037d47fce25e5800648ef2f0e53f2ce4ba
v1.0
instruct
Docs
Docs: Pytorch_36966_I
### Question: Implementing a Custom Attention Mechanism using Mask Utilities #### Objective Your task is to implement a custom attention mechanism that uses provided mask utility functions from the PyTorch `torch.nn.attention.flex_attention` module. The custom attention mechanism should apply various masks to an input...
import torch # Placeholder utility functions to simulate the mask operations from 'torch.nn.attention.flex_attention' def create_block_mask(batch_size, seq_length): return torch.ones((batch_size, seq_length)) def create_mask(batch_size, seq_length): return torch.ones((batch_size, seq_length)) def and_masks(m...
import pytest import torch from solution import custom_attention def test_custom_attention_and_mask(): input_tensor = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.float32) output_tensor = custom_attention(input_tensor, "and") # Since all masks are ones, the output tensor should be identical to the inpu...
[ { "docstring": null, "function_declaration": "def create_block_mask(batch_size, seq_length):", "function_name": "create_block_mask", "parameter_list": "(batch_size, seq_length)" }, { "docstring": null, "function_declaration": "def create_mask(batch_size, seq_length):", "function_name...
[ 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 torch\nfrom torch.nn.attention.flex_attention import create_block_mask, create_mask, and_masks, or_masks, noop_mask\n\ndef custom_attention(input_tensor: torch.T...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00036966", "row_id": 36966, "seed_ids": "[0]" }
0.459265
Docs: Pytorch_36966
I
[ "create_block_mask", "create_mask", "and_masks", "or_masks", "noop_mask", "custom_attention" ]
6
[ [ "custom_attention", "and_masks" ], [ "custom_attention", "create_block_mask" ], [ "custom_attention", "create_mask" ], [ "custom_attention", "noop_mask" ], [ "custom_attention", "or_masks" ] ]
5
[]
false
[]
false
pytest
true
[ "torch" ]
false
1eb91a820e7e923c72aae7e439d605e88fae7b06
960c61057a205216104bd73d011138fbe262ce2e
v1.0
instruct
Docs
Docs: Python310_36991_I
#### Objective Demonstrate your understanding of the `curses` module by creating a simple text-based user interface application. #### Task Implement a Python function named `run_curses_interface` that uses the `curses` module to create a text-based user interface. The interface should have the following features: 1. *...
import curses def run_curses_interface(stdscr): # Initialize the curses application curses.curs_set(0) # hide cursor curses.noecho() curses.cbreak() stdscr.keypad(True) # Start color functionality curses.start_color() curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) # Ma...
import pytest from solution import run_curses_interface_wrapper def test_curses_interface(): # Testing curses apps is done manually because # they rely on interactive user input. # This is a placeholder for any necessary setup/teardown. try: run_curses_interface_wrapper() except: # ...
[ { "docstring": null, "function_declaration": "def run_curses_interface(stdscr):", "function_name": "run_curses_interface", "parameter_list": "(stdscr)" }, { "docstring": null, "function_declaration": "def run_curses_interface_wrapper():", "function_name": "run_curses_interface_wrappe...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import curses\n\ndef run_curses_interface(stdscr):\n # Basic initialization\n curses.noecho()\n curses.cbreak()\n stdscr.keypad(True)\n \n # Check if ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00036991", "row_id": 36991, "seed_ids": "[74]" }
0.390096
Docs: Python310_36991
I
[ "run_curses_interface", "run_curses_interface_wrapper" ]
2
[ [ "run_curses_interface_wrapper", "run_curses_interface" ] ]
1
[]
false
[]
false
pytest
true
[]
true
71822ee615369f87c7bd35e423668cb97b6c6e87
e442a2da2098d497e94f3e0310eeafd89c4a55fa
v1.0
instruct
Docs
Docs: Python310_37057_I
#### Objective: Demonstrate understanding of the hashlib module's hashing methods, including creating and using hash objects, handling bytes-like data, and utilizing advanced features such as keyed hashing and salted hashing. #### Problem Statement: You are tasked with creating a secure file verification system using ...
import hashlib def calculate_file_hash(filepath, hash_type): """ Calculate the hash of a file content. :param filepath: Path to the file to be hashed. :param hash_type: Type of the hash algorithm (e.g., 'sha256', 'blake2b'). :return: The hexadecimal digest of the hashed file content. """ ...
import os import pytest from solution import calculate_file_hash, verify_file_hash, sign_file TEST_FILE_CONTENT = b"Hello, this is a test file for hashing." TEST_FILE_PATH = "test_file.txt" # Setup and Teardown for creating a temporary test file @pytest.fixture(autouse=True) def setup_and_teardown(): with open(TE...
[ { "docstring": "Calculate the hash of a file content.\n\n:param filepath: Path to the file to be hashed.\n:param hash_type: Type of the hash algorithm (e.g., 'sha256', 'blake2b').\n:return: The hexadecimal digest of the hashed file content.", "function_declaration": "def calculate_file_hash(filepath, hash_t...
[ 1, 0 ]
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 hashlib\n\ndef calculate_file_hash(filepath, hash_type):\n \"\"\"\n Calculate the hash of a file content.\n \n :param filepa...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00037057", "row_id": 37057, "seed_ids": "[225]" }
0.715258
Docs: Python310_37057
I
[ "calculate_file_hash", "verify_file_hash", "sign_file" ]
3
[ [ "verify_file_hash", "calculate_file_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0bed5c4a0c6404f4afcaa896ede1e224b4ecf583
efa7da256085a7e310d652c5ab06c6e45d50cb98
v1.0
instruct
Docs
Docs: Python310_37087_I
### File Synchronizer and Logger You are required to implement a Python script that synchronizes the contents of a source directory to a destination directory. Additionally, the script should log all major steps of its execution. Specifically, your script should: 1. **Monitor**: Continuously monitor the source direct...
import os import time import argparse import logging from shutil import copy2, rmtree from filecmp import cmpfiles def setup_logger(log_file): logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') def get_all_files(directory): a...
import os import shutil import logging from solution import monitor_directories, setup_logger, synchronize_files def test_synchronize_added_file(tmp_path, caplog): source_dir = tmp_path / "source" dest_dir = tmp_path / "dest" log_file = tmp_path / "logfile.log" source_dir.mkdir() dest_dir.mkdi...
[ { "docstring": null, "function_declaration": "def setup_logger(log_file):", "function_name": "setup_logger", "parameter_list": "(log_file)" }, { "docstring": null, "function_declaration": "def get_all_files(directory):", "function_name": "get_all_files", "parameter_list": "(direc...
[ 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 os\nimport time\nimport argparse\nimport logging\nfrom shutil import copy2, rmtree\n\ndef setup_logger(log_file):\n logging.basicConfig(filename=log_file, lev...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00037087", "row_id": 37087, "seed_ids": "[165]" }
0.612195
Docs: Python310_37087
I
[ "setup_logger", "get_all_files", "synchronize_files", "monitor_directories" ]
4
[ [ "monitor_directories", "synchronize_files" ], [ "synchronize_files", "get_all_files" ] ]
2
[]
false
[]
false
pytest
true
[]
true
048ee3bf1092abd1999eaf6b752006433485f9d1
fa2f9ed46486bcb8a40750383e128da4edf29ffa
v1.0
instruct
Docs
Docs: Python310_37117_I
**Question: Implementing Concurrent Data Fetching with Threading and Multiprocessing** You are tasked to design a system that concurrently fetches data from multiple URLs and processes the data fetched. You have to implement two versions of this system: one using thread-based parallelism (using the `threading` module)...
import threading import multiprocessing import requests from typing import List, Dict, Any import json def fetch_data(url: str) -> Any: """ Fetch data from a URL and return the required field from the JSON response. """ try: response = requests.get(url) data = response.json() re...
from solution import fetch_data_using_threads, fetch_data_using_multiprocessing import pytest import requests from unittest.mock import patch # Define test URLs and mock data test_urls = [ "http://example.com/data1", "http://example.com/data2", "http://example.com/data3" ] mock_responses = { "http://e...
[ { "docstring": "Fetch data from a URL and return the required field from the JSON response.", "function_declaration": "def fetch_data(url):", "function_name": "fetch_data", "parameter_list": "(url)" }, { "docstring": "Fetch data from URLs using threads and return a dictionary mapping URLs to...
[ 1, 1, 0, 1, 1, 1, 1, 1, 0 ]
7
easy
0.778
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import threading\nimport multiprocessing\nimport requests\nfrom typing import List, Dict, Any\n\ndef fetch_and_process(url: str) -> Any:\n \"\"\"\n Fetch data fro...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00037117", "row_id": 37117, "seed_ids": "[206]" }
0.574166
Docs: Python310_37117
I
[ "fetch_data", "fetch_data_using_threads", "fetch_data_using_multiprocessing" ]
3
[ [ "fetch_data_using_multiprocessing", "fetch_data" ], [ "fetch_data_using_threads", "fetch_data" ] ]
2
[]
false
[]
false
pytest
true
[ "requests" ]
false
eca43da130f2f61df00b12c02f08ce1038850fa4
eb0e8ada22930f4f69eb9c4ba697cdea7ed57342
v1.0
instruct
Docs
Docs: Python310_37143_I
### Question: Asynchronous Download Manager You are tasked with implementing a basic download manager using the asyncio library. Your download manager should fetch data concurrently from multiple URLs and process this data asynchronously. #### Requirements: 1. Implement a function `fetch_data(url: str) -> str` that...
import asyncio from typing import List # Simulate downloading data with a given URL async def fetch_data(url: str) -> str: await asyncio.sleep(1) # Simulate network delay return url # Simulate processing fetched data async def process_data(data: str) -> str: await asyncio.sleep(0.5) # Simulate processin...
import asyncio from solution import download_manager def test_download_manager_with_multiple_urls(): urls = [ "http://example.com/1", "http://example.com/2", "http://example.com/3", "http://example.com/4", "http://example.com/5", "http://example.com/6", ] exp...
[]
[ 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\nfrom typing import List\n\nasync def fetch_data(url: str) -> str:\n \"\"\"\n Simulates an asynchronous download of data from a given URL by sleepi...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00037143", "row_id": 37143, "seed_ids": "[270]" }
0.549385
Docs: Python310_37143
I
[ "fetch_data", "process_data", "download_manager" ]
3
[ [ "download_manager", "fetch_data" ], [ "download_manager", "process_data" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
da77222d14e8d0e30805f2b86939ac56f97347a6
10018e887f1e7938072fa0ab92c301e63a574787
v1.0
instruct
Docs
Docs: Seaborn_37146_I
You are tasked with visualizing a dataset using Seaborn, ensuring that the plots are visually appealing and appropriately styled for different contexts. Write a function `styled_plots` that accomplishes the following: 1. Generates and plots a set of subplots demonstrating four distinct Seaborn figure styles. 2. Adjust...
import numpy as np import seaborn as sns import matplotlib.pyplot as plt def sinplot(n=10, flip=1): x = np.linspace(0, 14, 100) for i in range(1, n + 1): plt.plot(x, np.sin(x + i * .5) * (n + 2 - i) * flip) def styled_plots(): sns.set_theme() f = plt.figure(figsize=(12, 8)) gs = f.add...
def test_styled_plots(): import matplotlib.pyplot as plt # Call the function styled_plots() # Check that a figure has been created assert plt.get_fignums(), "No figure created" # Check that the number of subplots is 4 figs = [plt.figure(num) for num in plt.get_fignums()] f...
[ { "docstring": null, "function_declaration": "def sinplot(n=10, flip=1):", "function_name": "sinplot", "parameter_list": "(n=10, flip=1)" }, { "docstring": null, "function_declaration": "def styled_plots():", "function_name": "styled_plots", "parameter_list": "()" } ]
[ 0, 1, 0, 1, 1, 0, 0, 1, 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\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef sinplot(n=10, flip=1):\n x = np.linspace(0, 14, 100)\n for i in range(1, n + 1):...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00037146", "row_id": 37146, "seed_ids": "[2]" }
0.73422
Docs: Seaborn_37146
I
[ "sinplot", "styled_plots" ]
2
[ [ "styled_plots", "sinplot" ] ]
1
[]
false
[]
false
pytest
false
[ "matplotlib", "numpy", "seaborn" ]
false
2039025b900d0422e34ee759703c8c55d3f54d30
31ec51566284485a6af9f89ca1306789d484b839
v1.0
instruct
Docs
Docs: Python310_37166_I
**Coding Challenge: International Event Scheduler** **Objective:** You are required to design a function that schedules an international event for a company. The event must be scheduled such that it accommodates attendees from three different time zones and ensures that the event time does not clash with any timezone’...
from datetime import datetime, timedelta from zoneinfo import ZoneInfo def is_night_time(local_time): if 22 <= local_time.hour or local_time.hour < 6: return True return False def schedule_event(date, start_time, company_timezone, attendee_timezones): company_datetime = datetime.strptime(f"{date} ...
from solution import schedule_event def test_event_not_in_night_hours(): event_date = '2023-11-15' proposed_start = '21:00' company_tz = 'America/New_York' attendees_tz = ['Europe/London', 'Asia/Tokyo', 'America/Los_Angeles'] scheduled_times = schedule_event(event_date, proposed_start, company...
[ { "docstring": null, "function_declaration": "def is_night_time(local_time):", "function_name": "is_night_time", "parameter_list": "(local_time)" }, { "docstring": null, "function_declaration": "def schedule_event(date, start_time, company_timezone, attendee_timezones):", "function_n...
[ 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": "from datetime import datetime, timedelta\nimport pytz\n\ndef is_night_hour(local_time):\n \"\"\"\n Checks if a given time is within night hours (10 PM to 6 AM).\n...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00037166", "row_id": 37166, "seed_ids": "[219]" }
0.662196
Docs: Python310_37166
I
[ "is_night_time", "schedule_event" ]
2
[ [ "schedule_event", "is_night_time" ] ]
1
[]
false
[]
false
pytest
true
[]
true
284bae79f1783a5c499c9f7e498b0464502a5b0f
45c5088bbe01756b58968fc7705163df2b51f0ad
v1.0
instruct
Docs
Docs: Python310_37244_I
**Title: Context Variable Management in Asynchronous Tasks** #### Problem Statement You are tasked to implement a system that simulates processing multiple user requests in an asynchronous server environment, while ensuring each request's context remains isolated. You will use the `contextvars` module to achieve this...
import asyncio import contextvars session_id_var = contextvars.ContextVar("session_id") counter_var = contextvars.ContextVar("counter") session_var_entry = contextvars.ContextVar("session_var") def process_request(session_id: str, counter: int, session_var: str) -> dict: session_id_var.set(session_id) counter...
import asyncio from solution import process_request, main def test_process_request(): result1 = process_request("user1", 0, "data1") assert result1 == {"session_id": "user1", "counter": 1, "session_var": "data1"} result2 = process_request("user2", 0, "data2") assert result2 == {"session_id": "user...
[ { "docstring": null, "function_declaration": "def process_request(session_id, counter, session_var):", "function_name": "process_request", "parameter_list": "(session_id, counter, session_var)" } ]
[ 1, 0, 1, 1, 1, 1, 1, 0, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\n\nsession_id_var = contextvars.ContextVar(\"session_id\")\ncounter_var = contextvars.ContextVar(\"counter\")\nsession_var_entry = co...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00037244", "row_id": 37244, "seed_ids": "[392]" }
0.464922
Docs: Python310_37244
I
[ "process_request", "handle_request", "main" ]
3
[ [ "handle_request", "process_request" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2a88c2344e69ceac1bfdd8a5b0c0f68102d34f3d
0dc89ccd9b35f2782efaea55bffe53b7fb57bacf
v1.0
instruct
Docs
Docs: Python310_37256_I
Asynchronous Web Scraper You are required to write an asynchronous web scraper that can fetch HTML content from multiple URLs concurrently and process the content to extract all the hyperlink references (`<a href="">` tags). #### Requirements 1. **Input:** - A list of URLs. Each URL is a string. - Example: `["...
import asyncio from typing import List, Dict import aiohttp from bs4 import BeautifulSoup async def fetch_html(url: str) -> str: """ Fetches the HTML content of the given URL asynchronously. """ async with aiohttp.ClientSession() as session: try: async with session.get(url) as respo...
import pytest import asyncio from solution import fetch_all_links @pytest.mark.asyncio async def test_fetch_all_links_single_url(): urls = ["http://example.com"] result = await fetch_all_links(urls) assert "http://example.com" in result assert isinstance(result["http://example.com"], list) @pytest.mar...
[ { "docstring": "Extracts all hyperlink references from the given HTML content.", "function_declaration": "def extract_links(html):", "function_name": "extract_links", "parameter_list": "(html)" } ]
[ 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\nfrom typing import List, Dict\nimport aiohttp\nfrom bs4 import BeautifulSoup\n\nasync def fetch_html(url: str) -> str:\n \"\"\"\n Asynchronously f...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00037256", "row_id": 37256, "seed_ids": "[151]" }
0.730119
Docs: Python310_37256
I
[ "fetch_html", "extract_links", "fetch_all_links" ]
3
[ [ "fetch_all_links", "extract_links" ], [ "fetch_all_links", "fetch_html" ] ]
2
[]
false
[]
false
pytest
true
[ "aiohttp", "bs4" ]
false
9fcfeb375a6ac89f42f62fd267d71f5d2282c655
ab26d84702af4415dae349b552c5e25b806ccf67
v1.0
instruct
Docs
Docs: Pandas_37267_I
### Pandas Windowing Operations Assessment #### Objective To test the understanding and application of pandas windowing operations, including rolling, expanding, exponentially weighted windows, and custom window functions. #### Problem Statement You are provided with a dataset containing daily stock prices for multi...
import pandas as pd import numpy as np from pandas.api.indexers import BaseIndexer def load_data(filepath): df = pd.read_csv(filepath, parse_dates=['Date']) df.set_index('Date', inplace=True) return df def calculate_7day_rolling_mean(df): df['7Day_Rolling_Close_Mean'] = df.groupby('Company')['Close']....
import pytest import pandas as pd from io import StringIO from solution import (load_data, calculate_7day_rolling_mean, calculate_expanding_max, calculate_ewma, calculate_custom_volume_sum, calculate_5day_rolling_corr) csv_data = """ Date,Company,Open,Close,High,Low,Volume 2023-01-01,CompanyA,10...
[]
[ 0, 1, 0, 0, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport numpy as np\nfrom pandas.api.indexers import BaseIndexer\n\ndef load_data(filepath):\n \"\"\"\n Load stock prices data from a CSV file...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00037267", "row_id": 37267, "seed_ids": "[0]" }
0.706818
Docs: Pandas_37267
I
[ "load_data", "calculate_7day_rolling_mean", "calculate_expanding_max", "calculate_ewma", "calculate_custom_volume_sum", "calculate_5day_rolling_corr", "process_stock_data" ]
7
[ [ "process_stock_data", "calculate_5day_rolling_corr" ], [ "process_stock_data", "calculate_7day_rolling_mean" ], [ "process_stock_data", "calculate_custom_volume_sum" ], [ "process_stock_data", "calculate_ewma" ], [ "process_stock_data", "calculate_expanding_...
6
[]
false
[ "CustomIndexer" ]
true
pytest
true
[ "numpy", "pandas" ]
false
d6d686b1a04b0bf0bac11473ff5b5954103d5345
1269f7cdb3233f72f00299ae091b7181ed00441d
v1.0
instruct
Docs
Docs: Pytorch_37270_I
### PyTorch Distributed RPC: Implementing and Testing RRef Protocol #### Objective: To assess your understanding of PyTorch's distributed RPC framework, specifically the Remote Reference Protocol (RRef). You will need to implement a function to simulate creating, sharing, and managing RRefs in a distributed environmen...
import torch import torch.distributed.rpc as rpc from typing import List import time def run_worker(rank, world_size, owner_index, user_indices): rpc.init_rpc( name=f"worker{rank}", rank=rank, world_size=world_size ) if rank == owner_index: rref = rpc.RRef("This is an RRef ...
from solution import simulate_rref_protocol def test_rref_protocol_simple(): num_workers = 3 owner_index = 0 user_indices = [1, 2] simulate_rref_protocol(num_workers, owner_index, user_indices) # Testing Guarantee G1 & G2 implicitly through running without errors def test_rref_protocol_user_to_us...
[ { "docstring": null, "function_declaration": "def run_worker(rank, world_size, owner_index, user_indices):", "function_name": "run_worker", "parameter_list": "(rank, world_size, owner_index, user_indices)" }, { "docstring": null, "function_declaration": "def use_rref(owner_rref):", "...
[ 0, 0, 1, 0, 1, 0, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.distributed.rpc as rpc\nfrom torch.distributed.rpc import RRef\nfrom typing import List\nimport time\nfrom threading import Event\n\n# This f...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00037270", "row_id": 37270, "seed_ids": "[158]" }
0.413371
Docs: Pytorch_37270
I
[ "run_worker", "use_rref", "simulate_rref_protocol" ]
3
[ [ "run_worker", "use_rref" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
05d29427486381c87e06f16f97bc7c26de011f49
83c9ec769ef6b45315ead1d4d66918318c0c428a
v1.0
instruct
Docs
Docs: Python310_37272_I
## Coding Assessment Question ### Objective To gauge your understanding of email parsing functionalities in Python, specifically using the `email.parser` module's `Parser` and `FeedParser` APIs, including handling different types of email messages. ### Question **Scenario:** You have been tasked with developing a to...
from email.parser import BytesParser, BytesFeedParser from email.policy import default def parse_email_message_from_file(file_path): """ Parses an email message from a file and returns its components. Args: file_path (string): Path to a text file containing the complete email message. ...
import pytest import os from solution import parse_email_message_from_file, incremental_email_parser def test_parse_email_message_from_file(): email_content = """\ From: test@example.com To: recipient@example.com Subject: Test Email This is a test email message. """ file_path = "test_email.eml" with open(...
[ { "docstring": "Parses an email message from a file and returns its components.\n\nArgs:\n file_path (string): Path to a text file containing the complete email message.\n\nReturns:\n dict: Contains 'headers', 'body', 'is_multipart', and 'defects'.", "function_declaration": "def parse_email_message_fr...
[ 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import email\nfrom email.parser import BytesParser, BytesFeedParser\nfrom email.policy import default\n\ndef parse_email_message_from_file(file_path):\n \"\"\"\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00037272", "row_id": 37272, "seed_ids": "[262]" }
0.588084
Docs: Python310_37272
I
[ "parse_email_message_from_file", "get_email_body", "incremental_email_parser" ]
3
[ [ "incremental_email_parser", "get_email_body" ], [ "parse_email_message_from_file", "get_email_body" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b520f7b123485923d69eb3b01fc32d77db55e3d5
08b57937d95ba4e919331104ba74458c388b580b
v1.0
instruct
Docs
Docs: Python310_37339_I
### Advanced Coding Assessment: Serialization and Database Integration #### Objective Implement a Python program that demonstrates data persistence by using the `pickle` and `sqlite3` modules. The task is to create a program that stores and retrieves user data in a persistent manner. #### Problem Statement Design a P...
import pickle import sqlite3 import os def collect_user_data(): """ Collects user information from standard input and returns as a dictionary. """ user_data = {} user_data['name'] = input("Enter your name: ") user_data['age'] = int(input("Enter your age: ")) user_data['email'] = input("Ente...
import pytest import os import sqlite3 from solution import collect_user_data, serialize_data, store_data_in_db, retrieve_data_from_db, initialize_database def test_serialize_and_deserialize_data(): user_data = {'name': 'Alice', 'age': 30, 'email': 'alice@example.com', 'address': '123 Main St'} serialized_data...
[ { "docstring": "Collects user information from standard input and returns as a dictionary.", "function_declaration": "def collect_user_data():", "function_name": "collect_user_data", "parameter_list": "()" }, { "docstring": "Serializes the input dictionary using `pickle` and returns the seri...
[ 1, 1, 1, 0, 1, 0, 1, 0, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pickle\nimport sqlite3\n\ndef collect_user_data() -> dict:\n \"\"\"\n Collect user information from standard input.\n \"\"\"\n user_data = {}\n us...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00037339", "row_id": 37339, "seed_ids": "[140]" }
0.527898
Docs: Python310_37339
I
[ "collect_user_data", "serialize_data", "initialize_database", "store_data_in_db", "retrieve_data_from_db", "main" ]
6
[ [ "store_data_in_db", "initialize_database" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2f879cc50ccb5bd2b1c06695de369d5653c3fee9
1aa96d86c9eb1bf56123f203521253e6e119fa30
v1.0
instruct
Docs
Docs: Python310_37391_I
**Objective**: Demonstrate the ability to utilize the asyncio module to perform asynchronous programming, manage multiple tasks, handle inter-task communication using asyncio queues, and ensure proper synchronization using asyncio synchronization primitives. **Question**: You are tasked with simulating a simplified c...
import asyncio import random from typing import List async def fetch_data(url: str) -> str: # Simulate network delay await asyncio.sleep(random.uniform(0.5, 1.5)) return f"Data from {url}" async def worker(semaphore: asyncio.Semaphore, queue: asyncio.Queue, url: str): async with semaphore: dat...
import asyncio from solution import fetch_and_process async def test_fetch_and_process(): urls = [ "http://example.com/page1", "http://example.com/page2", "http://example.com/page3" ] max_concurrent_tasks = 2 await fetch_and_process(urls, max_concurrent_tasks) # Funct...
[]
[ 1, 1, 1, 1, 1, 0, 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\nfrom typing import List\n\nasync def fetch_url(url: str) -> str:\n # Simulating network delay of fetching data from url\n await asy...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00037391", "row_id": 37391, "seed_ids": "[360]" }
0.460568
Docs: Python310_37391
I
[ "fetch_data", "worker", "process_data", "fetch_and_process" ]
4
[ [ "fetch_and_process", "process_data" ], [ "fetch_and_process", "worker" ], [ "worker", "fetch_data" ] ]
3
[ "process_data" ]
false
[]
false
pytest
true
[]
true
5b724b0a319b6936f43f4592e4217f369de7933a
5ed322722a7aabaf948501a1355b79be857fa6a6
v1.0
instruct
Docs
Docs: Python310_37405_I
### Python Coding Assessment #### Question: Analyze Python Installation Paths and Configuration Variables You are tasked with writing a Python script that analyzes the current Python installation's configuration and paths to help in setting up a development environment or debugging installation issues. ### Objective...
import sysconfig def fetch_installed_paths(): """ Returns the default installation paths for the current platform. """ return sysconfig.get_paths() def fetch_configuration_variable(variable_name): """ Returns the value of a configuration variable. Args: variable_name (str): The co...
from solution import fetch_installed_paths, fetch_configuration_variable, is_python_source_build, analyze_environment def test_fetch_installed_paths(): paths = fetch_installed_paths() assert isinstance(paths, dict) # Checking if common keys exist in the paths dictionary assert 'stdlib' in paths ass...
[ { "docstring": "Returns the default installation paths for the current platform.", "function_declaration": "def fetch_installed_paths():", "function_name": "fetch_installed_paths", "parameter_list": "()" }, { "docstring": "Returns the value of a configuration variable.\n\nArgs:\nvariable_nam...
[ 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
8
easy
0.889
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sysconfig\n\ndef fetch_installed_paths():\n \"\"\"\n Returns the default installation paths for the current platform.\n \"\"\"\n return sysconfig.get...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00037405", "row_id": 37405, "seed_ids": "[102]" }
0.647321
Docs: Python310_37405
I
[ "fetch_installed_paths", "fetch_configuration_variable", "is_python_source_build", "analyze_environment" ]
4
[ [ "analyze_environment", "fetch_configuration_variable" ], [ "analyze_environment", "fetch_installed_paths" ], [ "analyze_environment", "is_python_source_build" ] ]
3
[]
false
[]
false
pytest
true
[]
true
5f051257c20112891aca113d6ae585658a58ad98
683dfbdb6ff2f3179676698da8aeffad2cc17942