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: Pytorch_17493_I
### Question: Tensor Views and Contiguity in PyTorch In this exercise, you will demonstrate your understanding of tensor views and contiguity in PyTorch by implementing a series of operations that optimize memory usage and evaluate tensor properties. #### Task: 1. Write a function `create_view` that takes a 2D tenso...
import torch def create_view(t, new_rows, new_cols): """ Create a view of tensor t with shape (new_rows, new_cols). """ return t.view(new_rows, new_cols) def is_contiguous(t): """ Check if the tensor t is contiguous. """ return t.is_contiguous() def make_contiguous(t): """ Ret...
from solution import create_view, is_contiguous, make_contiguous, process_tensor import torch def test_create_view(): t = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) expected = torch.tensor([[ 1, 2, 3, 4, 5,...
[ { "docstring": "Create a view of tensor t with shape (new_rows, new_cols).", "function_declaration": "def create_view(t, new_rows, new_cols):", "function_name": "create_view", "parameter_list": "(t, new_rows, new_cols)" }, { "docstring": "Check if the tensor t is contiguous.", "function_...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef create_view(t, new_rows, new_cols):\n \"\"\"\n Creates a view of tensor `t` with shape `(new_rows, new_cols)`.\n \"\"\"\n return t.view(...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00017493", "row_id": 17493, "seed_ids": "[65]" }
0.536517
Docs: Pytorch_17493
I
[ "create_view", "is_contiguous", "make_contiguous", "process_tensor" ]
4
[ [ "process_tensor", "create_view" ], [ "process_tensor", "is_contiguous" ], [ "process_tensor", "make_contiguous" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
1a2d230fd12fe4b1cfe521615b29e481609c5c48
c16bcd71ef40ef373d42df08845b56bfb29089df
v1.0
instruct
Docs
Docs: Scikit_17698_I
#### Objective: In this assignment, you are required to demonstrate your understanding of both validation and learning curves in the scikit-learn package. You will implement functions to plot these curves and analyze the results to diagnose a machine learning model. #### Problem Statement: Given a dataset, your task i...
import numpy as np from sklearn.svm import SVC from sklearn.model_selection import validation_curve, learning_curve from sklearn.datasets import load_iris from sklearn.utils import shuffle import matplotlib.pyplot as plt def plot_validation_curve(X_train, y_train, param_range): train_scores, valid_scores = validat...
from solution import plot_validation_curve, plot_learning_curve from sklearn.datasets import load_iris from sklearn.utils import shuffle import numpy as np def test_plot_validation_curve_execution(): X, y = load_iris(return_X_y=True) X, y = shuffle(X, y, random_state=0) param_range = np.logspace(-7, 3...
[ { "docstring": null, "function_declaration": "def plot_validation_curve(X_train, y_train, param_range):", "function_name": "plot_validation_curve", "parameter_list": "(X_train, y_train, param_range)" }, { "docstring": null, "function_declaration": "def plot_learning_curve(X_train, y_trai...
[ 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 numpy as np\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import validation_curve, learning_curve\nfrom sklearn.datasets import load_iris\nfrom skle...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017698", "row_id": 17698, "seed_ids": "[45]" }
0.603719
Docs: Scikit_17698
I
[ "plot_validation_curve", "plot_learning_curve", "analyze_model" ]
3
[ [ "analyze_model", "plot_learning_curve" ], [ "analyze_model", "plot_validation_curve" ] ]
2
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "sklearn" ]
false
1886c3c88a3da77e20ff328ef4eec63558969883
d2ebc0c22b78ecdead541063086fc80ff6c899ec
v1.0
instruct
Docs
Docs: Python310_17707_I
### Asynchronous News Fetcher **Objective**: You are tasked with implementing an asynchronous news fetcher that collects news articles from multiple sources concurrently. Some of the fetching operations are CPU-intensive and must be handled without blocking the event loop. **Requirements**: 1. Implement an asynchrono...
import asyncio from concurrent.futures import ThreadPoolExecutor import logging logging.basicConfig(level=logging.DEBUG) async def fetch_news_source(source_id): """ Asynchronously fetches news from a given source. Simulates a delay proportional to the source_id and returns a dummy article. """ try...
import pytest from solution import fetch_news_source, fetch_all_news, fetch_news_with_cpu_bound_task @pytest.mark.asyncio async def test_fetch_news_source(): result = await fetch_news_source(1) assert result["source_id"] == 1 assert "article" in result @pytest.mark.asyncio async def test_fetch_all_news():...
[ { "docstring": "Dummy CPU-bound task that squares the source_id.", "function_declaration": "def cpu_bound_task(source_id):", "function_name": "cpu_bound_task", "parameter_list": "(source_id)" }, { "docstring": null, "function_declaration": "def fetch_news_with_cpu_bound_task_wrapper(num_...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom concurrent.futures import ProcessPoolExecutor\n\nasync def fetch_news_source(source_id):\n \"\"\"\n Simulates fetching a news article from a ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017707", "row_id": 17707, "seed_ids": "[200]" }
0.438623
Docs: Python310_17707
I
[ "fetch_news_source", "fetch_all_news", "cpu_bound_task", "fetch_news_with_cpu_bound_task", "main", "fetch_news_with_cpu_bound_task_wrapper" ]
6
[ [ "fetch_all_news", "fetch_news_source" ], [ "fetch_news_with_cpu_bound_task", "cpu_bound_task" ], [ "fetch_news_with_cpu_bound_task_wrapper", "main" ] ]
3
[]
false
[]
false
pytest
true
[]
true
20f007a04034c28537b1b722fe9e8fc50a400b58
8861c474802309776814d9757c8c299777d03821
v1.0
instruct
Docs
Docs: Scikit_17740_I
#### Objective: Implement a `sklearn.linear_model.SGDClassifier` model to classify a provided dataset while optimizing for prediction latency and memory usage. You will need to utilize sparse matrix representations and configure scikit-learn’s settings to limit validation overhead and working memory. #### Input: 1. A ...
import numpy as np import scipy.sparse as sp from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score import time import sklearn def sparsity_ratio(X): return 1.0 - np.count_nonzero(X.toarray()) / float(X.shape[0] * X.shape[1]) def classify_and_optimize(X_train, y_train, X_test, y...
import numpy as np from scipy.sparse import csr_matrix from solution import classify_and_optimize, sparsity_ratio def test_sparsity_ratio(): dense_matrix = np.array([[1, 0, 0], [0, 0, 1], [1, 0, 0]]) sparse_matrix = csr_matrix(dense_matrix) ratio = sparsity_ratio(sparse_matrix) assert ratio == 0.666666...
[ { "docstring": null, "function_declaration": "def sparsity_ratio(X):", "function_name": "sparsity_ratio", "parameter_list": "(X)" }, { "docstring": null, "function_declaration": "def classify_and_optimize(X_train, y_train, X_test, y_test):", "function_name": "classify_and_optimize", ...
[ 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 numpy as np\nimport scipy.sparse as sp\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\nimport time\nimport sklearn\n...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017740", "row_id": 17740, "seed_ids": "[64]" }
0.544605
Docs: Scikit_17740
I
[ "sparsity_ratio", "classify_and_optimize" ]
2
[ [ "classify_and_optimize", "sparsity_ratio" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "scipy", "sklearn" ]
false
5efc867aa0a191b926167f2260029ec3ed4e92b7
7a551b1b4ed6a64d4fc33a3c3a25c88c664e960f
v1.0
instruct
Docs
Docs: Scikit_17745_I
Supervised Learning with Scikit-Learn **Objective**: This question aims to assess your ability to preprocess data, implement a supervised learning algorithm using scikit-learn, and evaluate the model's performance. **Scenario**: You are provided with a dataset containing information about various houses, including th...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score def preprocess_data(file_path): """ Loads and preprocesses th...
import pandas as pd import numpy as np from sklearn.datasets import make_regression from io import StringIO from solution import preprocess_data, train_and_evaluate def create_mock_csv(): """ Creates a mock CSV file-like object for testing. """ X, y = make_regression(n_samples=100, n_features=8, noise=...
[ { "docstring": "Loads and preprocesses the data.", "function_declaration": "def preprocess_data(file_path):", "function_name": "preprocess_data", "parameter_list": "(file_path)" }, { "docstring": "Trains and evaluates a regression model on the provided dataset.", "function_declaration": ...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LinearRegr...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00017745", "row_id": 17745, "seed_ids": "[1]" }
0.619446
Docs: Scikit_17745
I
[ "preprocess_data", "train_and_evaluate" ]
2
[ [ "train_and_evaluate", "preprocess_data" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "pandas", "sklearn" ]
false
625298e28f56944eced9cfde0b587c2a11fe270e
c02e6fb3a57a4d9200c0ffde19e1ab451bf2c443
v1.0
instruct
Docs
Docs: Python310_17765_I
### Mini Chat Server using `asyncio` Streams #### Objective: Design and implement a mini chat server using `asyncio` streams. The server should be able to handle multiple clients simultaneously, broadcast messages from any client to all connected clients, and properly manage connection resources. #### Instructions: 1...
import asyncio clients = [] async def handle_client(reader, writer): addr = writer.get_extra_info('peername') clients.append(writer) print(f"{addr} is connected") try: while True: data = await reader.read(100) message = data.decode() if not message: ...
import asyncio import pytest from sys import platform from solution import start_chat_server async def client_dummy(host, port, message): reader, writer = await asyncio.open_connection(host, port) writer.write(message.encode()) await writer.drain() data = await reader.read(100) received_message = d...
[]
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import asyncio\n\nconnected_clients = []\n\nasync def handle_client(reader, writer):\n client_address = writer.get_extra_info('peername')\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017765", "row_id": 17765, "seed_ids": "[182]" }
0.650903
Docs: Python310_17765
I
[ "handle_client", "broadcast", "start_chat_server" ]
3
[ [ "handle_client", "broadcast" ], [ "start_chat_server", "handle_client" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1bfa5a1429fc9ec5b597c45d046cbeb92342b08c
142f1d669c28639be135ec2a17983e8fb29d5af6
v1.0
instruct
Docs
Docs: Python310_17778_I
**Problem Statement: Asynchronous Task Manager** You are tasked with creating an asynchronous task manager using Python's asyncio module. The task manager should be able to handle multiple types of tasks concurrently, ensure certain tasks do not block or cancel others, and handle timeouts effectively. **Requirements:...
import asyncio import time async def task_1(seconds: int, name: str) -> str: await asyncio.sleep(seconds) return f"Task {name} completed after {seconds} seconds." async def task_2(name: str) -> str: for i in range(1000): if i % 100 == 0: await asyncio.sleep(0) return f"Task {name} ...
import pytest import asyncio from solution import task_1, task_2, task_3, task_manager @pytest.mark.asyncio async def test_task_1(): result = await task_1(1, 'T1-Test') assert "Task T1-Test completed after 1 seconds." in result @pytest.mark.asyncio async def test_task_2(): result = await task_2('T2-Test')...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport time\n\nasync def task_1(seconds: int, name: str) -> str:\n print(f\"{name} starting at {time.strftime('%X')}\")\n await asyncio.sleep(seco...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017778", "row_id": 17778, "seed_ids": "[317]" }
0.649493
Docs: Python310_17778
I
[ "task_1", "task_2", "task_3", "task_manager" ]
4
[ [ "task_manager", "task_1" ], [ "task_manager", "task_2" ], [ "task_manager", "task_3" ] ]
3
[]
false
[]
false
pytest
true
[]
true
82be85152a4f04435998315df1d8c2e44e5765d5
14e5cc09c8660c67816a057169f572f0f9dc15d5
v1.0
instruct
Docs
Docs: Pytorch_17783_I
### Sparse Tensors in PyTorch: Challenge Task As neural networks become large, models with sparse connections and weights often arise, especially in graph neural networks or pruned networks. Efficiently handling these sparse structures can significantly reduce computation time and memory usage. In this task, you are ...
import torch def convert_to_sparse(input_tensor: torch.Tensor, layout: str) -> torch.Tensor: """ Converts a given dense tensor to the specified sparse format. Args: - input_tensor (torch.Tensor): The dense tensor to convert. - layout (str): The sparse format ('coo', 'csr', 'csc', 'bsr', 'bsc'). ...
import pytest import torch from solution import convert_to_sparse, sparse_matrix_multiplication, sparse_tensor_operations def test_convert_to_sparse_coo(): dense_tensor = torch.tensor([[0, 2], [3, 0]], dtype=torch.float32) sparse_tensor = convert_to_sparse(dense_tensor, 'coo') assert sparse_tensor.layout =...
[ { "docstring": "Converts a given dense tensor to the specified sparse format.\n\nArgs:\n- input_tensor (torch.Tensor): The dense tensor to convert.\n- layout (str): The sparse format ('coo', 'csr', 'csc', 'bsr', 'bsc').\n\nReturns:\n- torch.Tensor: The tensor in the specified sparse format.", "function_decl...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef convert_to_sparse(input_tensor: torch.Tensor, layout: str) -> torch.Tensor:\n \"\"\"\n Converts a given dense tensor to the specified sparse f...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017783", "row_id": 17783, "seed_ids": "[10]" }
0.496185
Docs: Pytorch_17783
I
[ "convert_to_sparse", "sparse_matrix_multiplication", "sparse_tensor_operations" ]
3
[ [ "sparse_matrix_multiplication", "convert_to_sparse" ], [ "sparse_tensor_operations", "convert_to_sparse" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
c50cba096c58832202f89d7dc1652ef26655566b
22d244d67dcb7fd82599bdf54c32290917b6f75c
v1.0
instruct
Docs
Docs: Python310_17815_I
#### Objective Your task is to create a utility that benchmarks different sorting algorithms using the `timeit` module. This will test your understanding of `timeit` and ability to write code that leverages this module to compare performance accurately. #### Requirements and Constraints: 1. **Implement at least three ...
import random import timeit # Sorting Algorithms def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def merge_sort(arr): if len(arr) > 1: mid = l...
from solution import insertion_sort, merge_sort, quick_sort_wrapper import random def test_insertion_sort(): arr = generate_specific_random_list() sorted_arr = sorted(arr) insertion_sort(arr) assert arr == sorted_arr def test_merge_sort(): arr = generate_specific_random_list() sorted_arr = sor...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr):", "function_name": "insertion_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "doc...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport timeit\n\n# Sorting Algorithms\ndef insertion_sort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017815", "row_id": 17815, "seed_ids": "[328]" }
0.536087
Docs: Python310_17815
I
[ "insertion_sort", "merge_sort", "quick_sort", "quick_sort_wrapper", "generate_random_list", "benchmark_sorting_algorithms" ]
6
[ [ "quick_sort_wrapper", "quick_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
39e9e38d49af8c1f2f21ee85b49c0cd0d45fb922
5e5b7f0031a421482ada7a1d83308fb0d219ae06
v1.0
instruct
Docs
Docs: Python310_17871_I
#### Objective: You are required to create a Python script using the `random` module to simulate drawing balls from a bag. The bag contains balls of different colors, and you will perform various random operations to demonstrate your understanding of the module's functionalities. #### Task: 1. **Define a function `ini...
import random def initialize_bag(ball_counts: dict) -> list: """ Initialize the bag of balls. Parameters: ball_counts (dict): A dictionary where keys are colors (str) and values are counts (int) of balls. Returns: list: A list where each element is a ball (represented by its color as a string...
from solution import initialize_bag, draw_balls, shuffle_bag, generate_statistics def test_initialize_bag(): assert initialize_bag({'red': 5, 'blue': 3, 'green': 2}) == ['red']*5 + ['blue']*3 + ['green']*2 def test_draw_balls(): bag = ['red', 'red', 'blue', 'green'] drawn = draw_balls(bag, 2) assert l...
[ { "docstring": "Initialize the bag of balls.\n\nParameters:\nball_counts (dict): A dictionary where keys are colors (str) and values are counts (int) of balls.\n\nReturns:\nlist: A list where each element is a ball (represented by its color as a string) based on the input counts.", "function_declaration": "...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom collections import Counter\n\ndef initialize_bag(ball_counts: dict) -> list:\n \"\"\"\n Initialize the bag of balls.\n\n Parameters:\n b...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017871", "row_id": 17871, "seed_ids": "[119]" }
0.596493
Docs: Python310_17871
I
[ "initialize_bag", "draw_balls", "shuffle_bag", "generate_statistics" ]
4
[ [ "generate_statistics", "draw_balls" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4b2f679c6ff95269de68b75bc180ea91ee41c973
cc8531b146c9ce4b5d34d3348456c6354b6ebd1b
v1.0
instruct
Docs
Docs: Python310_17901_I
**Objective:** Implement a task processing system using asyncio queues where multiple workers process tasks concurrently and handle priorities of tasks. **Problem Statement:** You are required to implement an asynchronous task processing system using `asyncio.PriorityQueue`. Your system should handle tasks with diff...
import asyncio from typing import List, Tuple async def worker(queue: asyncio.PriorityQueue, results: List[str]): while True: try: priority, task = await queue.get() except asyncio.CancelledError: break results.append(task) await asyncio.sleep(0.1) # Simulat...
import pytest import asyncio from solution import process_tasks @pytest.mark.asyncio async def test_process_tasks_single_worker(): tasks = [(1, 'Task1'), (3, 'Task3'), (2, 'Task2')] num_workers = 1 result = await process_tasks(tasks, num_workers) assert result == ['Task1', 'Task2', 'Task3'] @pytest.ma...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def worker(queue: asyncio.PriorityQueue, results: List[str]):\n while True:\n try:\n priori...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017901", "row_id": 17901, "seed_ids": "[111]" }
0.601292
Docs: Python310_17901
I
[ "worker", "process_tasks" ]
2
[ [ "process_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
69f5321b0a660a500a19cdec44daaa5c8c7a4144
91d6249e906f9e141dd93ee6aba31ebfe485c0e6
v1.0
instruct
Docs
Docs: Scikit_17925_I
### Coding Assessment: Implementing an Out-of-Core Learning Pipeline #### Objective The task is to implement an out-of-core learning pipeline using scikit-learn, demonstrating your understanding of streaming instances, feature extraction, and incremental learning. #### Problem Statement You are given a large dataset ...
import os import pandas as pd from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier def data_streamer(folder_path, batch_size): """ Generator that yields mini-batches from CSV files in the folder. :param folder_path: Path to the folder containing ...
import os import pandas as pd import pytest from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from solution import data_streamer, build_out_of_core_pipeline # Create temporary directory and CSV files for testing @pytest.fixture(scope="module") def prepare_test...
[ { "docstring": "Generator that yields mini-batches from CSV files in the folder.\n\n:param folder_path: Path to the folder containing CSV files.\n:param batch_size: Number of rows to yield per mini-batch.", "function_declaration": "def data_streamer(folder_path, batch_size):", "function_name": "data_str...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport pandas as pd\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\n\ndef data_streamer(folde...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00017925", "row_id": 17925, "seed_ids": "[63]" }
0.517741
Docs: Scikit_17925
I
[ "data_streamer", "build_out_of_core_pipeline" ]
2
[ [ "build_out_of_core_pipeline", "data_streamer" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas", "sklearn" ]
false
7c2e82cd96f2eed11d519e46fc78c860e6111571
cc280eb9cece4ac44637f0f9ac12e76d3890fbbe
v1.0
instruct
Docs
Docs: Python310_17999_I
## Coding Assessment Question ### Objective Implement a function that encodes a list of strings into various Unicode codecs and then decodes them, storing the results in a dictionary. ### Task You are tasked with writing two functions: 1. `encode_strings(strings: List[str], codec: str) -> List[bytes]`: This function...
from typing import List, Dict def encode_strings(strings: List[str], codec: str) -> List[bytes]: """ Encode a list of strings using the specified codec. """ try: return [s.encode(codec) for s in strings] except Exception as e: raise ValueError(f"Encoding failed: {e}") def decode_st...
from solution import encode_strings, decode_strings, process_strings def test_encode_strings_utf8(): strings = ["hello", "world"] assert encode_strings(strings, "utf-8") == [b'hello', b'world'] def test_encode_strings_utf16(): strings = ["hello", "world"] encoded = encode_strings(strings, "utf-16") ...
[ { "docstring": "Encode a list of strings using the specified codec.", "function_declaration": "def encode_strings(strings, codec):", "function_name": "encode_strings", "parameter_list": "(strings, codec)" }, { "docstring": "Decode a list of encoded bytes using the specified codec.", "fun...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Dict\n\ndef encode_strings(strings: List[str], codec: str) -> List[bytes]:\n \"\"\"\n Encodes a list of strings using the specified codec...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017999", "row_id": 17999, "seed_ids": "[5]" }
0.586805
Docs: Python310_17999
I
[ "encode_strings", "decode_strings", "process_strings" ]
3
[ [ "process_strings", "decode_strings" ], [ "process_strings", "encode_strings" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f590b87c61a149949d28e186aaea3c8d8322fa14
ffb695dc38c70ecf4e732422490b5a1ea43c957a
v1.0
instruct
Docs
Docs: Python310_18003_I
### Context Management with Python's `contextlib` #### Objective: Implement a custom context manager using `contextlib`'s `contextmanager` decorator that maintains a stack of resources and ensures their proper release. Additionally, implement a mechanism that supports conditional resource acquisition and cleanup. ###...
from contextlib import contextmanager, ExitStack @contextmanager def resource_manager(resource_name): """ Context manager that acquires and releases a resource. Args: resource_name (str): The name of the resource to acquire. Yields: str: The name of the acquired resource. """ ...
# To properly test the solution, create a test file named test_solution.py with the following code: from solution import resource_manager, conditional_resource_manager import pytest def test_resource_manager(): with resource_manager("test_resource") as resource: assert resource == "test_resource" def test...
[ { "docstring": "Context manager that acquires and releases a resource.\n\nArgs:\nresource_name (str): The name of the resource to acquire.\n\nYields:\nstr: The name of the acquired resource.", "function_declaration": "def resource_manager(resource_name):", "function_name": "resource_manager", "param...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from contextlib import contextmanager, ExitStack\n\n@contextmanager\ndef resource_manager(resource_name):\n \"\"\"\n A context manager that acquires and releases ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018003", "row_id": 18003, "seed_ids": "[177]" }
0.366082
Docs: Python310_18003
I
[ "resource_manager", "conditional_resource_manager" ]
2
[ [ "conditional_resource_manager", "resource_manager" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b79ad4fca34240fb1c32de9aa9c18e9a1627e25e
c13e8d0318cc2fa70a0832e63437ec0db56c6f44
v1.0
instruct
Docs
Docs: Seaborn_18056_I
#### Objective Assess your understanding of the Seaborn library, specifically the `sns.pointplot` functionality, by creating and customizing point plots with multiple layers of complexity. #### Dataset We will use the `penguins` dataset available in the Seaborn library. Ensure you have the necessary library and datase...
import seaborn as sns import matplotlib.pyplot as plt import numpy as np # Load the dataset penguins = sns.load_dataset("penguins") # Function to calculate the 95% confidence interval def ci_95(data): return 1.96 * np.std(data) / np.sqrt(len(data)) # Create the point plot with enhancements def create_custom_poin...
def test_create_custom_pointplot(): # Testing if the function runs without errors try: create_custom_pointplot() assert True # If this point is reached, test is successful except Exception as e: assert False, f"create_custom_pointplot raised an exception: {e}" # As the function pri...
[ { "docstring": null, "function_declaration": "def ci_95(data):", "function_name": "ci_95", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def create_custom_pointplot():", "function_name": "create_custom_pointplot", "parameter_list": "()" } ]
[ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\n# Load the penguins dataset\npenguins = sns.load_dataset(\"penguins...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00018056", "row_id": 18056, "seed_ids": "[45]" }
0.636866
Docs: Seaborn_18056
I
[ "ci_95", "create_custom_pointplot" ]
2
[ [ "create_custom_pointplot", "ci_95" ] ]
1
[]
false
[]
false
pytest
false
[ "matplotlib", "numpy", "seaborn" ]
false
bdfaa6b787562df144d414235fe89cf1ccad755a
dff5b7a152d94328fdd1a936f58dd1e6e2a22c39
v1.0
instruct
Docs
Docs: Python310_18105_I
**Concurrent File Processing** You are tasked with processing multiple large text files concurrently to generate statistical data about the frequency of words in these files. To achieve optimal performance in this task, you will need to use the `concurrent.futures` module. Specifically, you will use the `ThreadPoolExe...
import os from typing import List, Dict from collections import defaultdict from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor def count_words_in_file(file_path: str) -> Dict[str, int]: word_count = defaultdict(int) try: with open(file_path, 'r', encoding='utf-8') as file: ...
import os import pytest from solution import concurrent_word_frequency @pytest.fixture def create_test_files(): file_contents = { 'file1.txt': "apple banana apple", 'file2.txt': "banana orange", 'file3.txt': "apple orange banana" } for filename, content in file_contents.items(): ...
[]
[ 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 concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nfrom collections import defaultdict\nfrom typing import List, Dict\n\ndef count_words...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00018105", "row_id": 18105, "seed_ids": "[206]" }
0.643085
Docs: Python310_18105
I
[ "count_words_in_file", "merge_word_counts", "concurrent_word_frequency" ]
3
[ [ "concurrent_word_frequency", "count_words_in_file" ], [ "concurrent_word_frequency", "merge_word_counts" ] ]
2
[]
false
[]
false
pytest
true
[]
true
707db89db19d06995219dfd3fbdebe39dba62304
95b1d519fb8a88e392db893e4a2dad9b5ad75b45
v1.0
instruct
Docs
Docs: Pytorch_18140_I
You are given a machine learning problem where you need to compute the gradient of a loss function with respect to the model parameters for each sample in the batch efficiently. ### Task Implement a function `compute_batch_gradients` that takes in a dataset and model weights, and returns the per-sample gradients of t...
import torch from torch.func import grad, vmap def model(weights, feature_vec): """ Simple linear model with ReLU activation """ return torch.nn.functional.relu(feature_vec.matmul(weights)) def compute_loss(weights, example, target): """ Computes Mean Squared Error (MSE) loss between model pre...
import torch from solution import model, compute_loss, compute_batch_gradients def test_model(): weights = torch.tensor([0.5, -1.0]) feature_vec = torch.tensor([2.0, 3.0]) result = model(weights, feature_vec) assert result == torch.tensor(0.0) # ReLU should zero out the negative value def test_comput...
[ { "docstring": "Simple linear model with ReLU activation", "function_declaration": "def model(weights, feature_vec):", "function_name": "model", "parameter_list": "(weights, feature_vec)" }, { "docstring": "Computes Mean Squared Error (MSE) loss between model prediction and target", "fun...
[ 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.func import vmap, grad\n\ndef model(weights, feature_vec):\n \"\"\"\n Linear model with ReLU activation\n \"\"\"\n assert feature_v...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018140", "row_id": 18140, "seed_ids": "[69]" }
0.515017
Docs: Pytorch_18140
I
[ "model", "compute_loss", "compute_batch_gradients" ]
3
[ [ "compute_batch_gradients", "compute_loss" ], [ "compute_loss", "model" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
e3a769c4802491c9c133ac96354e9d1abe548eb6
7ce8d90cb83568aac222a3e6ec6bcad33a315139
v1.0
instruct
Docs
Docs: Python310_18149_I
### Asynchronous Programming with Asyncio In this coding exercise, demonstrate your understanding of Python's asyncio package by implementing an asynchronous task manager. Your task manager will manage multiple tasks with varying completion times, handle timeouts and cancellations, and gather results. ### Task: 1. Wr...
import asyncio async def async_task(name: str, duration: int): """ Asynchronous task that waits for a given duration and handles timeout. """ print(f"{name} started") try: await asyncio.sleep(duration) print(f"{name} completed") return name except asyncio.CancelledError:...
import asyncio from solution import async_task, task_manager async def test_async_task(): result = await async_task("test_task", 1) assert result == "test_task" def test_task_manager(): tasks = [('Task1', 3), ('Task2', 7), ('Task3', 2)] results = asyncio.run(task_manager(tasks)) assert results == ...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def async_task(name: str, duration: int):\n print(f\"{name} started\")\n try:\n await asyncio.sleep(duration)\n print(f\"{na...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00018149", "row_id": 18149, "seed_ids": "[317]" }
0.662887
Docs: Python310_18149
I
[ "async_task", "task_manager" ]
2
[ [ "task_manager", "async_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b8e3d5efc27225848e8b75958ce363d8945b5c80
fc55a867135d6601371e60119614c034b8d32e62
v1.0
instruct
Docs
Docs: Python310_18166_I
### Coding Challenge: Custom Codec Implementation The provided documentation describes various functions related to codec registration, codec lookup, and error handling. In this challenge, you will demonstrate your understanding of these concepts by implementing a custom codec and encoding/decoding operations in simul...
import codecs class ReverseCodec(codecs.Codec): def encode(self, input, errors='strict'): try: if not isinstance(input, str): raise TypeError('input should be a string') return (input[::-1], len(input)) except Exception as e: return ('?', len(inpu...
from solution import perform_operations, register_reverse_codec, unregister_reverse_codec, encode_string, decode_string def test_perform_operations(): assert perform_operations() == "hello world" def test_encoding_decoding(): register_reverse_codec() # Test encoding encoded = encode_string("hello...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import codecs\n\nclass ReverseCodec(codecs.Codec):\n\n def encode(self, input, errors='strict'):\n if not isinstance(input, str):\n raise TypeError...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018166", "row_id": 18166, "seed_ids": "[47]" }
0.618886
Docs: Python310_18166
I
[ "reverse_codec", "register_reverse_codec", "unregister_reverse_codec", "encode_string", "decode_string", "perform_operations" ]
6
[ [ "perform_operations", "decode_string" ], [ "perform_operations", "encode_string" ], [ "perform_operations", "register_reverse_codec" ], [ "perform_operations", "unregister_reverse_codec" ], [ "register_reverse_codec", "reverse_codec" ], [ "unregister...
6
[]
false
[ "ReverseCodec" ]
true
pytest
true
[]
true
1694df9b2987a777ff65c85ab6eced1951cc0459
91818c2d68a914c82a8c24ed88d0b2e6bad5b41d
v1.0
instruct
Docs
Docs: Python310_18228_I
You are tasked with implementing a utility that reads data from multiple URLs and processes the data concurrently. To ensure proper resource management, you need to use asynchronous context managers. ### Requirements 1. **Context Manager**: Implement an asynchronous context manager to handle acquiring and releasing ne...
import asyncio from contextlib import AbstractAsyncContextManager class AsyncNetworkManager(AbstractAsyncContextManager): async def __aenter__(self): print("Acquiring connection") await asyncio.sleep(1) # Simulate network delay return self async def __aexit__(self, exc_type, exc, tb):...
import pytest import asyncio from solution import AsyncNetworkManager, fetch_data, process_urls @pytest.mark.asyncio async def test_async_network_manager(): async with AsyncNetworkManager() as manager: assert isinstance(manager, AsyncNetworkManager) @pytest.mark.asyncio async def test_fetch_data(): ur...
[]
[ 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 contextlib import AbstractAsyncContextManager\n\nclass AsyncNetworkManager(AbstractAsyncContextManager):\n async def __aenter__(self):\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00018228", "row_id": 18228, "seed_ids": "[177]" }
0.495349
Docs: Python310_18228
I
[ "fetch_data", "process_urls" ]
2
[ [ "process_urls", "fetch_data" ] ]
1
[]
false
[ "AsyncNetworkManager" ]
true
pytest
true
[]
true
acadbfcebd2d59a6abb80326bf6c25b098f8d47b
e5c6d31f374858a6673c42b88fc61baccc62dd09
v1.0
instruct
Docs
Docs: Python310_18246_I
### Exception Handling and Custom Exception Creation in Python In this exercise, you are required to demonstrate your understanding of Python's exception handling mechanisms and custom exception creation. You will create a set of functions that simulate a simple banking system, handle exceptions properly, and create c...
class InsufficientFundsError(Exception): pass class AccountNotFoundError(Exception): pass def create_account(account_data, account_id, initial_balance): if initial_balance < 0: raise ValueError("Initial balance cannot be negative!") account_data[account_id] = initial_balance def get_balance(a...
from solution import create_account, get_balance, deposit, withdraw, transfer, InsufficientFundsError, AccountNotFoundError def test_create_account(): account_data = {} create_account(account_data, 'acc1', 500) assert account_data['acc1'] == 500 def test_create_account_negative_initial_balance(): acco...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class InsufficientFundsError(Exception):\n pass\n\nclass AccountNotFoundError(Exception):\n pass\n\ndef create_account(account_data, account_id, initial_balance):...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018246", "row_id": 18246, "seed_ids": "[256]" }
0.576207
Docs: Python310_18246
I
[ "create_account", "get_balance", "deposit", "withdraw", "transfer" ]
5
[ [ "transfer", "deposit" ], [ "transfer", "withdraw" ] ]
2
[]
false
[ "InsufficientFundsError", "AccountNotFoundError" ]
true
pytest
true
[]
true
5a7ef89ded18ea273170f1393feff25af807d215
f6a9df5a7efd34c30f7fe772ed4dfadf053d0c16
v1.0
instruct
Docs
Docs: Python310_18265_I
**Title**: Implementing and Managing Cached Functions with `functools` **Objective**: Demonstrate your understanding of caching mechanisms provided by the `functools` module by implementing a project which uses `@functools.lru_cache` and `@functools.cache` decorators. **Problem Statement**: **Part 1**: Implement a ...
import functools @functools.lru_cache(maxsize=100) def fib_lru(n: int) -> int: """ Returns the nth Fibonacci number using LRU cache with a max size of 100. """ if n < 2: return n return fib_lru(n - 1) + fib_lru(n - 2) @functools.cache def factorial_cache(n: int) -> int: """ Returns...
from solution import fib_lru, factorial_cache, evaluate_cache_performance def test_fib_lru(): assert fib_lru(0) == 0 assert fib_lru(1) == 1 assert fib_lru(10) == 55 assert fib_lru(20) == 6765 assert fib_lru(30) == 832040 def test_factorial_cache(): assert factorial_cache(0) == 1 assert fac...
[ { "docstring": "Returns the nth Fibonacci number using LRU cache with a max size of 100.", "function_declaration": "def fib_lru(n):", "function_name": "fib_lru", "parameter_list": "(n)" }, { "docstring": "Returns the factorial of n using a simple cache.", "function_declaration": "def fac...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import functools\n\n# Part 1: Implement Fibonacci function with LRU cache\n@functools.lru_cache(maxsize=100)\ndef fib_lru(n):\n \"\"\"\n Returns the nth Fibonacci...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018265", "row_id": 18265, "seed_ids": "[236]" }
0.557841
Docs: Python310_18265
I
[ "fib_lru", "factorial_cache", "evaluate_cache_performance" ]
3
[ [ "evaluate_cache_performance", "factorial_cache" ], [ "evaluate_cache_performance", "fib_lru" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1a91c92660556b1659fc12ae786c5e0ec60e442b
b947095d1c115975f38a38bfec4a1171a4f954e2
v1.0
instruct
Docs
Docs: Python310_18270_I
### Coding Assessment **Objective**: Demonstrate your understanding of Python's asyncio module by implementing a task that performs multiple concurrent operations and manages task synchronization and timeouts. **Problem Statement**: You are required to implement an asynchronous simulation of a content delivery netwo...
import asyncio async def fetch_piece(server_id: int, delay: int) -> str: """ Simulates fetching a piece of data from a server. Args: - server_id (int): The ID of the server to fetch from. - delay (int): The simulated time in seconds it takes to fetch the data. Returns: - str: The piece of...
import asyncio import pytest from solution import fetch_piece, combine_results @pytest.mark.asyncio async def test_fetch_piece(): result = await fetch_piece(1, 1) assert result == "Data from server 1" @pytest.mark.asyncio async def test_combine_results_all_within_timeout(): servers = [(1, 1), (2, 2), (3, ...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def fetch_piece(server_id: int, delay: int) -> str:\n \"\"\"\n Simulates fetching a piece of data from a server.\n\n Args:\n - serve...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00018270", "row_id": 18270, "seed_ids": "[360]" }
0.515322
Docs: Python310_18270
I
[ "fetch_piece", "combine_results" ]
2
[ [ "combine_results", "fetch_piece" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bfc1a3be13302ad1823e510085f6e7fac545e9e8
6554d20f75f6916945da990bbc2808f62c486cf8
v1.0
instruct
Docs
Docs: Python310_18272_I
You are tasked with writing a Python script that simulates the process of integrating tracing functionality in a simplified, educational version of CPython. The goal is to understand how tracing of function calls and their returns could be implemented. **Objective**: Implement a tracing mechanism for Python functions ...
import inspect import os call_depth = 0 def trace(func): def wrapper(*args, **kwargs): global call_depth # Get calling frame for getting filename and line number frame = inspect.currentframe().f_back file_name = os.path.basename(frame.f_code.co_filename) line_no = ...
from solution import start, function_1, function_2, function_3 def test_trace_output(capsys): start() captured = capsys.readouterr() output_lines = captured.out.strip().split("\n") assert "Entering start in" in output_lines[0] assert "Entering function_1 in" in output_lines[1] assert "Ente...
[ { "docstring": null, "function_declaration": "def trace(func):", "function_name": "trace", "parameter_list": "(func)" }, { "docstring": null, "function_declaration": "def start():", "function_name": "start", "parameter_list": "()" }, { "docstring": null, "function_dec...
[ 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 inspect\nimport os\n\ncall_depth = 0\n\ndef trace(func):\n def wrapper(*args, **kwargs):\n global call_depth\n \n # Get calling frame for...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00018272", "row_id": 18272, "seed_ids": "[79]" }
0.602662
Docs: Python310_18272
I
[ "trace", "start", "function_1", "function_2", "function_3" ]
5
[ [ "function_1", "function_3" ], [ "function_2", "function_1" ], [ "start", "function_1" ], [ "start", "function_2" ] ]
4
[]
false
[]
false
pytest
true
[]
true
28dad31bd64759071554e58ecf870ca456e25555
308abb95f160090d8b77a336684d76107707e338
v1.0
instruct
Docs
Docs: Python310_18277_I
**Objective:** The goal of this question is to assess your understanding of handling annotations in Python 3.10. You will be required to implement various functions that adhere to best practices for accessing and managing the `__annotations__` attribute. #### Problem Statement Implement a function `validate_and_get_a...
import inspect def validate_and_get_annotations(obj): """ Return the annotations of an object if they exist, or an empty dictionary if they don't. :param obj: Any Python object such as a function, class, or module. :return: A dictionary containing annotation names and types. """ try: re...
from solution import validate_and_get_annotations, unstringize_annotations def test_validate_and_get_annotations_no_annotations(): def func_without_annotations(): pass assert validate_and_get_annotations(func_without_annotations) == {} def test_validate_and_get_annotations_with_annotations(): def...
[ { "docstring": "Return the annotations of an object if they exist, or an empty dictionary if they don't.\n:param obj: Any Python object such as a function, class, or module.\n:return: A dictionary containing annotation names and types.", "function_declaration": "def validate_and_get_annotations(obj):", ...
[ 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 inspect\n\ndef validate_and_get_annotations(obj):\n \"\"\"\n Return the annotations of an object if they exist, or an empty dictionary if they don't.\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00018277", "row_id": 18277, "seed_ids": "[66]" }
0.489096
Docs: Python310_18277
I
[ "validate_and_get_annotations", "unstringize_annotations" ]
2
[ [ "unstringize_annotations", "validate_and_get_annotations" ] ]
1
[]
false
[]
false
pytest
true
[]
true
26ec3d5208fb6dd48dd1033fe71054ccb71ac4d9
22a2c0ff945349704feb0b431a2549fad38ac49a
v1.0
instruct
Docs
Docs: Pytorch_18284_I
### Question: Signal Processing with PyTorch Windows You are given a 1-dimensional PyTorch tensor representing a signal. Your task is to apply different window functions from the `torch.signal.windows` module to this signal and analyze the results. Specifically, you need to perform the following steps: 1. Implement a...
import torch from typing import Any, Tuple def apply_window(signal: torch.Tensor, window_type: str, **kwargs) -> torch.Tensor: """ Applies a specified window function to the input signal. Parameters: signal (torch.Tensor): The input 1-dimensional signal tensor. window_type (str): The t...
from solution import apply_window, analyze_window_effect import torch import pytest def test_apply_window_invalid_type(): signal = torch.ones(10) with pytest.raises(ValueError): apply_window(signal, "invalid") def test_apply_window_hamming(): signal = torch.ones(10) windowed_signal = apply...
[ { "docstring": "Applies a specified window function to the input signal.\n\nParameters:\n signal (torch.Tensor): The input 1-dimensional signal tensor.\n window_type (str): The type of window function to apply.\n kwargs (Any): Additional arguments required for specific window functions.\n\nReturns:\n ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.signal.windows as windows\nfrom typing import Tuple\n\ndef apply_window(signal: torch.Tensor, window_type: str, **kwargs) -> torch.Tensor:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00018284", "row_id": 18284, "seed_ids": "[58]" }
0.48651
Docs: Pytorch_18284
I
[ "apply_window", "analyze_window_effect" ]
2
[ [ "analyze_window_effect", "apply_window" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
3267e82402a5083e0be83116447ad1a7248ef2d1
7c1bc9902d57a3f69baa08c5197f217b7e982fe5
v1.0
instruct
Docs
Docs: Python310_18301_I
You are required to implement a Python function that fetches the HTML content from a list of URLs, handles HTTP basic authentication if needed, and returns the clean text (no HTML tags) from the fetched content. You will use the `urllib.request` module for these operations. ### Function Signature: ```python def fetch_...
import urllib.request import urllib.error from urllib.request import HTTPBasicAuthHandler, HTTPPasswordMgrWithDefaultRealm, build_opener, install_opener, urlopen from html.parser import HTMLParser # Custom HTMLParser to extract text from HTML class MyHTMLParser(HTMLParser): def __init__(self): super().__in...
import pytest from solution import fetch_clean_text_from_urls # The following tests mock urlopen but in real scenario you might want to use libraries like responses to mock requests def test_fetch_clean_text_no_auth(): urls = ["http://example.com"] result = fetch_clean_text_from_urls(urls) assert "http://...
[]
[ 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 urllib.request\nimport urllib.error\nfrom urllib.request import HTTPBasicAuthHandler, HTTPPasswordMgrWithDefaultRealm, build_opener, install_opener, urlopen\nfro...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00018301", "row_id": 18301, "seed_ids": "[343]" }
0.667399
Docs: Python310_18301
I
[ "strip_html_tags", "fetch_clean_text_from_urls" ]
2
[ [ "fetch_clean_text_from_urls", "strip_html_tags" ] ]
1
[]
false
[ "MyHTMLParser" ]
true
pytest
true
[]
true
f8176f6cd65160ab79739aa21d8b4ea9a610bf0f
b6179e8b5fcbc621bffe2efeddbcf5c6e9df2085
v1.0
instruct
Docs
Docs: Python310_18329_I
**Networking Chat Application Using Sockets and Asynchronous I/O** ### Objective Implement a simple chat server-client system using the `asyncio` and `socket` modules. The server should handle simultaneous connections from multiple clients and facilitate message broadcasting to all connected clients in real-time. ###...
import asyncio import socket import time clients = [] async def handle_client(client_socket, addr): while True: try: message = await asyncio.get_event_loop().sock_recv(client_socket, 1024) if not message: break message = message.decode('utf-8') ...
import pytest import asyncio import socket @pytest.mark.asyncio async def test_server_client_connection(): async def run_server(): loop = asyncio.get_event_loop() await server(loop) async def run_client(): client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) await ...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport socket\nimport time\n\nclients = []\n\nasync def handle_client(client_socket, addr):\n while True:\n try:\n message = await ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00018329", "row_id": 18329, "seed_ids": "[151]" }
0.661606
Docs: Python310_18329
I
[ "handle_client", "server" ]
2
[ [ "server", "handle_client" ] ]
1
[]
false
[]
false
pytest
false
[]
true
51a0180fc27784b9a794c0e4e7e951128e1df8e9
9ee51fe351266d3c9fe024911b467e55d035efd2
v1.0
instruct
Docs
Docs: Pytorch_18341_I
### Task You are given a deep learning model implemented in PyTorch and you are required to perform GPU profiling to identify and optimize its performance bottlenecks using TorchInductor. Follow the steps below: 1. **Setup the Environment:** - Implement a function to set the relevant TorchInductor environment vari...
import os import subprocess from typing import List, Tuple def set_environment_variables(): """ Set the relevant TorchInductor environment variables. """ os.environ['TORCHINDUCTOR_UNIQUE_KERNEL_NAMES'] = '1' os.environ['TORCHINDUCTOR_BENCHMARK_KERNEL'] = '1' def run_model(model_script: str) -> str...
import os import subprocess from solution import set_environment_variables, run_model, parse_profiling_data, optimize_kernel def test_set_environment_variables(): set_environment_variables() assert os.environ['TORCHINDUCTOR_UNIQUE_KERNEL_NAMES'] == '1' assert os.environ['TORCHINDUCTOR_BENCHMARK_KERNEL'] ==...
[ { "docstring": "Set the relevant TorchInductor environment variables.", "function_declaration": "def set_environment_variables():", "function_name": "set_environment_variables", "parameter_list": "()" }, { "docstring": "Run the given model script and collect profiling data.\n\nArgs:\n- model...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport subprocess\nfrom typing import List, Tuple\n\ndef set_environment_variables():\n \"\"\"\n Set the relevant TorchInductor environment variables.\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00018341", "row_id": 18341, "seed_ids": "[15]" }
0.520435
Docs: Pytorch_18341
I
[ "set_environment_variables", "run_model", "parse_profiling_data", "optimize_kernel", "parse_execution_time" ]
5
[ [ "optimize_kernel", "parse_execution_time" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d88bd9ab64848eb17c28c8e6a2042fb8a8cb98df
72a315fee933f89c1a1901cd9a35f3eaac222979
v1.0
instruct
Docs
Docs: Python310_18348_I
### Asyncio Subprocess Management You are tasked with creating a Python function that asynchronously runs multiple shell commands concurrently and processes their output. Each command's output should be collected, decoded, and returned. If any command fails (i.e., returns a non-zero exit code), the function should rai...
import asyncio from typing import List, Tuple async def run_single_command(command: str) -> Tuple[str, int, str, str]: """ Helper function to run a single shell command asynchronously and collect its output. """ process = await asyncio.create_subprocess_shell( command, stdout=asyncio.su...
import pytest import asyncio from solution import run_commands @pytest.mark.asyncio async def test_run_commands_success(): commands = ["echo 'hello world'", "echo 'this is a test'"] results = await run_commands(commands) assert results == [ ("echo 'hello world'", 0, "hello world", ""), ("ec...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def run_commands(commands: List[str]) -> List[Tuple[str, int, str, str]]:\n \"\"\"\n Run multiple shell co...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018348", "row_id": 18348, "seed_ids": "[264]" }
0.733897
Docs: Python310_18348
I
[ "run_single_command", "run_commands" ]
2
[ [ "run_commands", "run_single_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e0d73551a7445d9e09103b3e06fc3859d9d4fe4d
4333820d9f3a445065fdfccbdcb41b901a08eef0
v1.0
instruct
Docs
Docs: Python310_18412_I
### Python Exception Handling and Custom Exception Implementation #### Objective To assess your understanding of Python's exception handling mechanisms, custom exception creation, and proper usage of exception functions. #### Problem Statement You are required to implement a Python function that simulates an operatio...
import sys import traceback class CustomError(Exception): """ Custom error for specific application needs. """ pass def log_exception(exc: Exception): """ Logs the details of an exception, including its type, message, and traceback. """ exc_type, exc_value, exc_traceback = sys.exc_info...
import pytest from solution import CustomError, perform_operations def test_perform_operations_value_error(): steps = [{"type": "value_error", "description": "Raise a ValueError"}] results = perform_operations(steps) assert results == {0: False} def test_perform_operations_type_error(): steps = [{"typ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\nimport traceback\n\nclass CustomError(Exception):\n \"\"\"\n Custom exception class for specific application needs.\n \"\"\"\n pass\n\ndef log_e...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018412", "row_id": 18412, "seed_ids": "[33]" }
0.457324
Docs: Python310_18412
I
[ "log_exception", "perform_operations" ]
2
[ [ "perform_operations", "log_exception" ] ]
1
[]
false
[ "CustomError" ]
true
pytest
true
[]
true
51a175a5119632e03d2b7ad45e116aa2e4c16764
d21d3608c83ed3b9924055d89fea85a580e7f5f0
v1.0
instruct
Docs
Docs: Python310_18431_I
**Objective**: Write a Python script to demonstrate your understanding of the `contextvars` module and its usage in an asynchronous environment. **Instructions**: 1. Create a context variable called `request_id` to store request identifiers for an asynchronous web server. 2. Implement a function `handle_request` that ...
import asyncio import contextvars # Define the context variable request_id = contextvars.ContextVar("request_id") async def handle_request(id): """ Simulates handling a client request by setting the request_id and printing the ID before and after processing. """ # Set the request_id for the contex...
import asyncio import contextvars from solution import handle_request, simulate_requests, request_id async def test_handle_request(): """ Tests the handle_request function to ensure correct handling of context variables. """ id = 1 token = request_id.set(id) try: await handle_r...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\n\n# Define the context variable\nrequest_id = contextvars.ContextVar(\"request_id\")\n\nasync def handle_request(id):\n # Set the...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00018431", "row_id": 18431, "seed_ids": "[392]" }
0.497603
Docs: Python310_18431
I
[ "handle_request", "simulate_requests" ]
2
[ [ "simulate_requests", "handle_request" ] ]
1
[]
false
[]
false
pytest
true
[]
true
14f9dfa47dd48ed537836d7dfaf858adf7272ace
5e8940e875efb80fd6eaad857327b20bad815f3b
v1.0
instruct
Docs
Docs: Pandas_18470_I
### Objective: You are required to manipulate a dataset using pandas to analyze sales data of a company. The dataset is provided as a CSV file named `sales_data.csv` with the following columns: - `date` (String): Date of the sale in YYYY-MM-DD format. - `salesperson` (String): Name of the salesperson. - `region` (Strin...
import pandas as pd def load_and_clean_data(file_path): # Load the dataset df = pd.read_csv(file_path) # Parse the 'date' column to datetime df['date'] = pd.to_datetime(df['date']) # Remove any duplicate rows df = df.drop_duplicates() # Fill missing values in 'units_sold' and...
import os import pandas as pd import pytest from solution import load_and_clean_data, generate_summary_report, create_pivot_table, save_to_csv, process_sales_data def setup_module(module): # Setup a temporary CSV file for testing test_data = '''date,salesperson,region,product,units_sold,unit_price 2022-01-01,J...
[ { "docstring": null, "function_declaration": "def load_and_clean_data(file_path):", "function_name": "load_and_clean_data", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def generate_summary_report(df):", "function_name": "generate_summary_report", ...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\n\ndef process_sales_data(input_csv, pivot_csv, summary_csv):\n # Load the dataset into a pandas DataFrame\n df = pd.read_csv(input_csv)\n ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00018470", "row_id": 18470, "seed_ids": "[39]" }
0.769322
Docs: Pandas_18470
I
[ "load_and_clean_data", "generate_summary_report", "create_pivot_table", "save_to_csv", "process_sales_data" ]
5
[ [ "process_sales_data", "create_pivot_table" ], [ "process_sales_data", "generate_summary_report" ], [ "process_sales_data", "load_and_clean_data" ], [ "process_sales_data", "save_to_csv" ] ]
4
[]
false
[]
false
pytest
true
[ "pandas" ]
false
d955eb5ecea31b1f16469b0f6582a28ed404159a
7aaceba300db81113743b7b8636fb669d1c76f64
v1.0
instruct
Docs
Docs: Python310_18490_I
### Asynchronous Networking with Asyncio You are tasked with creating a simple asynchronous TCP echo server using Python's asyncio module. The server should be capable of handling multiple client connections simultaneously, echoing back any received messages to the sender. Implement the following function: ```python...
import asyncio async def handle_client(reader, writer): """ Coroutine to handle client connections. """ try: while True: data = await reader.read(100) if not data: break writer.write(data) await writer.drain() except asyncio.Ca...
import asyncio import socket import pytest from solution import echo_server @pytest.fixture async def start_server(): server_task = asyncio.create_task(echo_server('127.0.0.1', 8888)) await asyncio.sleep(1) # give the server time to start yield server_task.cancel() try: await server_task ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n \"\"\"\n This coroutine handles individual client connections, reading messages\n from the reader ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018490", "row_id": 18490, "seed_ids": "[101]" }
0.681378
Docs: Python310_18490
I
[ "handle_client", "echo_server", "main" ]
3
[ [ "echo_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ce830468ffb5307d9dd1b644c341975fd558cec5
78b9683c5b2b0f6c5ab4f86b9c088eb41ade9cbc
v1.0
instruct
Docs
Docs: Python310_18492_I
**Question: Warning Customization and Control using Python's `warnings` Module** You have been tasked with improving a legacy codebase of a Python application. The application is riddled with deprecated functions, resource mismanagement, and several other issues that raise warnings. Your goal is to gain fine-grained c...
import warnings def handle_warnings(): """ Set up warning filters: - Convert DeprecationWarning to errors. - Ignore (but log) UnicodeWarning. """ # Turn DeprecationWarning into an error warnings.filterwarnings('error', category=DeprecationWarning) # Ignore (but log) UnicodeWarning ...
import warnings from solution import handle_warnings, suppress_specific_warning, example_function def test_handle_warnings(): handle_warnings() # Test DeprecationWarning raising an error try: warnings.warn("This is a deprecation warning.", DeprecationWarning) assert False, "DeprecationWarn...
[ { "docstring": "Set up warning filters:\n- Convert DeprecationWarning to errors.\n- Ignore (but log) UnicodeWarning.", "function_declaration": "def handle_warnings():", "function_name": "handle_warnings", "parameter_list": "()" }, { "docstring": "Temporarily suppress ResourceWarning during t...
[ 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 warnings\n\ndef handle_warnings():\n \"\"\"\n Sets the necessary warning filters.\n \"\"\"\n # Turn DeprecationWarning into an error\n warnings.si...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00018492", "row_id": 18492, "seed_ids": "[125]" }
0.438097
Docs: Python310_18492
I
[ "handle_warnings", "suppress_specific_warning", "example_function", "test_warnings" ]
4
[ [ "test_warnings", "example_function" ], [ "test_warnings", "handle_warnings" ], [ "test_warnings", "suppress_specific_warning" ] ]
3
[]
false
[]
false
pytest
true
[]
true
9264869a2b5f5072bf4870ee5da2ea72e9e15343
7116ceef57cb8e90118a35e6514eb9b2a21a987b
v1.0
instruct
Docs
Docs: Python310_18500_I
### Asynchronous Server with Concurrency and Proper Exception Handling You are tasked with creating an asynchronous server that handles incoming connections from clients. The server should be able to handle multiple clients concurrently while ensuring that blocking operations do not impede the performance of the event...
import asyncio import logging # Setting up logging logging.basicConfig(level=logging.DEBUG) async def simulate_cpu_bound_operation(data: bytes) -> str: """ Simulate a CPU-bound task. The operation will reverse the string as a simple simulation. """ # Simulate computation await asyncio.sleep(2)...
import asyncio import logging import pytest from solution import start_server, handle_client @pytest.fixture async def server(): """ Fixture to start and stop the server. """ server = await asyncio.start_server(handle_client, '127.0.0.1', 8888) yield server server.close() await server.wait_...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport logging\n\n# Setting up logging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger('asyncio')\nlogger.setLevel(logging.DEBUG)\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018500", "row_id": 18500, "seed_ids": "[200]" }
0.619508
Docs: Python310_18500
I
[ "simulate_cpu_bound_operation", "handle_client", "start_server" ]
3
[ [ "handle_client", "simulate_cpu_bound_operation" ], [ "start_server", "handle_client" ] ]
2
[]
false
[]
false
pytest
true
[]
true
8721d6ee8252dc1cfe4ba7d6d29da0d615a819fd
f3f157abb90e8eb9d75cf5a8fffcb813229a7ccf
v1.0
instruct
Docs
Docs: Python310_18546_I
#### Objective: Demonstrate proficiency in using Python's standard library by creating a script that processes, manages, and persists data using specified modules. #### Problem Statement: You are required to implement a function `process_user_data(file_path: str, output_path: str) -> None`. This function will read a J...
import json import pickle from datetime import datetime from typing import List, Dict def read_user_data(file_path: str) -> List[Dict]: with open(file_path, 'r') as file: data = json.load(file) return data def compute_days_since_join(join_date: str) -> int: join_date_obj = datetime.strptime(join_d...
import pytest import os import json import pickle from solution import process_user_data, read_user_data, compute_days_since_join @pytest.fixture def create_test_json_file(tmp_path): data = [ {"name": "John Doe", "age": 28, "join_date": "2022-01-15"}, {"name": "Jane Smith", "age": 22, "join_date": ...
[ { "docstring": null, "function_declaration": "def read_user_data(file_path):", "function_name": "read_user_data", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def compute_days_since_join(join_date):", "function_name": "compute_days_since_join", ...
[ 0, 0, 0, 0, 1, 1, 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 json\nimport pickle\nfrom datetime import datetime\nfrom pathlib import Path\n\n\ndef process_user_data(file_path: str, output_path: str) -> None:\n \"\"\"\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00018546", "row_id": 18546, "seed_ids": "[255]" }
0.608977
Docs: Python310_18546
I
[ "read_user_data", "compute_days_since_join", "process_user_data" ]
3
[ [ "process_user_data", "compute_days_since_join" ], [ "process_user_data", "read_user_data" ] ]
2
[]
false
[]
false
pytest
true
[]
true
6c8dae7accee50e9ebc7f79e8c39dcfcddaea6fa
6c1854d2e4935916b10f09af547b954cebcd6f18
v1.0
instruct
Docs
Docs: Python310_18550_I
**Internationalization and Localized Greetings** ### Objective: Implement a function that generates localized greeting messages based on user's preferred language and locale. The function should utilize the `gettext` module to fetch appropriate translations from message catalogs. ### Requirements: 1. Use the GNU `get...
import gettext import os def setup_translations(): locales_dir = os.path.join(os.path.dirname(__file__), 'locales') os.makedirs(locales_dir, exist_ok=True) # This setup assumes that the .mo files are already compiled and placed in appropriate directories # English: locales/en/LC_MESSAGES/messages....
from solution import localized_greeting # Assuming the solution is saved as solution.py def test_localized_greeting_english(): assert localized_greeting('en', 'Alice') == "Hello, Alice!" def test_localized_greeting_spanish(): assert localized_greeting('es', 'Carlos') == "¡Hola, Carlos!" def test_localized_g...
[ { "docstring": null, "function_declaration": "def setup_translations():", "function_name": "setup_translations", "parameter_list": "()" }, { "docstring": "Returns a localized greeting message in the specified language.\n\n:param language_code: Language code (e.g., 'en' for English, 'es' for ...
[ 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 gettext\nimport os\n\ndef setup_translations():\n locales_dir = os.path.join(os.path.dirname(__file__), 'locales')\n os.makedirs(locales_dir, exist_ok=True...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00018550", "row_id": 18550, "seed_ids": "[231]" }
0.426215
Docs: Python310_18550
I
[ "setup_translations", "localized_greeting" ]
2
[ [ "localized_greeting", "setup_translations" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5d59652bbbeaf8789cf00e6eadf9dcfabe9a8ebb
d7eb56b80413ceb76f81a2eb55d4398776b50d07
v1.0
instruct
Docs
Docs: Python310_18568_I
Title: Creating and Manipulating Custom Types Using Python C API **Objective**: Write a Python C extension module that defines a custom heap-allocated type. This type should include methods to check type flags and manipulate type features. **Instructions**: 1. **Creating a Custom Type**: - Define a custom type ...
# The real implementation would be done in C using Python C API, but here is a Python approximation for the # purpose of demonstrating the structure. class MyCustomType: """ A custom type that is typically defined using Python C API. """ def __init__(self): self.attributes = {} def is_subtype...
from solution import MyCustomType, is_subtype, get_type_flags, modify_type, create_instance def test_create_instance(): obj = create_instance() assert isinstance(obj, MyCustomType) def test_is_subtype_with_mycustomtype_instance(): obj = create_instance() assert is_subtype(obj) def test_is_subtype_wit...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "# mycustommodule.c\n#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include <structmember.h>\n\n// Define the structure of our custom type\ntypedef struct {\n PyObje...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018568", "row_id": 18568, "seed_ids": "[48]" }
0.432221
Docs: Python310_18568
I
[ "is_subtype", "get_type_flags", "modify_type", "create_instance" ]
4
[ [ "get_type_flags", "is_subtype" ], [ "modify_type", "is_subtype" ] ]
2
[]
false
[ "MyCustomType" ]
true
pytest
true
[]
true
bc6ce01a4e38b972f363105c764cf998ed8385db
a586eaad651f8db2f08da3d6ec48466281d2991a
v1.0
instruct
Docs
Docs: Pytorch_18573_I
### **Problem: Composable Function Transforms in PyTorch** You are given a function `f` that takes a 2D tensor (matrix) as input and returns a scalar value. Your task is to implement a new function that computes the per-sample gradients for a batch of such matrices using `torch.func`. ### **Instructions:** 1. **Gradi...
import torch import torch.func as tf def compute_gradient(f: callable) -> callable: """ Computes the gradient of the function f with respect to its input. Args: - f (callable): A function that takes a 2D tensor and returns a scalar. Returns: - callable: A function that computes the gradient o...
import torch from solution import compute_gradient, batch_compute_gradient def test_compute_gradient_simple_function(): def f(x): return torch.sum(x ** 2) grad_f = compute_gradient(f) x = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) expected_grad = 2 * x assert torch.allclose(grad_f(x),...
[ { "docstring": "Computes the gradient of the function f with respect to its input.\n\nArgs:\n- f (callable): A function that takes a 2D tensor and returns a scalar.\n\nReturns:\n- callable: A function that computes the gradient of f.", "function_declaration": "def compute_gradient(f):", "function_name":...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.func as tf\n\ndef compute_gradient(f: callable) -> callable:\n \"\"\"\n Computes the gradient of the function f with respect to its inp...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018573", "row_id": 18573, "seed_ids": "[56]" }
0.539938
Docs: Pytorch_18573
I
[ "compute_gradient", "batch_compute_gradient", "f" ]
3
[ [ "batch_compute_gradient", "compute_gradient" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
30c9b7a1cb3de6ec8e2a4319f918e860433e5e47
1e95b6c73af85d8b90be57a94908ec5baa99fdfc
v1.0
instruct
Docs
Docs: Python310_18583_I
### Python Asyncio and Event Loops Challenge You are required to create a script that leverages the `asyncio` module to manage multiple asynchronous tasks. Your solution will need to create an event loop, schedule tasks, handle subprocesses on Windows and macOS, and consider the limitations described in the provided d...
import asyncio import platform import aiohttp async def fetch_data(url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.text() async def gather_data(urls): tasks = [fetch_data(url) for url in urls] return await asyncio.gath...
import pytest import asyncio from unittest.mock import patch, Mock from solution import fetch_data, gather_data, run_subprocess @pytest.mark.asyncio async def test_fetch_data(): url = "http://example.com" expected_content = "Example Domain" with patch("aiohttp.ClientSession.get") as mock_get: mock_...
[ { "docstring": null, "function_declaration": "def main():", "function_name": "main", "parameter_list": "()" } ]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\nimport aiohttp\n\nasync def fetch_data(url):\n async with aiohttp.ClientSession() as session:\n async with session.get(url) a...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00018583", "row_id": 18583, "seed_ids": "[370]" }
0.568922
Docs: Python310_18583
I
[ "fetch_data", "gather_data", "run_subprocess", "main" ]
4
[ [ "gather_data", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
ee0c42aeee8027670e85a292f09b44858e81a794
83cfcef884d2abd72c47e22fd2a069682b207f6d
v1.0
instruct
Docs
Docs: Python310_18588_I
#### Objective You are required to implement a Python script that parses a `MANIFEST.in` file, generates a `MANIFEST` file listing all files for distribution, and creates a source distribution archive. This question assesses your understanding of file manipulation, parsing, and usage of Python standard libraries. ####...
import fnmatch import os import tarfile import zipfile def parse_manifest_in(manifest_in_file): with open(manifest_in_file, 'r') as f: lines = f.readlines() files_to_include = [] for line in lines: line = line.strip() if line.startswith('include'): pattern = line.sp...
import os import shutil import pytest from solution import create_source_distribution # Fixture to setup and teardown a basic file structure for testing @pytest.fixture def setup_files(): os.mkdir('test_dist') os.chdir('test_dist') with open('README.txt', 'w') as f: f.write('This is a README f...
[ { "docstring": null, "function_declaration": "def parse_manifest_in(manifest_in_file):", "function_name": "parse_manifest_in", "parameter_list": "(manifest_in_file)" }, { "docstring": null, "function_declaration": "def write_manifest(manifest_file, files):", "function_name": "write_m...
[ 0, 0, 0, 0, 0, 1, 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 os\nimport tarfile\nimport zipfile\nfrom glob import glob\n\ndef parse_manifest_in(manifest_in_file):\n \"\"\"\n Parse the MANIFEST.in file and generate th...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00018588", "row_id": 18588, "seed_ids": "[439]" }
0.53474
Docs: Python310_18588
I
[ "parse_manifest_in", "write_manifest", "create_archive", "create_source_distribution" ]
4
[ [ "create_source_distribution", "create_archive" ], [ "create_source_distribution", "parse_manifest_in" ], [ "create_source_distribution", "write_manifest" ] ]
3
[]
false
[]
false
pytest
true
[]
true
eb9b7ba05631b5b26c5319cf0b5b363dbd679400
688909a14e821ceeffe027d149a73183d02c5b87
v1.0
instruct
Docs
Docs: Pytorch_18729_I
### Question: Implementing and Applying FFT in PyTorch In this exercise, you will demonstrate your understanding of PyTorch's FFT functionality by implementing functions to process and analyze signals. #### Problem Statement 1. **Signal Frequency Analysis:** - Write a function `compute_fft(signal: torch.Tensor)...
import torch def compute_fft(signal: torch.Tensor) -> torch.Tensor: """ Computes the one-dimensional FFT of a real-valued input signal. Args: signal (torch.Tensor): Real-valued input signal. Returns: torch.Tensor: Complex tensor representing the frequency domain. """ return to...
import torch from solution import compute_fft, reconstruct_signal, filter_frequencies def test_compute_fft(): signal = torch.tensor([0.0, 1.0, 0.0, -1.0]) frequency_domain = compute_fft(signal) expected_frequency_domain = torch.tensor([0.0+0.0j, 0.0-2.0j, 0.0+0.0j, 0.0+2.0j]) assert torch.allclose(freq...
[ { "docstring": "Computes the one-dimensional FFT of a real-valued input signal.\n\nArgs:\nsignal (torch.Tensor): Real-valued input signal.\n\nReturns:\ntorch.Tensor: Complex tensor representing the frequency domain.", "function_declaration": "def compute_fft(signal):", "function_name": "compute_fft", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef compute_fft(signal: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Computes the one-dimensional FFT of a given real-valued input signal.\n \"\"\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018729", "row_id": 18729, "seed_ids": "[125]" }
0.53319
Docs: Pytorch_18729
I
[ "compute_fft", "reconstruct_signal", "filter_frequencies" ]
3
[ [ "filter_frequencies", "compute_fft" ], [ "filter_frequencies", "reconstruct_signal" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
7f321d4df50ffa48d7a5e7dc03de93bfbc8a5036
9e8c95d224a8fadf76fab8f86583cd63cb942375
v1.0
instruct
Docs
Docs: Seaborn_18764_I
### Coding Assessment: Create and Apply Custom Seaborn Palettes **Objective:** You will create custom color palettes using seaborn's `dark_palette` function and apply these palettes to a variety of plots. This will test your understanding of seaborn's palette creation and visualization techniques. **Task:** 1. **Cr...
import seaborn as sns import matplotlib.pyplot as plt def create_palettes(): """ Create color palettes and colormap using seaborn's dark_palette function. """ # Sequential color palette from dark gray to "seagreen" palette_seagreen = sns.dark_palette("seagreen", as_cmap=False) # Sequential...
import pytest def test_create_palettes(): from solution import create_palettes palette_seagreen, palette_hex, palette_husl, palette_golden, cmap_continuous = create_palettes() # Assert palettes are correctly created assert len(palette_seagreen) > 0 assert len(palette_hex) > 0 assert len(p...
[ { "docstring": "Create color palettes and colormap using seaborn's dark_palette function.", "function_declaration": "def create_palettes():", "function_name": "create_palettes", "parameter_list": "()" }, { "docstring": "Create and display plots using created palettes and colormap.", "fun...
[ 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 seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef create_palettes():\n \"\"\"\n Creates and returns various color palettes using seaborn's dark_palett...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00018764", "row_id": 18764, "seed_ids": "[18]" }
0.653562
Docs: Seaborn_18764
I
[ "create_palettes", "create_plots" ]
2
[ [ "create_plots", "create_palettes" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "seaborn" ]
false
3011acd97f644cff22221eead62aa8b2f55b8ec8
a4165554fc5e1e5528abe5ff2b45e9ab17a2e3f1
v1.0
instruct
Docs
Docs: Python310_18797_I
### Python Coding Assessment: Custom Exceptions and Exception Handling **Objective:** Demonstrate your understanding of Python's built-in exception hierarchy and your ability to create and handle custom exceptions. **Problem Statement:** You are tasked with creating an application that simulates a file processing sy...
class FileProcessingException(Exception): """Base class for all custom file processing exceptions""" pass class FileNotFoundErrorCustom(FileProcessingException): """Raised when a file does not exist""" pass class PermissionErrorCustom(FileProcessingException): """Raised when there are insufficient...
from solution import process_files, FileNotFoundErrorCustom, PermissionErrorCustom, ProcessingErrorCustom def test_file_not_found(): file_paths = ["nonexistent.txt"] try: process_files(file_paths) except FileNotFoundErrorCustom as e: assert str(e) == "File 'nonexistent.txt' not found." def...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class FileProcessingException(Exception):\n \"\"\"Base class for custom exceptions in file processing.\"\"\"\n pass\n\nclass FileNotFoundErrorCustom(FileProcessin...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018797", "row_id": 18797, "seed_ids": "[256]" }
0.587072
Docs: Python310_18797
I
[ "file_exists", "has_permission", "read_file", "process_content", "process_files" ]
5
[ [ "process_files", "file_exists" ], [ "process_files", "has_permission" ], [ "process_files", "process_content" ], [ "process_files", "read_file" ] ]
4
[]
false
[ "FileProcessingException", "FileNotFoundErrorCustom", "PermissionErrorCustom", "ProcessingErrorCustom" ]
true
pytest
true
[]
true
8586c465600d40f63952cfc0c0bafff1956acb8c
25d0ecec25524ce70d629b4c49a8a3cdc6920b31
v1.0
instruct
Docs
Docs: Python310_18798_I
### Asynchronous File Downloader with Platform-Specific Limitations **Objective:** Implement an asynchronous file downloader using the "asyncio" module in Python that handles platform-specific limitations. #### Problem Statement: You are tasked with writing a Python function, `async_file_downloader`, which downloads ...
import asyncio import aiohttp import os import platform import sys from selectors import SelectSelector from typing import List async def download_file(session, url, dest_folder): try: async with session.get(url) as response: if response.status != 200: raise Exception(f"Failed t...
import os import pytest import asyncio from unittest.mock import patch, MagicMock from solution import async_file_downloader # Setup for tests @pytest.fixture def download_urls(): return ["http://example.com/file1.txt", "http://example.com/file2.txt", "http://example.com/file3.txt"] @pytest.fixture def dest_folde...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nimport os\nimport platform\nfrom asyncio import AbstractEventLoop\nfrom typing import List\n\nasync def download_file(session: aiohttp.C...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00018798", "row_id": 18798, "seed_ids": "[370]" }
0.610859
Docs: Python310_18798
I
[ "download_file", "async_file_downloader" ]
2
[ [ "async_file_downloader", "download_file" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
9070c78fc6c3d431f80df44b1b3ad1eff507120b
281147768bc4086ff86a9d3afb22b64aa9887976
v1.0
instruct
Docs
Docs: Python310_18813_I
### Advanced Hashing with Python's `hashlib` Module #### Objective You are tasked to implement a secure file verification mechanism using Python's `hashlib` module. The goal is to ensure the integrity of files by creating and verifying their hashes. #### Requirements 1. **Function 1: `create_file_hash(file_path, algo...
import hashlib def create_file_hash(file_path, algorithm): """ Creates a hash for the specified file using the given algorithm. Args: - file_path (str): Path to the file that needs to be hashed. - algorithm (str): The hashing algorithm to use (e.g., 'sha256', 'sha512'). Returns: - str: Th...
import pytest from solution import create_file_hash, verify_file_integrity def test_create_file_hash_sha256(tmp_path): file = tmp_path / "testfile.txt" file.write_text("This is a test.") expected_hash = hashlib.sha256(b"This is a test.").hexdigest() assert create_file_hash(str(file), 'sha256') == expe...
[ { "docstring": "Creates a hash for the specified file using the given algorithm.\n\nArgs:\n- file_path (str): Path to the file that needs to be hashed.\n- algorithm (str): The hashing algorithm to use (e.g., 'sha256', 'sha512').\n\nReturns:\n- str: The computed hash of the file's contents.", "function_decla...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\n\ndef create_file_hash(file_path, algorithm):\n \"\"\"\n Creates a hash for the specified file using the given algorithm.\n\n Args:\n - file...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00018813", "row_id": 18813, "seed_ids": "[394]" }
0.707291
Docs: Python310_18813
I
[ "create_file_hash", "verify_file_integrity" ]
2
[ [ "verify_file_integrity", "create_file_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6006dade1679a64804fc8808dcf243abf6c1cd73
7dc67c4b404bfcbc6a109ad10545a6ceb2462a6a
v1.0
instruct
Docs
Docs: Pytorch_18834_I
**Coding Question: Implement a Flexible Attention Mechanism** ### Objective The objective of this question is to test your understanding and ability to implement a custom attention mechanism using PyTorch's `torch.nn.attention.flex_attention` module and its associated utility functions. ### Task You are required to: ...
import torch from torch.nn.functional import softmax def create_block_mask(seq_len, block_size): mask = torch.zeros(seq_len, seq_len) for i in range(seq_len): start = max(0, i - block_size) end = min(seq_len, i + block_size + 1) mask[i, start:end] = 1 return mask def create_nested_...
import torch from solution import custom_flex_attention def test_custom_flex_attention_block_mask(): input_tensor = torch.randn(2, 10, 64) mask_type = "block" output_tensor = custom_flex_attention(input_tensor, mask_type) assert output_tensor.shape == input_tensor.shape def test_custom_flex_attention_...
[ { "docstring": null, "function_declaration": "def create_block_mask(seq_len, block_size):", "function_name": "create_block_mask", "parameter_list": "(seq_len, block_size)" }, { "docstring": null, "function_declaration": "def create_nested_block_mask(seq_len):", "function_name": "crea...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.nn.functional import softmax\n\ndef create_block_mask(seq_len, block_size):\n mask = torch.zeros(seq_len, seq_len)\n for i in range(seq_l...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00018834", "row_id": 18834, "seed_ids": "[0]" }
0.456208
Docs: Pytorch_18834
I
[ "create_block_mask", "create_nested_block_mask", "noop_mask", "flex_attention", "custom_flex_attention" ]
5
[ [ "custom_flex_attention", "create_block_mask" ], [ "custom_flex_attention", "create_nested_block_mask" ], [ "custom_flex_attention", "flex_attention" ], [ "custom_flex_attention", "noop_mask" ] ]
4
[]
false
[]
false
pytest
true
[ "torch" ]
false
187aae5236cbb8df4e270927ed216395e97fdfe7
4dccd643b164b3307cddd8936b317c1933acfd6e
v1.0
instruct
Docs
Docs: Python310_18913_I
#### Objective Write a Python script that utilizes various modules from the standard library to perform the following tasks: 1. Read integers from a file and calculate their statistical properties. 2. Allow users to specify the file and some optional parameters via command line arguments. 3. Handle errors gracefully a...
import argparse import os import statistics import sys from datetime import datetime def read_integers_from_file(file_path, log_path): """ Reads integers from a given file and logs errors to a specified log file. Returns a list of read integers. """ integers = [] with open(log_path, 'a') as log...
import os import pytest from solution import read_integers_from_file, calculate_statistics # Helper function to create a temporary file for testing def create_temp_file(content, filename="temp.txt"): with open(filename, 'w') as f: f.write(content) return filename def test_read_integers_from_file(): ...
[ { "docstring": "Reads integers from a given file and logs errors to a specified log file.\nReturns a list of read integers.", "function_declaration": "def read_integers_from_file(file_path, log_path):", "function_name": "read_integers_from_file", "parameter_list": "(file_path, log_path)" }, { ...
[ 0, 0, 0, 0, 1, 0, 1, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import argparse\nimport os\nimport statistics\nimport sys\nfrom datetime import datetime\n\ndef read_integers(file_path, log_file):\n integers = []\n with open(fi...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00018913", "row_id": 18913, "seed_ids": "[422]" }
0.703382
Docs: Python310_18913
I
[ "read_integers_from_file", "log_error", "calculate_statistics", "main" ]
4
[ [ "read_integers_from_file", "log_error" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9f8289fe2b5b04fa3cdc6b245392d5f6906ff477
91dd65a4f86ebc0fb6df69c0f2bcd78ca06edcd2
v1.0
instruct
Docs
Docs: Python310_18974_I
You are given the task of developing a secure messaging feature for a system that ensures data integrity using HMAC (Hash-based Message Authentication Code). You will write a Python function to generate and verify the HMAC of messages. #### Function Specifications: 1. **Function 1: `generate_hmac(key: bytes, message: ...
import hmac import hashlib def generate_hmac(key: bytes, message: str, digestmod: str) -> str: """ Generates an HMAC for a given message using the specified key and hash algorithm. """ if len(key) < 16: raise ValueError("Key must be at least 16 bytes long.") hmac_obj = hmac.new(key, message...
from solution import generate_hmac, verify_hmac def test_generate_hmac(): key = b'validkey12345678' message = "The quick brown fox jumps over the lazy dog" digestmod = 'sha256' hmac_result = generate_hmac(key, message, digestmod) assert len(hmac_result) == 64 # SHA256 produces 64 hex digits ...
[ { "docstring": "Generates an HMAC for a given message using the specified key and hash algorithm.", "function_declaration": "def generate_hmac(key, message, digestmod):", "function_name": "generate_hmac", "parameter_list": "(key, message, digestmod)" }, { "docstring": "Verifies an HMAC again...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hmac\nimport hashlib\n\ndef generate_hmac(key: bytes, message: str, digestmod: str) -> str:\n \"\"\"\n Generates the HMAC for the given message using the s...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00018974", "row_id": 18974, "seed_ids": "[298]" }
0.856287
Docs: Python310_18974
I
[ "generate_hmac", "verify_hmac" ]
2
[ [ "verify_hmac", "generate_hmac" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c550027cf4144468059c55567d843233a79c7398
bcaf2d31266b4a4b011c01383e09b882de7aa381
v1.0
instruct
Docs
Docs: Python310_19006_I
### Advanced Python Coding Assessment #### Objective: To assess your understanding of asynchronous programming in Python using the `asyncio` module, including debugging, concurrency, running blocking code, and proper task handling. #### Task: Create an asynchronous Python application that simulates a simplified real-...
import asyncio import logging import random from concurrent.futures import ThreadPoolExecutor logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) async def fetch_page(url): """ Simulates fetching a web page by sleeping for a random time between 0.1 to 1 second. """ sleep_time...
import asyncio from solution import fetch_page, process_content, main def test_fetch_page(monkeypatch): class MockRandom: def uniform(self, a, b): return 0.5 monkeypatch.setattr('random.uniform', MockRandom().uniform) asyncio.run(async_test_fetch_page()) async def async_test_fetch_pag...
[ { "docstring": null, "function_declaration": "def blocking_task():", "function_name": "blocking_task", "parameter_list": "()" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport logging\nimport random\nfrom concurrent.futures import ThreadPoolExecutor\n\nasync def fetch_page(url):\n \"\"\"\n Simulates fetching a web...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00019006", "row_id": 19006, "seed_ids": "[200]" }
0.581387
Docs: Python310_19006
I
[ "fetch_page", "process_content", "simulate_blocking_operation", "main", "fetch_and_process" ]
5
[ [ "fetch_and_process", "fetch_page" ], [ "fetch_and_process", "process_content" ] ]
2
[]
false
[]
false
pytest
true
[]
true
58f846976231f9fd6e8ab19ff9a1294fda7a5709
ff0f491015d025041f9125e5890e294c95a8ed7a
v1.0
instruct
Docs
Docs: Python310_19056_I
**Queue Load Balancer** You are required to implement a load balancer using the asyncio Queue. The load balancer will distribute tasks among multiple workers. Each task will have a defined processing time, and we will simulate the processing by making the workers sleep for that duration. Note that the workers should p...
import asyncio from typing import List async def worker(queue: asyncio.Queue): while True: task_duration = await queue.get() await asyncio.sleep(task_duration) queue.task_done() async def distribute_tasks(n_workers: int, tasks: List[float]) -> float: queue = asyncio.Queue() fo...
import asyncio import pytest from solution import distribute_tasks @pytest.mark.asyncio async def test_distribute_tasks_single_worker(): assert await distribute_tasks(1, [0.5, 0.5, 0.5]) == 1.5 @pytest.mark.asyncio async def test_distribute_tasks_multiple_workers(): assert await distribute_tasks(3, [0.5, 0.5,...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List\n\nasync def worker(name: str, queue: asyncio.Queue):\n while True:\n task_duration = await queue.get()\n if ta...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00019056", "row_id": 19056, "seed_ids": "[111]" }
0.542846
Docs: Python310_19056
I
[ "worker", "distribute_tasks" ]
2
[ [ "distribute_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b4877cff4ff5976fe25a7e5600b188a900833318
1ce0f1466a08500febed8bde584cf13bca280fd7
v1.0
instruct
Docs
Docs: Python310_19073_I
**Objective:** Create an asynchronous program in Python that monitors multiple network socket connections and performs specific read and write operations based on the platform it is running on. ### Requirements: 1. **Function Implementation:** Implement a function `async_monitor_sockets` that accepts a list of socke...
import asyncio import platform import socket import sys async def handle_socket(sock): loop = asyncio.get_event_loop() while True: data = await loop.sock_recv(sock, 1024) if not data: break print(f"Received data: {data.decode('utf-8')}") await loop.sock_sendall(sock,...
import pytest import socket import asyncio from solution import async_monitor_sockets @pytest.mark.asyncio async def test_async_monitor_sockets(): # Mock server to test against server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('localhost', 8000)) server.listen(5) server.setblo...
[]
[ 0, 0, 0, 0, 0, 1, 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\nimport platform\nimport socket\n\n\nasync def handle_socket(sock):\n try:\n # Read data from the socket\n data = await asyncio.to_threa...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00019073", "row_id": 19073, "seed_ids": "[370]" }
0.642702
Docs: Python310_19073
I
[ "handle_socket", "async_monitor_sockets" ]
2
[ [ "async_monitor_sockets", "handle_socket" ] ]
1
[]
false
[]
false
pytest
true
[]
true
86330b0d0c54c17c0086e3b674ccc2484f4db64f
fe840fc58c05c82f867229ace39483bc7434470a
v1.0
instruct
Docs
Docs: Python310_19107_I
<|Analysis Begin|> The provided documentation describes the `asyncio` library in Python, which is utilized for writing concurrent code using the `async` and `await` syntax. It outlines the major functionalities of `asyncio`: 1. High-level APIs: - Running coroutines concurrently. - Performing network IO and IPC....
import asyncio from typing import List, Tuple async def worker(worker_id: int, queue: asyncio.Queue): while not queue.empty(): task_name, duration = await queue.get() await asyncio.sleep(duration) print(f"Worker {worker_id} completed task '{task_name}' in {duration} seconds") queue....
import asyncio import pytest from solution import process_tasks_concurrently @pytest.mark.asyncio async def test_process_tasks_concurrently(): tasks = [("A", 2), ("B", 3), ("C", 1)] worker_count = 2 await process_tasks_concurrently(tasks, worker_count) @pytest.mark.asyncio async def test_single_worker...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def worker(worker_id: int, queue: asyncio.Queue):\n while not queue.empty():\n task_name, duration = a...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00019107", "row_id": 19107, "seed_ids": "[270]" }
0.556885
Docs: Python310_19107
I
[ "worker", "process_tasks_concurrently" ]
2
[ [ "process_tasks_concurrently", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
45214361ad42eb848995df9846bb6999673fb997
16b07694ea93dcf20ba94d0ed48cee8c3aa08bee
v1.0
instruct
Docs
Docs: Seaborn_19159_I
#### Objective In this task, you are required to demonstrate your understanding of seaborn by creating a function that generates and customizes various plots based on specified parameters. #### Question Write a function named `custom_plot` that takes in several parameters to generate a line plot using seaborn. The fun...
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 - i) * flip) def custom_plot(n: int, flip: int, theme: str, style: str, context: str, font_scale: float,...
import os from solution import custom_plot def test_custom_plot_creation(): custom_plot( n=5, flip=1, theme='darkgrid', style='whitegrid', context='notebook', font_scale=1.2, linewidth=2.0, despine_offset=5, save_filepath='test_plot.png' ) assert os.path.exists('test_plot.png') os.remov...
[ { "docstring": null, "function_declaration": "def sinplot(n=10, flip=1):", "function_name": "sinplot", "parameter_list": "(n=10, flip=1)" }, { "docstring": null, "function_declaration": "def custom_plot(n, flip, theme, style, context, font_scale, linewidth, despine_offset, save_filepath)...
[ 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 numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef sinplot(flip=1, n=7):\n x = np.linspace(0, 14, 100)\n for i in range(1, n + 1):\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00019159", "row_id": 19159, "seed_ids": "[2]" }
0.67099
Docs: Seaborn_19159
I
[ "sinplot", "custom_plot" ]
2
[ [ "custom_plot", "sinplot" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "seaborn" ]
false
669da4beb3ad1968b5cb7e36ee3bbf210619f826
966f677474c74245df6a07c6772ea4d9f502b293
v1.0
instruct
Docs
Docs: Python310_19228_I
You are tasked with implementing a simulation of a task scheduler using `asyncio.Queue` in Python 3.10. The goal is to distribute a list of tasks among a fixed number of workers, ensuring that each worker processes tasks in a fair manner. Your implementation should demonstrate your understanding of asynchronous program...
import asyncio async def worker(worker_id, task_queue, results): while True: task = await task_queue.get() if task is None: break task_id, duration = task await asyncio.sleep(duration) results[task_id] = worker_id task_queue.task_done() async def run_tas...
import asyncio from solution import run_task_scheduler def test_run_task_scheduler_simple(): tasks = [(1, 1.0), (2, 1.0), (3, 1.0)] num_workers = 2 results = asyncio.run(run_task_scheduler(tasks, num_workers)) assert results == {1: 0, 2: 1, 3: 0} or results == {1: 1, 2: 0, 3: 1} def test_run_task_sch...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def worker(worker_id, task_queue, result):\n while True:\n task = await task_queue.get()\n if task is None:\n break\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00019228", "row_id": 19228, "seed_ids": "[111]" }
0.551931
Docs: Python310_19228
I
[ "worker", "run_task_scheduler" ]
2
[ [ "run_task_scheduler", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
078c51fd56e6efcf7ac67603e6c02e9f9154654f
d881530a67c5cdec24da4eed07636a1d8392291e
v1.0
instruct
Docs
Docs: Python310_19280_I
### **Task: Implement a Concurrency Control System** You are tasked with designing a concurrency control system for handling a set of tasks, using Python's `asyncio` queues. ### **Problem Description:** Implement an asynchronous function `process_tasks(queue: asyncio.Queue, num_workers: int) -> Tuple[float, float]` th...
import asyncio from typing import Tuple async def worker(queue: asyncio.Queue): while True: processing_time = await queue.get() await asyncio.sleep(processing_time) queue.task_done() async def process_tasks(queue: asyncio.Queue, num_workers: int) -> Tuple[float, float]: start_time = as...
import asyncio import pytest from solution import process_tasks @pytest.mark.asyncio async def test_process_tasks_single_worker(): queue = asyncio.Queue() for time in [1.0, 2.0, 3.0]: await queue.put(time) total_time_taken, expected_time = await process_tasks(queue, 1) assert round(to...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import Tuple\n\nasync def worker(queue: asyncio.Queue):\n while not queue.empty():\n processing_time = await queue.get()\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00019280", "row_id": 19280, "seed_ids": "[111]" }
0.628444
Docs: Python310_19280
I
[ "worker", "process_tasks" ]
2
[ [ "process_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c3599f16f51949a79c4aeff40238bf0150230004
663cc92c901d03452c1fe1f300412c0173edad6d
v1.0
instruct
Docs
Docs: Python310_19377_I
### Asynchronous Task Management and Synchronization You are tasked with implementing a small server that handles client requests asynchronously using Python's `asyncio` module. The server must perform the following tasks: 1. Accept multiple client connections concurrently. 2. Use an asynchronous queue to distribute ...
import asyncio async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: """ Function to handle client connection. Reads a message from the client, processes it, and sends back a response. """ data = await reader.read(100) message = data.decode() addr = wr...
import asyncio import pytest from solution import handle_client, client_request_processor, main @pytest.mark.asyncio async def test_handle_client(): reader, writer = await asyncio.open_connection('127.0.0.1', 8888) writer.write(b'hello') await writer.drain() response = await reader.read(100) a...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:\n data = await reader.read(100)\n message = data.de...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00019377", "row_id": 19377, "seed_ids": "[360]" }
0.605125
Docs: Python310_19377
I
[ "handle_client", "client_request_processor", "main" ]
3
[ [ "client_request_processor", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
109d37c7f1f46a54c88bba3d8209074e69926424
23224305a1511accee00d6b943d51295575597b5
v1.0
instruct
Docs
Docs: Python310_19467_I
### Concurrent Execution with Threads **Objective:** Write a Python script that demonstrates your understanding of concurrent execution using the `threading` module. You will implement a program that calculates the factorial of multiple numbers concurrently. **Description:** 1. Create a function `factorial(n)` that c...
import threading def factorial(n): """ Returns the factorial of a given number n. """ if n == 0: return 1 result = 1 for i in range(1, n + 1): result *= i return result def calculate_factorials(numbers): """ Calculate the factorial of each number in the list 'number...
from solution import factorial, calculate_factorials def test_factorial(): assert factorial(0) == 1 assert factorial(1) == 1 assert factorial(5) == 120 assert factorial(7) == 5040 assert factorial(10) == 3628800 def test_calculate_factorials(): numbers = [0, 1, 5, 7, 10] result = calculate...
[ { "docstring": "Returns the factorial of a given number n.", "function_declaration": "def factorial(n):", "function_name": "factorial", "parameter_list": "(n)" }, { "docstring": "Calculate the factorial of each number in the list 'numbers' concurrently using threads.", "function_declarat...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import threading\n\ndef factorial(n):\n \"\"\"\n Returns the factorial of n.\n \"\"\"\n if n == 0:\n return 1\n result = 1\n for i in range(1, ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00019467", "row_id": 19467, "seed_ids": "[206]" }
0.72705
Docs: Python310_19467
I
[ "factorial", "calculate_factorials" ]
2
[ [ "calculate_factorials", "factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1af0e630b60f5d84b1f8d6aa0e075a140a64cfa8
3930031954e59b47a7aaa0e092282fbe67517abf
v1.0
instruct
Docs
Docs: Python310_19483_I
### Question: Python `bytes` Object Manipulation You are tasked with implementing a series of functions that manipulate Python's bytes objects at a low level using the C API methods described in the documentation. This will require understanding of memory management, as well as accurate transformation of raw data to...
def create_bytes_from_string(s: str) -> bytes: """ Create a new bytes object from the given string. :param s: Input string :return: Corresponding bytes object """ return s.encode() def concat_bytes_objects(bytes1: bytes, bytes2: bytes) -> bytes: """ Concatenate two bytes objects. ...
from solution import create_bytes_from_string, concat_bytes_objects, resize_bytes_object, get_bytes_size def test_create_bytes_from_string(): assert create_bytes_from_string("Hello") == b"Hello" assert create_bytes_from_string("") == b"" def test_concat_bytes_objects(): assert concat_bytes_objects(b"Hello...
[ { "docstring": "Create a new bytes object from the given string.\n\n:param s: Input string\n:return: Corresponding bytes object", "function_declaration": "def create_bytes_from_string(s):", "function_name": "create_bytes_from_string", "parameter_list": "(s)" }, { "docstring": "Concatenate tw...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def create_bytes_from_string(s: str) -> bytes:\n \"\"\"\n Create a new bytes object from the given string.\n\n :param s: Input string\n :return: Correspondi...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00019483", "row_id": 19483, "seed_ids": "[19]" }
0.523385
Docs: Python310_19483
I
[ "create_bytes_from_string", "concat_bytes_objects", "resize_bytes_object", "get_bytes_size", "demo_bytes_operations" ]
5
[ [ "demo_bytes_operations", "concat_bytes_objects" ], [ "demo_bytes_operations", "create_bytes_from_string" ], [ "demo_bytes_operations", "get_bytes_size" ], [ "demo_bytes_operations", "resize_bytes_object" ] ]
4
[]
false
[]
false
pytest
true
[]
true
17193aea0817b791bd2d5b392681436e1bc8eb9d
c6791106de4463a78f4c5de1f3b8f81ed1f6c9ab
v1.0
instruct
Docs
Docs: Python310_19495_I
**Question: Implement a Secure Data Serialization Process** You are to implement a secure data serialization and deserialization process for a set of Python objects using the `marshal` module. Due to the known security issue of the `marshal` module, you must incorporate additional checking mechanisms to ensure that on...
import marshal def is_supported_type(obj): if isinstance(obj, (int, float, str, bool, type(None))): return True elif isinstance(obj, (list, tuple, set)): return all(is_supported_type(item) for item in obj) elif isinstance(obj, dict): return all(isinstance(key, (str, int)) and is_sup...
def test_supported_types(): file_path = 'test_supported.marshal' # Test with int secure_marshal_dump(123, file_path) assert secure_marshal_load(file_path) == 123 # Test with float secure_marshal_dump(123.45, file_path) assert secure_marshal_load(file_path) == 123.45 # Test with str ...
[ { "docstring": null, "function_declaration": "def is_supported_type(obj):", "function_name": "is_supported_type", "parameter_list": "(obj)" }, { "docstring": null, "function_declaration": "def secure_marshal_dump(value, file_path):", "function_name": "secure_marshal_dump", "param...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import marshal\n\ndef is_supported_type(obj):\n if isinstance(obj, (int, float, str, bool, type(None))):\n return True\n elif isinstance(obj, (list, tuple,...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00019495", "row_id": 19495, "seed_ids": "[190]" }
0.506856
Docs: Python310_19495
I
[ "is_supported_type", "secure_marshal_dump", "secure_marshal_load" ]
3
[ [ "secure_marshal_dump", "is_supported_type" ], [ "secure_marshal_load", "is_supported_type" ] ]
2
[]
false
[]
false
pytest
false
[]
true
0443863bcb84f8840f436f4e38c6e43d06a402b6
e14352ac52de451aeb029eebdce963d3a713acf2
v1.0
instruct
Docs
Docs: Python310_19616_I
**Objective**: To assess the understanding and application of asynchronous programming concepts in Python using the `asyncio` package. **Problem Statement:** You are tasked with developing a simple asynchronous simulation of a library system where users can borrow and return books. The library system must handle mult...
import asyncio import random from typing import List, Tuple library_books = ["book1", "book2", "book3", "book4", "book5"] async def borrow_book(user_id: int, book_title: str) -> str: await asyncio.sleep(random.randint(1, 3)) if book_title in library_books: library_books.remove(book_title) retu...
import pytest import asyncio from solution import borrow_book, return_book, manage_library, library_books @pytest.mark.asyncio async def test_borrow_book_available(): test_books = ["test_book1"] user_id = 1 book_title = "test_book1" global library_books library_books = test_books.copy() result ...
[]
[ 0, 1, 1, 1, 1, 1, 1, 1, 0 ]
7
easy
0.778
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import asyncio\nimport random\nfrom typing import List, Tuple\n\n# Shared library collection\nlibrary_books = [\"book1\", \"book2\", \"book3\",...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00019616", "row_id": 19616, "seed_ids": "[317]" }
0.433776
Docs: Python310_19616
I
[ "borrow_book", "return_book", "manage_library", "main" ]
4
[ [ "manage_library", "borrow_book" ], [ "manage_library", "return_book" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b40b75d26767ca870822d0ad0f7d528771196b71
dd1fdbb94e8bebf9b9f74621c048cb54176647f2
v1.0
instruct
Docs
Docs: Python310_19617_I
**Objective**: Demonstrate your understanding of using the `concurrent.futures` module to asynchronously execute tasks with both thread and process pools. #### Problem: You are required to write a function `factorial_sum(n: int) -> int` that calculates the sum of the factorials of all numbers from 1 to `n` (inclusive...
import concurrent.futures import math import time def compute_factorial(num: int) -> int: """ Compute the factorial of a specified number. Args: num (int): The number to compute the factorial for. Returns: int: The factorial of the number. """ return math.factorial(num) def factorial...
from solution import factorial_sum def test_factorial_sum_small_number(): assert factorial_sum(1) == 1 def test_factorial_sum_larger_number(): assert factorial_sum(3) == 9 # 1! + 2! + 3! = 1 + 2 + 6 = 9 def test_factorial_sum_upper_limit(): # We will not calculate the strict expected value here since i...
[ { "docstring": "Compute the factorial of a specified number.\n\nArgs:\nnum (int): The number to compute the factorial for.\n\nReturns:\nint: The factorial of the number.", "function_declaration": "def compute_factorial(num):", "function_name": "compute_factorial", "parameter_list": "(num)" }, { ...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import concurrent.futures\nimport math\nimport time\n\n\ndef compute_factorial(num: int) -> int:\n \"\"\"\n Computes the factorial of the given number.\n \"\"\...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00019617", "row_id": 19617, "seed_ids": "[224]" }
0.72849
Docs: Python310_19617
I
[ "compute_factorial", "factorial_sum" ]
2
[ [ "factorial_sum", "compute_factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6e3519dc1bad572425ed311b3e2325422907e317
91aac7f5a16cae92123547718861f5c0833084b1
v1.0
instruct
Docs
Docs: Pytorch_19695_I
**Function Vectorization and Differentiability with Limited In-Place Operations using PyTorch** ### Objective Demonstrate your understanding of `torch.func` by implementing and transforming a function that is compatible with `vmap` and `grad`, and handles in-place operations cautiously. ### Problem You are provided...
import torch from torch.func import vmap, grad def transform_and_multiply(x: torch.Tensor, y: torch.Tensor, transform) -> torch.Tensor: """ Apply transformation function to the first tensor (without in-place modification), and then return element-wise multiplication with the second tensor. Args: x...
import torch from solution import transform_and_multiply, compute_gradient def test_transform_and_multiply_identity(): def identity_transform(tensor): return tensor x = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) y = torch.tensor([[2.0, 2.0], [2.0, 2.0]]) result = transform_and_multiply(x, y, i...
[ { "docstring": "Apply transformation function to the first tensor (without in-place modification),\nand then return element-wise multiplication with the second tensor.\n\nArgs:\nx (torch.Tensor): The input tensor to transform.\ny (torch.Tensor): The second tensor to multiply with.\ntransform (callable): The tra...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.func import vmap, grad\n\ndef transform_and_multiply(x: torch.Tensor, y: torch.Tensor, transform) -> torch.Tensor:\n \"\"\"\n Apply trans...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00019695", "row_id": 19695, "seed_ids": "[136]" }
0.527979
Docs: Pytorch_19695
I
[ "transform_and_multiply", "compute_gradient" ]
2
[ [ "compute_gradient", "transform_and_multiply" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
db44a71dea41269c1a1482875896ce6efd0a69b2
53dc5d546ba34d07e138961c027007a70fee7a2a
v1.0
instruct
Docs
Docs: Python310_19717_I
## Question ### Objective: Create utility functions for escaping and unescaping XML character entities and preparing attribute values for XML elements, similar to the functionality provided in the `xml.sax.saxutils` module. ### Task: You are tasked with implementing three functions: 1. `custom_escape(data: str, entit...
def custom_escape(data: str, entities: dict = None) -> str: """Escape XML characters in the data string.""" if entities is None: entities = {} # These are the basic XML escape entities base_entities = {"&": "&amp;", "<": "&lt;", ">": "&gt;"} # Update with additional entities if provided ...
from solution import custom_escape, custom_unescape, custom_quoteattr def test_custom_escape_basic(): assert custom_escape("5 < 6 & 7 > 4") == "5 &lt; 6 &amp; 7 &gt; 4" def test_custom_escape_with_entities(): assert custom_escape("5 < 6 & 7 > 4", {"5": "five", "4": "four"}) == "five &lt; 6 &amp; 7 &gt; four" ...
[ { "docstring": "Escape XML characters in the data string.", "function_declaration": "def custom_escape(data, entities=None):", "function_name": "custom_escape", "parameter_list": "(data, entities=None)" }, { "docstring": "Unescape XML characters in the data string.", "function_declaratio...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def custom_escape(data: str, entities: dict = None) -> str:\n \"\"\"Escape XML characters in the data string.\"\"\"\n if entities is None:\n entities = {}\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00019717", "row_id": 19717, "seed_ids": "[326]" }
0.527769
Docs: Python310_19717
I
[ "custom_escape", "custom_unescape", "custom_quoteattr" ]
3
[ [ "custom_quoteattr", "custom_escape" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a5547a3baa70e4c88083dc1faad27d94dca16334
f3455cbf5506cd159182020f19e07aba99dc7460
v1.0
instruct
Docs
Docs: Python310_19746_I
Custom Warning Handling and Filtering #### Objective: Implement a function that generates various types of warnings, applies custom filters to them, and handles the warnings in specified ways. #### Task: 1. **Create a function `custom_warning_emitter(inputs)`** that: - Takes a list of tuples as input where each ...
import warnings def custom_warning_emitter(inputs): warning_category_map = { 'UserWarning': UserWarning, 'DeprecationWarning': DeprecationWarning, 'SyntaxWarning': SyntaxWarning, 'RuntimeWarning': RuntimeWarning, 'FutureWarning': FutureWarning } for message, cat...
import warnings from solution import custom_warning_emitter, apply_warning_filter, handle_warnings def test_custom_warning_emitter(): inputs = [ ("Test UserWarning", "UserWarning", 10), ("Test DeprecationWarning", "DeprecationWarning", 20), ("Test SyntaxWarning", "SyntaxWarning", 30), ...
[ { "docstring": null, "function_declaration": "def custom_warning_emitter(inputs):", "function_name": "custom_warning_emitter", "parameter_list": "(inputs)" }, { "docstring": null, "function_declaration": "def apply_warning_filter(action, category):", "function_name": "apply_warning_f...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import warnings\n\ndef custom_warning_emitter(inputs):\n \"\"\"\n Emit custom warnings based on the input list of tuples.\n \"\"\"\n warning_map = {\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00019746", "row_id": 19746, "seed_ids": "[125]" }
0.472262
Docs: Python310_19746
I
[ "custom_warning_emitter", "apply_warning_filter", "handle_warnings" ]
3
[ [ "handle_warnings", "apply_warning_filter" ], [ "handle_warnings", "custom_warning_emitter" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b4231af6b738ec1fde8b6fd2e4bd69169fd24834
99b042a7232d2cbf8267d15db7d5374756290019
v1.0
instruct
Docs
Docs: Python310_19775_I
**Asynchronous Tasks and Future Objects** **Objective:** Implement and manage asynchronous operations using `asyncio.Future` objects to ensure that your function can handle low-level callback-based code and integrate it with high-level async/await code. Demonstrate the ability to set, retrieve results, and manage exc...
import asyncio async def _set_future_result(future, delay, value): """ Sets the result of the provided Future object after a specified delay. """ await asyncio.sleep(delay) future.set_result(value) async def manage_task(futures): """ Manages multiple Future objects, setting their results a...
import asyncio import pytest from solution import manage_task @pytest.mark.asyncio async def test_manage_task_basic(): test_futures = [(1, 'foo'), (2, 'bar'), (3, 'baz')] result = await manage_task(test_futures) assert result == {0: 'foo', 1: 'bar', 2: 'baz'} @pytest.mark.asyncio async def test_manage_tas...
[]
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def _set_future_result(future, delay, value):\n \"\"\"\n Sets the result of the provided Future object after a specified delay.\n \"\"\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00019775", "row_id": 19775, "seed_ids": "[113]" }
0.605816
Docs: Python310_19775
I
[ "_set_future_result", "manage_task" ]
2
[ [ "manage_task", "_set_future_result" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2f0c5d51f7eade0dfb6100514deccc48876a52fa
88d140f9e42312705d54b3e6e90770ab0eb3e8a3
v1.0
instruct
Docs
Docs: Python310_19796_I
**Asynchronous HTTP Server with Task Reporting** You are tasked with creating an asynchronous HTTP server that listens for incoming requests and performs various tasks. You must use Python's `asyncio` package to handle the concurrency. The server should have the following features: 1. **Endpoint `/task`**: - When...
import asyncio import logging import uuid from aiohttp import web # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) asyncio.get_event_loop().set_debug(True) # Dictionary to store tasks tasks = {} def generate_task_id(): return str(uuid.uuid4()) async def long_runni...
import asyncio import pytest from aiohttp import web from aiohttp.test_utils import TestClient, TestServer, loop_context from solution import app, long_running_task, generate_task_id, tasks @pytest.mark.asyncio async def test_handle_task(): async with TestClient(TestServer(app)) as client: resp = await cli...
[ { "docstring": null, "function_declaration": "def generate_task_id():", "function_name": "generate_task_id", "parameter_list": "()" } ]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nfrom aiohttp import web\n\ntasks = {}\nstatus_map = { 'pending': 'pending', 'running': 'running', 'completed': 'completed' }\ntask_count...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00019796", "row_id": 19796, "seed_ids": "[200]" }
0.650633
Docs: Python310_19796
I
[ "generate_task_id", "long_running_task", "handle_task", "handle_status" ]
4
[ [ "handle_task", "generate_task_id" ], [ "handle_task", "long_running_task" ] ]
2
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
1b51d89d46be842a5f2e928376f72e42d043c341
7843dfe428b3cd9612cd8b98e64dcfcbe2388611
v1.0
instruct
Docs
Docs: Python310_19817_I
### Python Coding Assessment: Py_Compile Module **Objective**: Implement a custom Python function that utilizes the `py_compile` module to compile a list of Python source files and handle errors efficiently. Additionally, create helper functions to enhance error reporting and logging. ### Instructions You are requir...
import py_compile import os from datetime import datetime from typing import List def compile_python_files(files: List[str], output_dir: str = None, optimize: int = 0, quiet: int = 0) -> List[str]: compiled_files = [] errors = [] for file in files: try: compiled_file = py_compile.compi...
import os import pytest from solution import compile_python_files, log_compile_errors @pytest.fixture def create_files(): file_names = ["test1.py", "test2.py"] for fn in file_names: with open(fn, "w") as f: f.write("print('Hello, World!')\n") yield file_names for fn in file_names: ...
[ { "docstring": null, "function_declaration": "def compile_python_files(files, output_dir=None, optimize=0, quiet=0):", "function_name": "compile_python_files", "parameter_list": "(files, output_dir=None, optimize=0, quiet=0)" }, { "docstring": null, "function_declaration": "def log_compi...
[ 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 py_compile\nfrom typing import List\nimport os\nfrom datetime import datetime\n\ndef compile_python_files(files: List[str], output_dir: str = None, optimize: int...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00019817", "row_id": 19817, "seed_ids": "[201]" }
0.520899
Docs: Python310_19817
I
[ "compile_python_files", "log_compile_errors" ]
2
[ [ "compile_python_files", "log_compile_errors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2e89b7cc6282da7c5a116fbf5ff95145dcae05c4
ac425376b5f5d65d5f7d646a2c2ec2188202f106
v1.0
instruct
Docs
Docs: Python310_19849_I
You are required to develop a Python program that mimics a simple server-client model using the asyncio event loop methods. The task focuses on your understanding of scheduling callbacks, creating futures/tasks, managing network connections, and handling asynchronous IO. ### Problem Statement: 1. **Server Implementat...
import asyncio async def handle_client(reader, writer): client_addr = writer.get_extra_info('peername') print(f"Connected to {client_addr}") writer.write("Welcome to the echo server!\n".encode()) await writer.drain() while True: data = await reader.read(100) if not data: ...
import asyncio import pytest from asyncio import StreamReader, StreamWriter from solution import start_server, handle_client, client_message, run_server_and_client @pytest.fixture def event_loop(): loop = asyncio.get_event_loop() yield loop loop.close() @pytest.mark.asyncio async def test_handle_client(ev...
[ { "docstring": null, "function_declaration": "def run_server_and_client():", "function_name": "run_server_and_client", "parameter_list": "()" } ]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n client_addr = writer.get_extra_info('peername')\n print(f\"Connected to {client_addr}\")\n writer....
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00019849", "row_id": 19849, "seed_ids": "[267]" }
0.663321
Docs: Python310_19849
I
[ "handle_client", "start_server", "client_message", "run_server_and_client" ]
4
[ [ "run_server_and_client", "client_message" ], [ "run_server_and_client", "start_server" ], [ "start_server", "handle_client" ] ]
3
[]
false
[]
false
pytest
true
[]
true
b42b5e9699e27193a30abab36d3fef21693a7765
0fcbf8d1f100bcde5b66af5716a29169b7094dd5
v1.0
instruct
Docs
Docs: Scikit_19857_I
### Out-of-Core Learning System Implementation #### Objective: Implement an out-of-core learning system using Scikit-learn to classify text documents. Your task is to design a system that processes data in mini-batches, extracts features using vectorization, and trains an incremental classifier. #### Instructions: 1...
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier import numpy as np def data_stream(documents, batch_size): """ Generator that yields mini-batches of documents. Parameters: - documents (list): List of text documents. - batch_size (int...
from solution import train_out_of_core_model, data_stream from sklearn.feature_extraction.text import HashingVectorizer import numpy as np def test_data_stream(): documents = ["doc1", "doc2", "doc3", "doc4"] result = list(data_stream(documents, batch_size=2)) assert result == [["doc1", "doc2"], ["doc3", "d...
[ { "docstring": "Generator that yields mini-batches of documents.\n\nParameters:\n- documents (list): List of text documents.\n- batch_size (int): Size of mini-batches.\n\nYields:\n- List of documents in the current mini-batch.", "function_declaration": "def data_stream(documents, batch_size):", "functio...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nimport numpy as np\n\ndef data_stream(documents, batch_si...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00019857", "row_id": 19857, "seed_ids": "[63]" }
0.501624
Docs: Scikit_19857
I
[ "data_stream", "train_out_of_core_model" ]
2
[ [ "train_out_of_core_model", "data_stream" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
fa140bb498af7359942032100de4b5b3c262e6a5
34a6e337d2d63518f3926f03193532fc53182301
v1.0
instruct
Docs
Docs: Pytorch_19871_I
### PyTorch Gradient Check Implementation **Objective:** Implement a custom PyTorch function and use `torch.autograd.gradcheck` and `torch.autograd.gradgradcheck` to verify the correctness of its gradient computations. **Instructions:** 1. **Function Implementation:** - Implement a custom PyTorch function `my_fu...
import torch from torch.autograd import Function class MyFunc(Function): @staticmethod def forward(ctx, input): # Compute any operation, for example, y = x^3 + 4 * x^2 - 7 * x ctx.save_for_backward(input) return input ** 3 + 4 * input ** 2 - 7 * input @staticmethod def backward...
import pytest import torch from solution import my_func, run_gradcheck def test_my_func_gradcheck(): gradcheck_result, gradgradcheck_result = run_gradcheck() assert gradcheck_result, "Gradcheck failed!" assert gradgradcheck_result, "Gradgradcheck failed!" def test_my_func_on_scalar(): input = torch.te...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.autograd import Function\n\nclass MyFunc(Function):\n @staticmethod\n def forward(ctx, input):\n # Compute any operation, for exam...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00019871", "row_id": 19871, "seed_ids": "[179]" }
0.504049
Docs: Pytorch_19871
I
[ "my_func", "run_gradcheck" ]
2
[ [ "run_gradcheck", "my_func" ] ]
1
[]
false
[ "MyFunc" ]
true
pytest
true
[ "torch" ]
false
ae8f710ba2bb4b85b8b310739e533f3b647a562e
9384cceaa24c07c95e9e8ac3531c80a7f185db64
v1.0
instruct
Docs
Docs: Python310_19872_I
**Question: Create a Terminal-based Chat Application using the `pty` module** In this task, you need to implement a terminal-based chat application that mimics a simple chat server-client interaction. The server and client will be separate processes, with the server process able to handle multiple clients simultaneous...
import os import pty import fcntl import select import logging LOG_FILE = 'chat_log.txt' def setup_logger(): logger = logging.getLogger('chat_logger') handler = logging.FileHandler(LOG_FILE) formatter = logging.Formatter('%(asctime)s - %(message)s') handler.setFormatter(formatter) logger.addHandle...
import os import pty import pytest import subprocess import time def test_chat_server(): server_process = subprocess.Popen(['python3', '-c', """ import os import pty import fcntl import select import logging LOG_FILE = 'chat_log.txt' def setup_logger(): logger = logging.getLogger('chat_logger') handler =...
[ { "docstring": null, "function_declaration": "def setup_logger():", "function_name": "setup_logger", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def read_from_client(client_fd, clients):", "function_name": "read_from_client", "parameter_list": "(client...
[ 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 pty\nimport select\nimport sys\nimport threading\n\nLOG_FILE = 'chat_log.txt'\n\nclients = []\n\ndef handle_client(master_fd, client_fd):\n \"\"\"\...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00019872", "row_id": 19872, "seed_ids": "[145]" }
0.539444
Docs: Python310_19872
I
[ "setup_logger", "read_from_client", "remove_client", "broadcast_message", "start_server", "start_client" ]
6
[ [ "read_from_client", "broadcast_message" ], [ "read_from_client", "remove_client" ], [ "start_server", "read_from_client" ] ]
3
[]
false
[]
false
pytest
false
[]
true
9f5cf09503e03f6972607d1968aeadb7cde7d8d4
43cdf3487f703f7b8f05cb83c25a69c41b5946ac
v1.0
instruct
Docs
Docs: Pytorch_19879_I
#### Objective Implement and compose different function transforms using the `torch.func` module to compute gradients and per-sample-gradients for a given function. This will test your comprehension of `torch.func`'s functionalities and your ability to apply them. #### Question You are given a function `f(x)` defined...
import torch import torch.func as func def f(x): return torch.sum(torch.sin(x) * torch.exp(x)) def compute_gradient(x): grad_f = func.grad(f) return grad_f(x) def compute_per_sample_gradients(X): grad_f = func.grad(f) vmap_grad_f = func.vmap(grad_f) return vmap_grad_f(X)
import torch from solution import compute_gradient, compute_per_sample_gradients def test_compute_gradient(): x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True) expected_gradient = torch.cos(x) * torch.exp(x) + torch.sin(x) * torch.exp(x) actual_gradient = compute_gradient(x) assert torch.allclose(a...
[ { "docstring": null, "function_declaration": "def f(x):", "function_name": "f", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def compute_gradient(x):", "function_name": "compute_gradient", "parameter_list": "(x)" }, { "docstring": null, "fu...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.func as func\n\ndef f(x):\n return torch.sum(torch.sin(x) * torch.exp(x))\n\ndef compute_gradient(x):\n return func.grad(f)(x)\n\ndef c...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00019879", "row_id": 19879, "seed_ids": "[56]" }
0.558774
Docs: Pytorch_19879
I
[ "f", "compute_gradient", "compute_per_sample_gradients" ]
3
[ [ "compute_gradient", "f" ], [ "compute_per_sample_gradients", "f" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
0f507d42cfe226facbbaa956ebbb6f5bb6e5d4bb
db6e7f38701ba3ad1af69221ad5e7bea830713a3
v1.0
instruct
Docs
Docs: Scikit_19944_I
### Permutation Feature Importance Analysis #### Objective You are tasked with evaluating the importance of features in a dataset for a regression problem using permutation feature importance. You will train a regression model, compute feature importances using permutations, and handle correlated features. Your imple...
from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split from sklearn.linear_model import Ridge from sklearn.inspection import permutation_importance from scipy.cluster.hierarchy import linkage, fcluster import numpy as np def handle_correlated_features(X, threshold=0.9): """...
from solution import permutation_feature_importance_analysis def test_permutation_feature_importance_analysis(): result = permutation_feature_importance_analysis(n_repeats=10, random_state=42) assert len(result) > 0, "The result should contain feature importances" for feature, importance_mean, importa...
[ { "docstring": "Identify and handle correlated features by clustering and returning one feature per cluster.", "function_declaration": "def handle_correlated_features(X, threshold=0.9):", "function_name": "handle_correlated_features", "parameter_list": "(X, threshold=0.9)" }, { "docstring": ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.datasets import load_diabetes\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import Ridge\nfrom sklearn.inspection import...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00019944", "row_id": 19944, "seed_ids": "[33]" }
0.56572
Docs: Scikit_19944
I
[ "handle_correlated_features", "permutation_feature_importance_analysis" ]
2
[ [ "permutation_feature_importance_analysis", "handle_correlated_features" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "scipy", "sklearn" ]
false
c8865c86dae365900eccc521a37c65de54072ae0
145f3eada7d2079ede4f67f71a341a2aa3859e42
v1.0
instruct
Docs
Docs: Pytorch_19945_I
#### Objective: The goal of this question is to assess your understanding of asynchronous execution using the `torch.futures` package. You will write code to handle multiple asynchronous operations and combine their results. #### Problem Statement: You are given an asynchronous function `fetch_data` that fetches data ...
from typing import List import torch import threading import time def fetch_data(source: int) -> torch.futures.Future: # Simulating an async fetch operation future = torch.futures.Future() def async_fetch(): time.sleep(0.1) # Simulate some delay future.set_result(f"data_from_source_{source}...
from solution import process_multiple_sources, fetch_data def test_process_multiple_sources(): sources = [1, 2, 3] expected = ['data_from_source_1', 'data_from_source_2', 'data_from_source_3'] assert process_multiple_sources(sources) == expected def test_process_multiple_sources_single_source(): sourc...
[ { "docstring": null, "function_declaration": "def fetch_data(source):", "function_name": "fetch_data", "parameter_list": "(source)" }, { "docstring": null, "function_declaration": "def process_multiple_sources(sources):", "function_name": "process_multiple_sources", "parameter_li...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom typing import List\n\ndef fetch_data(source: int) -> torch.futures.Future:\n # Simulating an async fetch operation\n future = torch.futures.Fut...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00019945", "row_id": 19945, "seed_ids": "[53]" }
0.470762
Docs: Pytorch_19945
I
[ "fetch_data", "process_multiple_sources" ]
2
[ [ "process_multiple_sources", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
803212f94c4736fa4b86c6e25409636104504489
b927d5ee4f8951d8569ac55475b6ba15eb69207b
v1.0
instruct
Docs
Docs: Python310_19964_I
### Question: Implement a Multi-threaded Counter with Synchronization You are tasked with implementing a multi-threaded counter using the low-level `_thread` module. This counter will be shared among multiple threads, and proper synchronization must be used to ensure accurate results. **Instructions:** 1. Implement...
import _thread from time import sleep class ThreadSafeCounter: def __init__(self): self.counter = 0 self.lock = _thread.allocate_lock() def increment(self): with self.lock: self.counter += 1 def get_value(self): with self.lock: return self.counter ...
from solution import ThreadSafeCounter, increment_counter, run_threads def test_thread_safe_counter_initial_value(): counter = ThreadSafeCounter() assert counter.get_value() == 0 def test_thread_safe_counter_increment(): counter = ThreadSafeCounter() counter.increment() assert counter.get_value() ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import _thread\nfrom threading import Event\n\nclass ThreadSafeCounter:\n \"\"\"Safe counter for multi-threading.\"\"\"\n def __init__(self):\n self.counte...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00019964", "row_id": 19964, "seed_ids": "[223]" }
0.518303
Docs: Python310_19964
I
[ "increment_counter", "run_threads" ]
2
[ [ "run_threads", "increment_counter" ] ]
1
[]
false
[ "ThreadSafeCounter" ]
true
pytest
true
[]
true
993084b6c5e004faa932ef4b0fcfe2fd760507a0
e2d5f9f3af105b7ab3d19e3bc785561f1a007349
v1.0
instruct
Docs
Docs: Pytorch_20003_I
### PyTorch MPS Backend Assessment In this question, you are required to demonstrate your understanding of the MPS backend in PyTorch. You will write functions to check MPS availability, perform tensor operations on the MPS device, and handle a simple neural network model using the MPS device. #### Part 1: MPS Availa...
import torch def check_mps_availability() -> bool: """ Checks whether the MPS backend is available. Returns: bool: True if MPS is available, False otherwise. """ return torch.backends.mps.is_available() def perform_tensor_operations(shape: tuple, operation: str): """ Creates a ten...
import torch import pytest from solution import check_mps_availability, perform_tensor_operations, move_model_to_mps def test_check_mps_availability(): assert isinstance(check_mps_availability(), bool) def test_perform_tensor_operations_add(): if not check_mps_availability(): pytest.skip("MPS backend ...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef check_mps_availability() -> bool:\n \"\"\"\n Checks whether the MPS backend is available.\n\n Returns:\n bool: True if MPS is availa...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00020003", "row_id": 20003, "seed_ids": "[167]" }
0.475449
Docs: Pytorch_20003
I
[ "check_mps_availability", "perform_tensor_operations", "move_model_to_mps" ]
3
[ [ "move_model_to_mps", "check_mps_availability" ], [ "perform_tensor_operations", "check_mps_availability" ] ]
2
[]
false
[ "SimpleNet" ]
true
pytest
true
[ "torch" ]
false
72882ec7d65546b4f3f77752bf503fc3e30d529a
e1c1cd69b1f2929b5645d7f5b297a1ce7d1413aa
v1.0
instruct
Docs
Docs: Python310_20008_I
### Context Variables Management in Python You are required to demonstrate your understanding of the `contextvars` module in Python by implementing a function that manages context variables during the execution of a code block. #### Objective 1. Implement a decorator function `manage_context` that: - Accepts a d...
from contextvars import ContextVar, copy_context from functools import wraps def manage_context(context_vars): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): originals = {} temp_context = copy_context() for var_name, new_value in context_vars.it...
from solution import demo_function, var1, var2, manage_context def test_demo_function_var1(): original_value = var1.get() assert demo_function('var1') == 'temp_value1' assert var1.get() == original_value def test_demo_function_var2(): original_value = var2.get() assert demo_function('var2') == 'te...
[ { "docstring": null, "function_declaration": "def manage_context(context_vars):", "function_name": "manage_context", "parameter_list": "(context_vars)" }, { "docstring": null, "function_declaration": "def demo_function(var_name):", "function_name": "demo_function", "parameter_lis...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from contextvars import ContextVar, copy_context\nfrom functools import wraps\n\ndef manage_context(context_vars):\n def decorator(func):\n @wraps(func)\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00020008", "row_id": 20008, "seed_ids": "[60]" }
0.389408
Docs: Python310_20008
I
[ "manage_context", "demo_function" ]
2
[ [ "demo_function", "manage_context" ] ]
1
[]
false
[]
false
pytest
true
[]
true
baedec520c736a156154487e75dd131efdf73ab7
88db3d7d274e2451edd47d7d7edb2e80dce9de2d
v1.0
instruct
Docs
Docs: Python310_20058_I
### Custom Type Inheritance and Management in Python In this assessment, you are required to implement custom types in Python that mimic some of the capabilities described in the `PyTypeObject` documentation. The task will assess your ability to create a complex type hierarchy, utilize type checking, inheritance, and ...
class CustomType: type_name = "CustomType" def describe(self): return f"This is a {self.type_name}" class DerivedType(CustomType): type_name = "DerivedType" def describe(self): return f"This is a derived type: {self.type_name}" class AnotherType: pass def is_cust...
from solution import CustomType, DerivedType, AnotherType, is_custom_type, get_type_name def test_describe_methods(): base = CustomType() assert base.describe() == "This is a CustomType" derived = DerivedType() assert derived.describe() == "This is a derived type: DerivedType" def test_is_custom_...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class CustomType:\n type_name = \"CustomType\"\n \n def describe(self):\n return f\"This is a {self.type_name}\"\n\nclass DerivedType(CustomType):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00020058", "row_id": 20058, "seed_ids": "[48]" }
0.511421
Docs: Python310_20058
I
[ "is_custom_type", "get_type_name" ]
2
[ [ "get_type_name", "is_custom_type" ] ]
1
[]
false
[ "CustomType", "DerivedType", "AnotherType" ]
true
pytest
true
[]
true
b2d3fb3d1dcb78054fec7f7544c0d5b6a5864745
5343a308df012b10ea6010add44b4e9ca25611aa
v1.0
instruct
Docs
Docs: Python310_20077_I
#### Objective To assess your understanding of Python socket programming, regular expressions, and file handling, you are tasked with implementing a server-client application where the server processes text data and the client sends requests to the server. #### Problem Statement 1. **Server Implementation** Impl...
import socket import threading import re # Server Implementation def extract_emails(text): # Regex pattern to match email addresses email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' emails = re.findall(email_pattern, text) return ','.join(emails) def handle_client(client_socket): t...
import pytest import socket import threading from solution import start_server, start_client, extract_emails, read_file def test_extract_emails(): text = "Contact us at example@example.com or at test.email@example.co.uk. Thank you." expected = "example@example.com,test.email@example.co.uk" assert extract_e...
[ { "docstring": null, "function_declaration": "def extract_emails(text):", "function_name": "extract_emails", "parameter_list": "(text)" }, { "docstring": null, "function_declaration": "def handle_client(client_socket):", "function_name": "handle_client", "parameter_list": "(clien...
[ 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 socket\nimport threading\nimport re\n\n# Server Implementation\ndef extract_emails(text):\n # Regex pattern to match email addresses\n email_pattern = r'[a...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00020077", "row_id": 20077, "seed_ids": "[73]" }
0.571785
Docs: Python310_20077
I
[ "extract_emails", "handle_client", "start_server", "read_file", "start_client" ]
5
[ [ "handle_client", "extract_emails" ], [ "start_client", "read_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4f5e81537e8033023f198d2873801a1f6e54b1d3
3957deb46a9c6e84dd7d5666c3ab89ee6880e57a
v1.0
instruct
Docs
Docs: Python310_20132_I
You are tasked with improving the performance of a CPU-bound task by implementing concurrent execution. The task involves calculating the nth Fibonacci number, but with added complexity to simulate a CPU-bound workload. To achieve this, you need to write a function `parallel_fibonacci` that uses both threading and mul...
import threading import multiprocessing import time def fibonacci(n): if n <= 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def fibonacci_threading(n, result, index): result[index] = fibonacci(n) def fibonacci_multiprocessing(n, result, ind...
from solution import parallel_fibonacci def test_parallel_fibonacci_small(): result = parallel_fibonacci(5) assert result['fibonacci'] == 5 assert result['threading_time'] >= 0 assert result['multiprocessing_time'] >= 0 def test_parallel_fibonacci_medium(): result = parallel_fibonacci(15) asse...
[ { "docstring": null, "function_declaration": "def fibonacci(n):", "function_name": "fibonacci", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def fibonacci_threading(n, result, index):", "function_name": "fibonacci_threading", "parameter_list": "(n, res...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import threading\nimport multiprocessing\nimport time\n\ndef fibonacci(n):\n \"\"\"Recursive function to calculate the nth Fibonacci number.\"\"\"\n if n <= 0:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00020132", "row_id": 20132, "seed_ids": "[206]" }
0.579116
Docs: Python310_20132
I
[ "fibonacci", "fibonacci_threading", "fibonacci_multiprocessing", "parallel_fibonacci" ]
4
[ [ "fibonacci_multiprocessing", "fibonacci" ], [ "fibonacci_threading", "fibonacci" ] ]
2
[]
false
[]
false
pytest
true
[]
true
93c3b56be13903f69fd91a21e87476c52ff1c72c
f6d3f12b45821f31b27120a3021d863da34d25d6
v1.0
instruct
Docs
Docs: Python310_20137_I
### Advanced Coding Assessment Question: PyCapsule Manipulation in Python #### Overview: In this coding task, you will need to create and manipulate `PyCapsule` objects in Python using C extension modules. The goal is to interact with these capsules by setting and retrieving their attributes such as pointers, names, c...
import ctypes from ctypes import CFUNCTYPE, c_void_p, py_object import builtins # Mocks to represent PyCapsule C API behavior in pure Python def PyCapsule_New(pointer, name, destructor): capsule = py_object() capsule.pointer = pointer capsule.name = name capsule.context = None capsule.destructor =...
from solution import create_capsule, set_new_pointer, validate_capsule, mock_destructor import pytest def test_create_capsule(): capsule = create_capsule(1000, "module.attribute", 2000) assert capsule.pointer == 1000 assert capsule.name == "module.attribute" assert capsule.context == 2000 def test_set...
[ { "docstring": null, "function_declaration": "def PyCapsule_New(pointer, name, destructor):", "function_name": "PyCapsule_New", "parameter_list": "(pointer, name, destructor)" }, { "docstring": null, "function_declaration": "def PyCapsule_GetPointer(capsule, name):", "function_name":...
[ 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 ctypes\nfrom cpython import capsule\n\ndef create_capsule(pointer: int, name: str, context: int):\n \"\"\"\n Creates a PyCapsule object encapsulating a moc...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00020137", "row_id": 20137, "seed_ids": "[16]" }
0.383429
Docs: Python310_20137
I
[ "PyCapsule_New", "PyCapsule_GetPointer", "PyCapsule_GetName", "PyCapsule_GetContext", "PyCapsule_SetPointer", "PyCapsule_SetDestructor", "mock_destructor", "create_capsule", "set_new_pointer", "validate_capsule" ]
10
[ [ "create_capsule", "PyCapsule_New" ], [ "create_capsule", "mock_destructor" ], [ "set_new_pointer", "PyCapsule_SetPointer" ], [ "validate_capsule", "PyCapsule_GetName" ] ]
4
[]
false
[]
false
pytest
true
[]
true
b41ab8577c9a2e4a756abb8601a4afdae8a70b15
85358d8e915dc8d2bb800fc09aef286edc26089b
v1.0
instruct
Docs
Docs: Pandas_20147_I
**Objective:** Demonstrate your understanding of the `pandas` `groupby` functionality by performing a series of data manipulations involving aggregation, transformation, and filtering. ### Problem Statement You are provided with a `pandas` DataFrame containing information about sales transactions. Each row represents...
import pandas as pd from scipy.stats import zscore def create_dataframe(): data = { "ProductID": [1, 2, 1, 3, 2, 1, 2, 3, 1, 3, 2], "StoreID": [1, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1], "Quantity": [10, 15, 8, 12, 10, 15, 9, 5, 20, 8, 7], "SalesAmount": [100, 150, 80, 120, 100, 150, 90, 50,...
def test_create_dataframe(): df = create_dataframe() assert not df.empty assert len(df) == 11 assert list(df.columns) == ['ProductID', 'StoreID', 'Quantity', 'SalesAmount', 'Date'] def test_aggregate_sales_data(): df = create_dataframe() aggregated_df = aggregate_sales_data(df) assert len(a...
[ { "docstring": null, "function_declaration": "def create_dataframe():", "function_name": "create_dataframe", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def aggregate_sales_data(df):", "function_name": "aggregate_sales_data", "parameter_list": "(df)" ...
[ 0, 1 ]
1
medium
0.5
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom scipy.stats import zscore\n\n# Step 1: Load the Data\ndata = {\n \"ProductID\": [1, 2, 1, 3, 2, 1, 2, 3, 1, 3, 2],...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00020147", "row_id": 20147, "seed_ids": "[16]" }
0.612519
Docs: Pandas_20147
I
[ "create_dataframe", "aggregate_sales_data", "transform_sales_data", "filter_transactions", "process_sales_data" ]
5
[ [ "process_sales_data", "aggregate_sales_data" ], [ "process_sales_data", "create_dataframe" ], [ "process_sales_data", "filter_transactions" ], [ "process_sales_data", "transform_sales_data" ] ]
4
[]
false
[]
false
pytest
false
[ "pandas", "scipy" ]
false
be97063444216f226960e4d4d5d8b7735856e9ef
4cd9a1a2c63f1f4681d9a35ac6dd17d8727fb9c0
v1.0
instruct
Docs
Docs: Scikit_20160_I
### Semi-Supervised Learning with Scikit-Learn In this assessment, you are required to demonstrate your understanding of semi-supervised learning techniques using the `sklearn.semi_supervised` module. Follow the instructions below and implement Python code to complete the task. #### Task 1. **Dataset Preparation**: ...
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_classification from sklearn.tree import DecisionTreeClassifier from sklearn.semi_supervised import SelfTrainingClassifier, LabelPropagation, LabelSpreading from sklearn.metrics import accuracy_score # Step 1: Dataset Preparation def c...
def test_create_dataset(): X, y = create_dataset() assert X.shape == (300, 20) assert len(y) == 300 assert len(np.unique(y)) == 3 # Should contain 2 class labels and -1 for unlabeled def test_self_training_classifier(): X, y = create_dataset() accuracy = self_training_classifier(X, y) asse...
[ { "docstring": null, "function_declaration": "def create_dataset():", "function_name": "create_dataset", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def self_training_classifier(X, y):", "function_name": "self_training_classifier", "parameter_list": "(...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import make_classification\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.sem...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00020160", "row_id": 20160, "seed_ids": "[21]" }
0.54112
Docs: Scikit_20160
I
[ "create_dataset", "self_training_classifier", "label_propagation_methods", "compare_methods" ]
4
[ [ "compare_methods", "create_dataset" ], [ "compare_methods", "label_propagation_methods" ], [ "compare_methods", "self_training_classifier" ] ]
3
[]
false
[]
false
pytest
false
[ "matplotlib", "numpy", "sklearn" ]
false
ca7c780fcf0d2b97ad29d72d13c5622274fd66f2
d58cc8bb18b33d05a689c1bff15cb841ca6a6bae
v1.0
instruct
Docs
Docs: Python310_20260_I
### Context Management with `contextvars` in Python You are required to write a Python script using the `contextvars` module to simulate context management for a multi-threaded or asynchronous environment. #### Task 1. **Define Context Variables**: - Create two context variables, `user_id` and `request_id`, usin...
import contextvars import threading import time # Function to create context variables def create_context_vars(): user_id = contextvars.ContextVar("user_id") request_id = contextvars.ContextVar("request_id") return user_id, request_id # Function to process requests with proper context management def proce...
import contextvars import threading import time from solution import create_context_vars, process_request, handle_request def test_create_context_vars(): user_id, request_id = create_context_vars() assert isinstance(user_id, contextvars.ContextVar) assert isinstance(request_id, contextvars.ContextVar) de...
[ { "docstring": null, "function_declaration": "def create_context_vars():", "function_name": "create_context_vars", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def process_request(user_id_value, request_id_value, user_id, request_id):", "function_name": "pr...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import contextvars\nimport threading\nimport time\n\n# Function to create context variables\ndef create_context_vars():\n user_id = contextvars.ContextVar(\"user_id\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00020260", "row_id": 20260, "seed_ids": "[60]" }
0.475885
Docs: Python310_20260
I
[ "create_context_vars", "process_request", "handle_request" ]
3
[ [ "handle_request", "create_context_vars" ] ]
1
[]
false
[]
false
pytest
true
[]
true
071945b552b3c55c323e4d46aa91e5fa19d20342
f49682def635648662741f85bdd524d5cb67bc7a
v1.0
instruct
Docs
Docs: Scikit_20280_I
### Out-of-Core Learning: Scikit-learn Incremental Learning #### Objective: Implement a scalable classification system utilizing out-of-core learning. Using the provided skeleton code below, complete the functions required to read data in streams, extract features using HashingVectorizer, and perform classification us...
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(file_path, batch_size): """ Generator function to read data from a file in chunks. Args: file_path (str): Path to the text data fi...
from solution import stream_data, extract_features, incremental_learning import os def test_stream_data(tmp_path): file_path = tmp_path / "test_data.txt" lines = [f"Line {i}" for i in range(100)] with open(file_path, 'w') as f: f.write("\n".join(lines)) batches = list(stream_data(file_path...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\n\ndef stream_...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00020280", "row_id": 20280, "seed_ids": "[63]" }
0.487469
Docs: Scikit_20280
I
[ "stream_data", "extract_features", "incremental_learning" ]
3
[ [ "incremental_learning", "extract_features" ], [ "incremental_learning", "stream_data" ] ]
2
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
3bcfd4b3eb23aa2bc281849b270fa04d5c553188
e380e378a16ee3c85d3b3d0e74e6869638bacdc9
v1.0
instruct
Docs
Docs: Python310_20293_I
### Question #### Objective: To assess your understanding of Python's asyncio event loop by implementing a function that utilizes asynchronous tasks, delayed callbacks, and handles task completion. #### Problem Statement: Implement a function named `async_process_tasks` that simulates processing multiple asynchronous...
import asyncio class AsyncTask: def __init__(self, name: str, delay: int, priority: int): self.name = name self.delay = delay self.priority = priority self.result = "Pending" async def process_individual_task(task: AsyncTask): await asyncio.sleep(task.delay) task.result = "...
from solution import AsyncTask, async_process_tasks def test_async_process_tasks_basic(): tasks = [AsyncTask('Task1', 2, 1), AsyncTask('Task2', 1, 2), AsyncTask('Task3', 3, 1)] result = async_process_tasks(tasks) assert result == ['Task2', 'Task1', 'Task3'] def test_async_process_tasks_same_delay(): 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\n\nclass AsyncTask:\n def __init__(self, name: str, delay: int, priority: int):\n self.name = name\n self.delay = delay\n self.pr...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00020293", "row_id": 20293, "seed_ids": "[267]" }
0.640843
Docs: Python310_20293
I
[ "process_individual_task", "async_process_tasks" ]
2
[ [ "async_process_tasks", "process_individual_task" ] ]
1
[]
false
[ "AsyncTask" ]
true
pytest
true
[]
true
a79e1b4ce4857c31451e179124860c7cf7e8337c
34a081a9e094b248a635d84ed97f60fd4b9c74bf
v1.0
instruct
Docs
Docs: Python310_20311_I
### Objective Your task is to demonstrate your understanding of the `wsgiref` package by implementing a simple WSGI-based web application. The application must handle HTTP GET and POST requests efficiently and use several utilities provided by the `wsgiref` module. ### Task Implement a web application that allows us...
from wsgiref.simple_server import make_server from wsgiref.util import setup_testing_defaults, request_uri import cgi quotes = [] def quote_app(environ, start_response): setup_testing_defaults(environ) # Parse request method and URI method = environ['REQUEST_METHOD'] uri = request_uri(environ) h...
from solution import quote_app, quotes from wsgiref.util import setup_testing_defaults from io import BytesIO import pytest def start_response_dummy(status, headers): pass def test_get_request(): environ = {} setup_testing_defaults(environ) environ['REQUEST_METHOD'] = 'GET' response = quote_app(e...
[ { "docstring": null, "function_declaration": "def quote_app(environ, start_response):", "function_name": "quote_app", "parameter_list": "(environ, start_response)" }, { "docstring": null, "function_declaration": "def generate_form(environ):", "function_name": "generate_form", "pa...
[ 0, 0, 0, 0, 1, 0, 0, 1, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from wsgiref.simple_server import make_server\nfrom wsgiref.util import setup_testing_defaults, request_uri\nfrom wsgiref.headers import Headers\nimport cgi\n\n# List t...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00020311", "row_id": 20311, "seed_ids": "[210]" }
0.466839
Docs: Python310_20311
I
[ "quote_app", "generate_form" ]
2
[ [ "quote_app", "generate_form" ] ]
1
[]
false
[]
false
pytest
true
[]
true
65664611ab7fac70649e32b29cab049b1d86feee
73ad1cd7bea75c1b74eafcd7ec90f98b404c4138
v1.0
instruct
Docs
Docs: Pytorch_20335_I
You are required to demonstrate your understanding of the `torch.futures` package by implementing a sequence of asynchronous operations. ### Problem Statement Write a Python function `compute_async_squares` which calculates the squares of a given list of integers asynchronously. Use the `torch.futures` package to car...
import torch import time from typing import List def square_with_delay(number: int) -> torch.futures.Future: future = torch.futures.Future() def delayed_computation(): time.sleep(0.1) future.set_result(number ** 2) # This simulates an asynchronous operation by calling delayed_comp...
from solution import compute_async_squares import torch def test_compute_async_squares_simple(): numbers = [1, 2, 3, 4, 5] expected = [1, 4, 9, 16, 25] assert compute_async_squares(numbers) == expected def test_compute_async_squares_single(): numbers = [10] expected = [100] assert compute_asyn...
[ { "docstring": null, "function_declaration": "def square_with_delay(number):", "function_name": "square_with_delay", "parameter_list": "(number)" }, { "docstring": null, "function_declaration": "def compute_async_squares(numbers):", "function_name": "compute_async_squares", "para...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport time\nfrom typing import List\n\ndef square_with_delay(n: int) -> torch.futures.Future:\n def delayed_square():\n time.sleep(0.1)\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00020335", "row_id": 20335, "seed_ids": "[53]" }
0.501106
Docs: Pytorch_20335
I
[ "square_with_delay", "compute_async_squares" ]
2
[ [ "compute_async_squares", "square_with_delay" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
dcfd85d0b03e8f5bc95367ee828d845da829072f
c66da02fa72ac105676cc41bf68cd00d0ce2ce75
v1.0
instruct
Docs
Docs: Python310_20354_I
### Asyncio Task Orchestrator You are to implement a simplified task orchestrator system using Python's asyncio module. The system will simulate multiple workers fetching and processing data from a shared queue, with support for task cancellation, synchronization, and error handling. #### Requirements 1. **Task Crea...
import asyncio import random async def process_data(data): """Simulate processing data by sleeping for a random short duration.""" await asyncio.sleep(random.uniform(0.1, 0.5)) # Simulate variable processing time return f"Processed {data}" async def create_worker_tasks(n, task_queue, lock, worker_task_co...
import pytest import asyncio from solution import create_worker_tasks, fill_queue, process_data, main @pytest.mark.asyncio async def test_process_data(): data = "test_data" result = await process_data(data) assert result == f"Processed {data}" @pytest.mark.asyncio async def test_fill_queue(): data_lis...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\n\nasync def process_data(data):\n \"\"\"\n Simulates processing data by sleeping for a random short duration.\n \"\"\"\n awai...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00020354", "row_id": 20354, "seed_ids": "[360]" }
0.552022
Docs: Python310_20354
I
[ "process_data", "create_worker_tasks", "fill_queue", "main" ]
4
[ [ "create_worker_tasks", "process_data" ] ]
1
[ "process_data" ]
false
[]
false
pytest
true
[]
true
f42d0629706b0914f2da1c5c9734e10eeffca7b6
e2013eb2176f70500dcc52c4aa3256eb6e4f1f57
v1.0
instruct
Docs
Docs: Python310_20388_I
#### Title: Mocking with unittest.mock #### Description: You are tasked with developing a small data processing function and thoroughly testing it using the `unittest.mock` module. The functionality involves fetching data from an API, processing it, and saving the results to a database. The data fetching and saving fu...
# Placeholder implementations def fetch_data(endpoint): """ Simulated fetch_data function that gets data from an endpoint. This is a placeholder and should be replaced by a mock in tests. """ pass def transform_data(raw_data): """ Simulated transform_data function that processes raw data. ...
from unittest.mock import patch, Mock import unittest from solution import process_data, fetch_data, transform_data, save_data class TestProcessData(unittest.TestCase): @patch('solution.fetch_data') @patch('solution.save_data') @patch('solution.transform_data') def test_process_data(self, mock_transf...
[ { "docstring": "Simulated fetch_data function that gets data from an endpoint.\nThis is a placeholder and should be replaced by a mock in tests.", "function_declaration": "def fetch_data(endpoint):", "function_name": "fetch_data", "parameter_list": "(endpoint)" }, { "docstring": "Simulated t...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def fetch_data(endpoint):\n \"\"\"\n Fetches data from the given endpoint.\n This is a placeholder implementation.\n \"\"\"\n return {\"data\": \"some_da...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00020388", "row_id": 20388, "seed_ids": "[104]" }
0.619453
Docs: Python310_20388
I
[ "fetch_data", "transform_data", "save_data", "process_data" ]
4
[ [ "process_data", "fetch_data" ], [ "process_data", "save_data" ], [ "process_data", "transform_data" ] ]
3
[ "process_data" ]
false
[]
false
pytest
true
[]
true
8786c0a0ddbf6a05ead91c2af08c9045e0f97584
e2e511fc60ffe4c48c0c4bed61a792f60c993dc1
v1.0
instruct
Docs
Docs: Python310_20445_I
**Question:** You are required to profile and optimize the performance of a Python program. The program includes a function that performs a specific task multiple times, which may be computationally intensive. Your task is to: 1. **Profile the function execution using `cProfile`** and collect the profiling data. 2. *...
import cProfile import pstats import io def sample_function(number_list): result = [] for num in number_list: if num % 2 == 0: result.append(num ** 2) else: result.append(num ** 3) return result # Profiling the original function def profile_original_function(): ...
from solution import sample_function, optimized_function import time def test_function_output(): number_list = list(range(100)) assert sample_function(number_list) == optimized_function(number_list), "Outputs do not match" def test_performance_improvement(): number_list = list(range(1000000)) # T...
[ { "docstring": null, "function_declaration": "def sample_function(number_list):", "function_name": "sample_function", "parameter_list": "(number_list)" }, { "docstring": null, "function_declaration": "def profile_original_function():", "function_name": "profile_original_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 cProfile\nimport pstats\nimport io\n\ndef sample_function(number_list):\n result = []\n for num in number_list:\n if num % 2 == 0:\n resu...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00020445", "row_id": 20445, "seed_ids": "[142]" }
0.530795
Docs: Python310_20445
I
[ "sample_function", "profile_original_function", "optimized_function", "profile_optimized_function", "main" ]
5
[ [ "profile_optimized_function", "optimized_function" ], [ "profile_original_function", "sample_function" ] ]
2
[]
false
[]
false
pytest
true
[]
true
02b9493d88fde980defa57654807fbc593826b04
2c6f94a990de81664cc38bf45f844a72ecbcdddb
v1.0
instruct
Docs
Docs: Pytorch_20478_I
### Scenario You have been hired by a tech company to optimize the data processing pipeline of a large machine learning project. The project involves performing computationally intensive transformations on a dataset using multiple processors to decrease the overall processing time. This is a perfect use case for levera...
import torch.multiprocessing as mp def dummy_task(num): """ Squares the input number. Args: num (int): Number to be squared. Returns: int: The square of the input number. """ return num * num def worker(rank, num_processes, inputs, results): """ Worker functio...
from solution import dummy_task, start_and_monitor_processes def test_dummy_task(): assert dummy_task(2) == 4 assert dummy_task(0) == 0 assert dummy_task(-3) == 9 def test_start_and_monitor_processes(): # Test with 4 processes and 4 inputs inputs = [1, 2, 3, 4] num_processes = 4 results = ...
[ { "docstring": "Squares the input number.\n\nArgs:\n num (int): Number to be squared.\n\nReturns:\n int: The square of the input number.", "function_declaration": "def dummy_task(num):", "function_name": "dummy_task", "parameter_list": "(num)" }, { "docstring": "Worker function to be e...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.multiprocessing as mp\n\ndef dummy_task(num):\n \"\"\"\n Returns the square of the input value num.\n \"\"\"\n return num * num\n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00020478", "row_id": 20478, "seed_ids": "[143]" }
0.553179
Docs: Pytorch_20478
I
[ "dummy_task", "worker", "start_and_monitor_processes" ]
3
[ [ "worker", "dummy_task" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
536628b57d0d43b7edcd6026ce1d6c2d0da66829
059909e289576c5b59c5a5e101cdf4d797b3f55a
v1.0
instruct
Docs
Docs: Python310_20496_I
### Design a Text-based User Interface with Curses #### Objective: Design a text-based user interface (TUI) to capture and display user input within a defined area of the terminal screen. The TUI should update in real-time as the user types, handle navigation within the input area, and support basic text editing funct...
import curses from curses.textpad import Textbox, rectangle def main(stdscr): # Initialize curses and settings curses.curs_set(1) curses.noecho() curses.cbreak() stdscr.keypad(True) curses.start_color() curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) # Define window size...
# Note: Testing a curses-based TUI typically involves manual testing, but we can write some tests using `pytest-curses` or similar. # The following is a conceptual framework for manual verification. def test_placeholder(): # Placeholder test function for conceptual framework. # In practice, observe manually ...
[ { "docstring": null, "function_declaration": "def main(stdscr):", "function_name": "main", "parameter_list": "(stdscr)" }, { "docstring": null, "function_declaration": "def run_curses_ui():", "function_name": "run_curses_ui", "parameter_list": "()" }, { "docstring": null,...
[ 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 curses\nfrom curses.textpad import Textbox, rectangle\n\ndef main(stdscr):\n # Initialize curses and settings (no echo, cbreak mode, etc.)\n curses.curs_se...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00020496", "row_id": 20496, "seed_ids": "[294]" }
0.401576
Docs: Python310_20496
I
[ "main", "run_curses_ui" ]
2
[ [ "run_curses_ui", "main" ] ]
1
[]
false
[]
false
pytest
false
[]
true
9f667840594aa36cf9e7c200c1fcc758e0602479
28d43b2df85ee11260aaba0ffad8c699486bd748
v1.0
instruct
Docs
Docs: Python310_20514_I
### Python Coding Assessment Question #### Objective: Implement a generator function in Python that iterates over a sequence of numbers and yields only the prime numbers from the sequence. The function should demonstrate a clear understanding of how generators work in Python. #### Description: Write a generator funct...
def is_prime(n): """Check if a number is a prime number.""" if n <= 1: return False if n == 2: return True # 2 is a prime number if n % 2 == 0: return False p = 3 while p * p <= n: if n % p == 0: return False p += 2 return True def prime_...
from solution import prime_generator def test_prime_generator_basic(): primes = list(prime_generator(10, 20)) assert primes == [11, 13, 17, 19] def test_prime_generator_small_range(): primes = list(prime_generator(1, 10)) assert primes == [2, 3, 5, 7] def test_prime_generator_large_start(): prime...
[ { "docstring": "Check if a number is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generator that yields prime numbers in the range [start, end).", "function_declaration": "def prime_generator(start, ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def prime_generator(start: int, end: int):\n \"\"\"\n A generator that yields prime numbers within a given range [start, end).\n \"\"\"\n def is_prime(n):\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00020514", "row_id": 20514, "seed_ids": "[27]" }
0.666552
Docs: Python310_20514
I
[ "is_prime", "prime_generator" ]
2
[ [ "prime_generator", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d60dcaf6c7b013b94c702466c9234cb903432188
66150e3820f78f83fa9039aaf28cc918003f19fe
v1.0
instruct
Docs
Docs: Python310_20516_I
### Python 3.10 Coding Assessment #### **Problem Overview:** As a Python developer, you are tasked with troubleshooting and optimizing a Python script that performs multiple nested function calls. To understand the flow of these function calls and identify potential bottlenecks in the execution, you will use SystemTap...
def start(): print("Starting function: start") function_1() def function_1(): print("In function_1 before calling function_2") function_2() print("In function_1 after calling function_2") def function_2(): print("In function_2 before performing arithmetic") result = 2 + 3 # Simple arithme...
from solution import start, function_1, function_2 def test_start(capsys): start() captured = capsys.readouterr() assert "Starting function: start" in captured.out assert "In function_1 before calling function_2" in captured.out assert "In function_1 after calling function_2" in captured.out as...
[ { "docstring": null, "function_declaration": "def start():", "function_name": "start", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def function_1():", "function_name": "function_1", "parameter_list": "()" }, { "docstring": null, "function_d...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def start():\n print(\"Starting function: start\")\n function_1()\n\ndef function_1():\n print(\"In function_1 before calling function_2\")\n function_2()\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00020516", "row_id": 20516, "seed_ids": "[79]" }
0.566717
Docs: Python310_20516
I
[ "start", "function_1", "function_2" ]
3
[ [ "function_1", "function_2" ], [ "start", "function_1" ] ]
2
[]
false
[]
false
pytest
true
[]
true
116eddd5deb1dfac5ec5cc01d7d91d6a56682245
fa9356f5b9c95c0d5fabe15b50a3fb3ed82f90c3
v1.0
instruct
Docs
Docs: Python310_20521_I
### Question: #### Objective: Write a Python function that performs various operations on rational numbers using the `fractions` module. Your function should be able to handle inputs of different types and perform a series of operations as described below. #### Function Signature: ```python def process_fractions(data...
from fractions import Fraction from decimal import Decimal def process_fractions(data: list) -> dict: results = {} for i, (operation, *params) in enumerate(data): if operation not in ["add", "subtract", "multiply", "divide", "limit_denominator", "as_integer_ratio"]: continue ...
from solution import process_fractions from fractions import Fraction from decimal import Decimal def test_basic_operations(): data = [ ("add", 1, 2), # 1 + 2 ("subtract", "3/4", "1/4"), # 3/4 - 1/4 ("multiply", Fraction(3, 7), 2) # 3/7 * 2 ] result = process_fr...
[ { "docstring": null, "function_declaration": "def process_fractions(data):", "function_name": "process_fractions", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def convert_to_fraction(param):", "function_name": "convert_to_fraction", "parameter_list...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from fractions import Fraction\nfrom decimal import Decimal\n\ndef to_fraction(value):\n if isinstance(value, (int, Fraction)):\n return Fraction(value)\n ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00020521", "row_id": 20521, "seed_ids": "[334]" }
0.699925
Docs: Python310_20521
I
[ "process_fractions", "convert_to_fraction" ]
2
[ [ "process_fractions", "convert_to_fraction" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cb2ec95f81279f6c464fd852b14ca5cb2c7732e1
69758165f8aa1b3e1e678fc6f27244edf2fcbbca
v1.0
instruct
Docs
Docs: Seaborn_20522_I
**Objective**: Demonstrate your understanding of Seaborn by creating and customizing a multi-plot figure. **Task**: Write a Python function `customize_plots()` that performs the following steps: 1. Import the necessary libraries (`numpy`, `seaborn`, and `matplotlib.pyplot`). 2. Generate a dataset with random values u...
import numpy as np import seaborn as sns import matplotlib.pyplot as plt def sinplot(n=10, flip=1): """ Plots multiple sine waves with an increasing phase shift. """ 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_plo...
from solution import customize_plots # Since the function customize_plots() produces visual output to be displayed, # we will test the function by verifying that it executes without errors. # Note: We won't use any assert statements here because we are testing a plot-producing function. def test_customize_plots(): ...
[ { "docstring": "Plots multiple sine waves with an increasing phase shift.", "function_declaration": "def sinplot(n=10, flip=1):", "function_name": "sinplot", "parameter_list": "(n=10, flip=1)" }, { "docstring": "Customizes and displays a 2x2 grid of plots with different Seaborn styles\nand c...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import 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_1
{ "original_instruction": "", "prompt_id": "00020522", "row_id": 20522, "seed_ids": "[2]" }
0.685132
Docs: Seaborn_20522
I
[ "sinplot", "customize_plots" ]
2
[ [ "customize_plots", "sinplot" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "seaborn" ]
false
5ea03bf57e89bf2d70e8ed2da5fe8cd960314fc6
fb0bae24246caeae6ad4cbff1f7aa9146563803c
v1.0
instruct
Docs
Docs: Pytorch_20540_I
### Advanced Coding Assessment: Implementing and Utilizing Block Masks in Flexible Attention #### Objective: The goal of this assessment is to test your ability to work with attention mechanisms and block masks in PyTorch. You will implement a function that creates a customized attention mask using several provided ut...
import torch # Note: Since torch.nn.attention.flex_attention module doesn't actually exist in PyTorch, # We will mock the flex_attention and and_masks functions for the purpose of this exercise. def and_masks(mask1: torch.Tensor, mask2: torch.Tensor) -> torch.Tensor: """ Mock function to perform 'AND' operati...
from solution import create_custom_mask, apply_flex_attention import torch def test_create_custom_mask(): mask1 = torch.tensor([[True, False], [True, True]], dtype=torch.bool) mask2 = torch.tensor([[True, True], [False, True]], dtype=torch.bool) expected = torch.tensor([[True, False], [False, True]], dtype...
[ { "docstring": "Mock function to perform 'AND' operation on two masks.", "function_declaration": "def and_masks(mask1, mask2):", "function_name": "and_masks", "parameter_list": "(mask1, mask2)" }, { "docstring": "Mock function to compute the flexible attention process, masked.", "functio...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.nn.attention.flex_attention import flex_attention, and_masks\n\ndef create_custom_mask(mask1: torch.Tensor, mask2: torch.Tensor) -> torch.Tenso...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00020540", "row_id": 20540, "seed_ids": "[0]" }
0.453561
Docs: Pytorch_20540
I
[ "and_masks", "flex_attention", "create_custom_mask", "apply_flex_attention" ]
4
[ [ "apply_flex_attention", "flex_attention" ], [ "create_custom_mask", "and_masks" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
b6b223cf2687904feec0a312facc869506634d63
c66867e35ec8ad0c793f82629d9a39d829ea477e