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
Filter
Filter_51567_I
Explain the concept of mutual recursion in computer science and provide a simple programming example to illustrate the idea.
def is_even(n): """ Returns True if n is even, otherwise False. """ if n == 0: return True else: return is_odd(n - 1) def is_odd(n): """ Returns True if n is odd, otherwise False. """ if n == 0: return False else: return is_even(n - 1)
from solution import is_even, is_odd def test_is_even(): assert is_even(0) == True assert is_even(1) == False assert is_even(2) == True assert is_even(3) == False assert is_even(10) == True def test_is_odd(): assert is_odd(0) == False assert is_odd(1) == True assert is_odd(2) == False ...
[ { "docstring": "Returns True if n is even, otherwise False.", "function_declaration": "def is_even(n):", "function_name": "is_even", "parameter_list": "(n)" }, { "docstring": "Returns True if n is odd, otherwise False.", "function_declaration": "def is_odd(n):", "function_name": "is_...
[ 0, 0, 1, 1, 1, 0, 1, 1, 1 ]
6
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_even(n):\n \"\"\"\n Checks if a number n is even using mutual recursion.\n \"\"\"\n if n == 0:\n return True\n else:\n return is_odd(n - 1)\n\ndef is_odd(n)...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00051567", "row_id": 51567, "seed_ids": "['Qwen2.5-72B-Instruct_106841']" }
0.414096
Filter_51567
I
[ "is_even", "is_odd" ]
2
[ [ "is_even", "is_odd" ], [ "is_odd", "is_even" ] ]
2
[]
false
[]
false
pytest
true
[]
true
58e137d17de0c2576b3a72a0bb3867d1976a7642
329b82aa6f7ccd6590b288fca34e8a59b45d4f22
v1.0
instruct
Filter
Filter_51628_I
Create a basic algorithm for image recognition using deep learning. Explain the steps involved and provide a simple pseudocode.
def basic_image_recognition(model, image): """ Perform a basic image recognition using a given machine learning model. Parameters: - model: A pre-trained deep learning model - image: The input image for recognition Returns: - The predicted class of the image """ # Step 1: P...
import numpy as np from solution import basic_image_recognition, preprocess_image, get_predicted_class class DummyModel: def predict(self, image): # Return a dummy prediction (e.g., a random vector simulating probabilities for 3 classes) return np.array([0.1, 0.7, 0.2]) def test_basic_image_recogn...
[]
[ 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.143
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.optimizers import Adam\n\ndef create_cn...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00051628", "row_id": 51628, "seed_ids": "['Qwen2.5-72B-Instruct_106924']" }
0.34138
Filter_51628
I
[ "basic_image_recognition", "preprocess_image", "get_predicted_class" ]
3
[ [ "basic_image_recognition", "get_predicted_class" ], [ "basic_image_recognition", "preprocess_image" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy" ]
false
b037f866b951ebe2fc78d71da3f45f7ae1907187
f1cef4c7935a120815e426fb1a993139ed44921a
v1.0
instruct
Filter
Filter_51721_I
How can I create a Python program to monitor the temperature of a CPU and alert me if it exceeds a certain threshold? I want to use this program on a Linux system.
import psutil import smtplib from email.mime.text import MIMEText from time import sleep def get_cpu_temp(): """ Retrieves the current CPU temperature. """ temps = psutil.sensors_temperatures() if "coretemp" in temps: core_temps = temps["coretemp"] for entry in core_temps: ...
import pytest from unittest.mock import patch, MagicMock from solution import get_cpu_temp, send_alert # Test get_cpu_temp function @patch("solution.psutil.sensors_temperatures") def test_get_cpu_temp(mock_sensors_temperatures): mock_sensors_temperatures.return_value = { "coretemp": [MagicMock(label="Packa...
[ { "docstring": "Retrieves the current CPU temperature.", "function_declaration": "def get_cpu_temp():", "function_name": "get_cpu_temp", "parameter_list": "()" }, { "docstring": "Sends an alert email.", "function_declaration": "def send_alert(subject, body, to_email, from_email, smtp_ser...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import psutil\nimport time\n\ndef get_cpu_temperature():\n \"\"\"\n Returns the current CPU temperature in Celsius.\n If unable to get the value, returns None.\n \"\"\"\n try:\n...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00051721", "row_id": 51721, "seed_ids": "['Qwen2.5-72B-Instruct_107088']" }
0.540568
Filter_51721
I
[ "get_cpu_temp", "send_alert", "monitor_cpu_temp" ]
3
[ [ "monitor_cpu_temp", "get_cpu_temp" ], [ "monitor_cpu_temp", "send_alert" ] ]
2
[]
false
[]
false
pytest
true
[ "psutil" ]
false
3da87276ad46468165ff37f14121209092cb5ded
5cdaf198c4b5d2899fb9cf605950304a517829b6
v1.0
instruct
Filter
Filter_51955_I
How can I use PyTorch to train a simple linear regression model? Can you provide a step-by-step guide with code examples?
import torch import torch.nn as nn import torch.optim as optim # Step-by-Step Guide to Create and Train a Simple Linear Regression Model in PyTorch # 1. Define the Linear Regression Model class LinearRegressionModel(nn.Module): def __init__(self): super(LinearRegressionModel, self).__init__() # Si...
import torch from solution import LinearRegressionModel, generate_data, train_model, predict, example_linear_regression def test_model_initialization(): model = LinearRegressionModel() assert isinstance(model, LinearRegressionModel), "Model initialization failed." def test_generate_data(): x, y = generate...
[]
[ 0, 0, 0, 1, 1, 0, 0, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\n# Define the simple linear regression model class\nclass LinearRegressionModel(nn.Module):\n def __init__(self):\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00051955", "row_id": 51955, "seed_ids": "['Qwen2.5-72B-Instruct_107467']" }
0.480302
Filter_51955
I
[ "generate_data", "train_model", "predict", "example_linear_regression" ]
4
[ [ "example_linear_regression", "generate_data" ], [ "example_linear_regression", "predict" ], [ "example_linear_regression", "train_model" ] ]
3
[]
false
[ "LinearRegressionModel" ]
true
pytest
true
[ "torch" ]
false
578f691a804c5d0f633269accde9c045007b45fc
1830463c13eae16baabbaebbd52ddf4cc2a8e441
v1.0
instruct
Filter
Filter_51975_I
Design a programming solution for a chess game that implements a basic AI using the Minimax algorithm. The AI should be able to play as both the white and black pieces, and the solution should consider optimizing performance for deeper search levels. Discuss the implementation details, including the evaluation function...
import random # Assuming a simplified chessboard representation and functions for moves and evaluation def is_game_over(board): # Function to check if the game is over (dummy implementation) # In an actual scenario, this would check for checkmate, stalemate, etc. return False def get_legal_moves(board, is...
from solution import minimax, ai_move, is_game_over, make_move, get_legal_moves, evaluate_board def test_is_game_over(): assert not is_game_over([""] * 64) def test_get_legal_moves(): board = [""] * 64 moves = get_legal_moves(board, True) assert len(moves) == 3 def test_evaluate_board(): board = ...
[ { "docstring": null, "function_declaration": "def is_game_over(board):", "function_name": "is_game_over", "parameter_list": "(board)" }, { "docstring": null, "function_declaration": "def get_legal_moves(board, is_white_turn):", "function_name": "get_legal_moves", "parameter_list"...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import chess\n\ndef evaluate_board(board):\n \"\"\"\n Basic evaluation function that gives a rough estimate of the board strength.\n Positive values indicate an advantage for white, a...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00051975", "row_id": 51975, "seed_ids": "['Qwen2.5-72B-Instruct_107494']" }
0.54335
Filter_51975
I
[ "is_game_over", "get_legal_moves", "make_move", "evaluate_board", "minimax", "ai_move" ]
6
[ [ "ai_move", "minimax" ], [ "minimax", "evaluate_board" ], [ "minimax", "get_legal_moves" ], [ "minimax", "is_game_over" ], [ "minimax", "make_move" ] ]
5
[]
false
[]
false
pytest
true
[]
true
349bc5987dddf2bb179378bfd1289aeba272ca30
403fa9412cca4fdf3b2e894597253624e8dde720
v1.0
instruct
Filter
Filter_51985_I
Develop a Python script that recursively searches for and replaces a specific word in all text files within a given directory. The script should be able to handle different file encodings and should not alter files that do not contain the target word. It should also log all changes made.
import os import chardet import logging logging.basicConfig(level=logging.INFO, filename='replacement_log.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s') def detect_encoding(file_path): with open(file_path, 'rb') as f: raw_data = f.read() return chardet.dete...
import os import tempfile from solution import search_and_replace def test_search_and_replace(): with tempfile.TemporaryDirectory() as tmpdirname: subdir = os.path.join(tmpdirname, 'subdir') os.makedirs(subdir) file_path1 = os.path.join(tmpdirname, 'file1.txt') file_path2 = os.path...
[ { "docstring": null, "function_declaration": "def detect_encoding(file_path):", "function_name": "detect_encoding", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def replace_word_in_file(file_path, target_word, replacement_word):", "function_name": ...
[ 0, 0, 0, 1, 0, 1, 1, 1, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport chardet\nimport logging\n\nlogging.basicConfig(filename='replacement.log', level=logging.INFO, format='%(asctime)s - %(message)s')\n\ndef detect_encoding(file_path):\n \"\...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00051985", "row_id": 51985, "seed_ids": "['Qwen2.5-72B-Instruct_107514']" }
0.529845
Filter_51985
I
[ "detect_encoding", "replace_word_in_file", "search_and_replace" ]
3
[ [ "replace_word_in_file", "detect_encoding" ], [ "search_and_replace", "replace_word_in_file" ] ]
2
[]
false
[]
false
pytest
true
[ "chardet" ]
false
ca4dbfb4cfd31c8dfe074d8de1b8fbf2f3019219
8abc794147e586ead539cc186bfcf0dcde32dfe6
v1.0
instruct
Filter
Filter_52246_I
Design a program that can parse a given text and identify all instances of dates, times, and numbers. The program should be able to recognize different formats for dates (e.g., 12/04/2023, 2023-04-12, April 12, 2023) and times (e.g., 14:30, 2:30 PM). Numbers should be identified as standalone digits or digits as part o...
import re from datetime import datetime def parse_text(text): """ Parses the given text and identifies instances of dates, times, and numbers. Parameters: text (str): the input text to be parsed. Returns: dict: a dictionary containing categorized found elements. """ ...
from solution import parse_text def test_parse_dates_in_text(): text = "We have a meeting on 12/04/2023 and another on April 12, 2023." result = parse_text(text) assert "12/04/2023" in result['dates'] assert "April 12, 2023" in result['dates'] def test_parse_times_in_text(): text = "The event ...
[ { "docstring": "Parses the given text and identifies instances of dates, times, and numbers.\n\nParameters:\n text (str): the input text to be parsed.\n \nReturns:\n dict: a dictionary containing categorized found elements.", "function_declaration": "def parse_text(text):", "function_name": "pa...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nfrom datetime import datetime\n\ndef parse_text(text):\n \"\"\"\n This function parses the given text and identifies all instances of dates, times, and numbers.\n It catego...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00052246", "row_id": 52246, "seed_ids": "['Qwen2.5-72B-Instruct_107921']" }
0.496842
Filter_52246
I
[ "parse_text", "test_parse_text" ]
2
[ [ "test_parse_text", "parse_text" ] ]
1
[]
false
[]
false
pytest
true
[]
true
936f0438c6c0183713c603df3ca231dd1db08225
35e6a02f22408c64123866d2f347d50dff77fd3e
v1.0
instruct
Filter
Filter_52269_I
Develop a Python script that periodically checks the availability of a website by sending HTTP requests and logs the response time and status code to a file. The script should run indefinitely and check the website every 10 minutes. If the website is down (status code is not 200), the script should send an email notifi...
import requests import smtplib from email.mime.text import MIMEText from datetime import datetime import time def send_email(subject, body, to_emails): from_email = "your_email@example.com" from_password = "your_password" smtp_server = "smtp.example.com" port = 587 # Create the email msg = MIM...
from solution import send_email, check_website, monitor_website import pytest from unittest.mock import patch def test_check_website_success(): with patch('requests.get') as mocked_get: mocked_get.return_value.status_code = 200 mocked_get.return_value.elapsed.total_seconds.return_value = 0.1 ...
[ { "docstring": null, "function_declaration": "def send_email(subject, body, to_emails):", "function_name": "send_email", "parameter_list": "(subject, body, to_emails)" }, { "docstring": null, "function_declaration": "def check_website(url, emails):", "function_name": "check_website",...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import smtplib\nimport time\nimport requests\nfrom datetime import datetime\n\ndef send_email(subject, body, to_addresses):\n smtp_server = 'smtp.gmail.com'\n smtp_port = 587\n smtp_u...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00052269", "row_id": 52269, "seed_ids": "['Qwen2.5-72B-Instruct_107951']" }
0.547401
Filter_52269
I
[ "send_email", "check_website", "monitor_website" ]
3
[ [ "check_website", "send_email" ], [ "monitor_website", "check_website" ] ]
2
[]
false
[]
false
pytest
true
[ "requests" ]
false
cf541b38d5961a1af31f574273ccdee649259ddb
4e90d691bcde3232ff00fec0654657edf43ea32b
v1.0
instruct
Filter
Filter_52451_I
Design a simple web crawler in Python that can scrape all the URLs from a given website. Ensure it can handle exceptions and can also limit the depth of the crawl. Provide the code and necessary explanations.
import requests from bs4 import BeautifulSoup from urllib.parse import urlparse, urljoin import logging from collections import deque logging.basicConfig(level=logging.INFO) def get_links(url): """ Scrape all the links from the given URL. """ try: response = requests.get(url) soup = Be...
import pytest from solution import get_links, crawl def test_get_links(monkeypatch): sample_html = """ <html> <body> <a href="https://example.com/page1"></a> <a href="/page2"></a> <a href="https://example.com/page3"></a> </body> </html> """ d...
[ { "docstring": "Scrape all the links from the given URL.", "function_declaration": "def get_links(url):", "function_name": "get_links", "parameter_list": "(url)" }, { "docstring": "Crawl a website and return all the found URLs up to max_depth levels deep.", "function_declaration": "def c...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urljoin\nimport re\n\nclass WebCrawler:\n def __init__(self, base_url, max_depth=2):\n self.base_url = base_u...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00052451", "row_id": 52451, "seed_ids": "['Qwen2.5-72B-Instruct_108229']" }
0.625259
Filter_52451
I
[ "get_links", "crawl" ]
2
[ [ "crawl", "get_links" ] ]
1
[]
false
[]
false
pytest
true
[ "bs4", "requests" ]
false
15e840cd2a75c1dd9f3535e2b64d1f608f7ebc64
33cf8601532f8071ec659ba2bc5a8f4a71b0af2c
v1.0
instruct
Filter
Filter_52560_I
Write a Python script that monitors the availability of a website and sends an email alert if the site is down. The script should check the site every 10 minutes. Use the `requests` library to check the website and the `smtplib` library to send the email. Assume that the email server settings are already configured and...
import requests import smtplib import time # Configuration for the website and email settings CHECK_INTERVAL = 600 # 10 minutes URL_TO_MONITOR = "http://example.com" EMAIL_FROM = "alert@example.com" EMAIL_TO = "admin@example.com" EMAIL_SUBJECT = "Website Down Alert" EMAIL_BODY = f"The website {URL_TO_MONITOR} is not ...
import pytest from unittest.mock import patch, call from solution import check_website, send_email, URL_TO_MONITOR, EMAIL_SUBJECT, EMAIL_BODY @patch('solution.requests.get') @patch('solution.send_email') def test_check_website_success(mock_send_email, mock_get): mock_get.return_value.status_code = 200 check_we...
[ { "docstring": null, "function_declaration": "def send_email(subject, body):", "function_name": "send_email", "parameter_list": "(subject, body)" }, { "docstring": null, "function_declaration": "def check_website():", "function_name": "check_website", "parameter_list": "()" }, ...
[ 0, 0, 0, 1, 1, 1, 0, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nimport smtplib\nimport time\n\ndef check_website(url):\n \"\"\"\n Checks if the specified website is accessible.\n \"\"\"\n try:\n response = requests.get(u...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00052560", "row_id": 52560, "seed_ids": "['Qwen2.5-72B-Instruct_108406']" }
0.497933
Filter_52560
I
[ "send_email", "check_website", "monitor_website" ]
3
[ [ "check_website", "send_email" ], [ "monitor_website", "check_website" ] ]
2
[]
false
[]
false
pytest
true
[ "requests" ]
false
785d938478255f8b3af174c6985cb4749dc7de38
d4f4103604c7e05796bb7707b5f3f4a1953601b3
v1.0
instruct
Filter
Filter_52606_I
Design a Python function `check_reversible_prime_sum` that generates a list of integers between 1000 and 1500 (inclusive), where the sum of each integer's digits is a prime number. The function should then check if the original list can be accurately reconstructed from the list of sums (i.e., if the sums are unique eno...
def is_prime(n): """ Check if a number is prime. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True def digit_sum(n): """ Calcul...
from solution import is_prime, digit_sum, check_reversible_prime_sum def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(18) == False assert is_prime(17) == True def test_digit_sum(): assert digit...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Calculate the sum of the digits of the number n.", "function_declaration": "def digit_sum(n):", "function_name": "digit_su...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00052606", "row_id": 52606, "seed_ids": "['Qwen2.5-72B-Instruct_108464']" }
0.584532
Filter_52606
I
[ "is_prime", "digit_sum", "check_reversible_prime_sum" ]
3
[ [ "check_reversible_prime_sum", "digit_sum" ], [ "check_reversible_prime_sum", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3b062a2feb10f6733f08f7fa636bb219ce5d57e0
a91fc0e6c4f00e6f8edffb68a4ce691442b64f96
v1.0
instruct
Filter
Filter_52635_I
Create a Python function that applies a Gaussian blur to an image using OpenCV. The function should accept the path to an image file, and the kernel size for the Gaussian blur as inputs. It should then apply the blur and return the blurred image. Make sure the function is well-documented, including a brief description,...
import cv2 def apply_gaussian_blur(image_path, kernel_size): """ Applies a Gaussian blur to an image using OpenCV. :param image_path: The path to the image file (str) :param kernel_size: The size of the Gaussian kernel (tuple of two integers) :return: The blurred image (numpy.ndarray) """ ...
import numpy as np import cv2 from solution import apply_gaussian_blur def test_apply_gaussian_blur(): # Create a dummy image (e.g., a 100x100 black square with a white square inside) dummy_image = np.zeros((100, 100, 3), dtype=np.uint8) cv2.rectangle(dummy_image, (25, 25), (75, 75), (255, 255, 255), -1) ...
[ { "docstring": "Applies a Gaussian blur to an image using OpenCV.\n\n:param image_path: The path to the image file (str)\n:param kernel_size: The size of the Gaussian kernel (tuple of two integers)\n:return: The blurred image (numpy.ndarray)", "function_declaration": "def apply_gaussian_blur(image_path, ker...
[ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cv2\n\ndef apply_gaussian_blur(image_path, kernel_size):\n \"\"\"\n Applies a Gaussian blur to an image.\n\n Parameters:\n image_path (str): The path to the image file.\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00052635", "row_id": 52635, "seed_ids": "['Qwen2.5-72B-Instruct_108519']" }
0.721521
Filter_52635
I
[ "apply_gaussian_blur", "demonstrate_gaussian_blur" ]
2
[ [ "demonstrate_gaussian_blur", "apply_gaussian_blur" ] ]
1
[]
false
[]
false
pytest
true
[ "cv2", "numpy" ]
false
9bd4f87291ababb17bfe34d508e6cb73184fe3ed
438e8903e8553c13843ebd012a2ffbe5043f1d15
v1.0
instruct
Filter
Filter_52674_I
Develop a Python script to automate the process of downloading images from a website, but ensure that the script adheres to the website's `robots.txt` file to respect its rules for web scraping. How can I accomplish this? Can you provide a sample script?
import requests from urllib.parse import urlparse, urljoin from bs4 import BeautifulSoup import re import os def is_allowed_by_robots(url, user_agent='*'): """ Check the site's robots.txt file to see if scraping is allowed. """ parsed_url = urlparse(url) robots_url = f"{parsed_url.scheme}://{parsed...
import pytest import requests from unittest.mock import patch, Mock from solution import is_allowed_by_robots, download_images def test_is_allowed_by_robots(): mock_response = Mock() mock_response.status_code = 200 mock_response.text = ( "User-agent: *\n" "Disallow: /private\n" ) ...
[ { "docstring": "Check the site's robots.txt file to see if scraping is allowed.", "function_declaration": "def is_allowed_by_robots(url, user_agent='*'):", "function_name": "is_allowed_by_robots", "parameter_list": "(url, user_agent='*')" }, { "docstring": "Download all images from the given...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport requests\nfrom urllib.parse import urljoin, urlparse\nfrom bs4 import BeautifulSoup\nimport re\nimport urllib.robotparser\n\n\ndef get_robot_parser(base_url):\n \"\"\"\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00052674", "row_id": 52674, "seed_ids": "['Qwen2.5-72B-Instruct_108580']" }
0.481676
Filter_52674
I
[ "is_allowed_by_robots", "download_images" ]
2
[ [ "download_images", "is_allowed_by_robots" ] ]
1
[]
false
[]
false
pytest
true
[ "bs4", "requests" ]
false
e3050d555513cb9f9492f4e3c003a8da94f0d08e
0829aecc09dff6729c767f09f0a06b85b5764918
v1.0
instruct
Filter
Filter_52743_I
Can you write a Python script that monitors CPU usage and sends an email alert if the usage exceeds a certain threshold?
import psutil import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def check_cpu_usage(threshold): """ Check the current CPU usage and return True if it exceeds the threshold. """ cpu_usage = psutil.cpu_percent(interval=1) return cpu_usage > threshold ...
import pytest from unittest.mock import patch, MagicMock from solution import check_cpu_usage, send_email_alert, monitor_cpu_usage @patch('psutil.cpu_percent', return_value=95) def test_check_cpu_usage_exceeds_threshold(mock_cpu_percent): assert check_cpu_usage(90) == True @patch('psutil.cpu_percent', return_valu...
[ { "docstring": "Check the current CPU usage and return True if it exceeds the threshold.", "function_declaration": "def check_cpu_usage(threshold):", "function_name": "check_cpu_usage", "parameter_list": "(threshold)" }, { "docstring": "Send an email alert with the given subject and body.", ...
[ 0, 0, 0, 1, 0, 0, 1, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import smtplib\nimport psutil\nimport time\n\ndef send_email_alert(subject, body, to_email, from_email, password):\n \"\"\"\n Sends an email alert with the specified subject and body.\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00052743", "row_id": 52743, "seed_ids": "['Qwen2.5-72B-Instruct_108697']" }
0.634008
Filter_52743
I
[ "check_cpu_usage", "send_email_alert", "monitor_cpu_usage" ]
3
[ [ "monitor_cpu_usage", "check_cpu_usage" ], [ "monitor_cpu_usage", "send_email_alert" ] ]
2
[]
false
[]
false
pytest
true
[ "psutil" ]
false
b30811de44e434a2a9fc8e39f3f3188687ca12da
390df5860b1ebd4e9e916b3fc90d2131d51113fc
v1.0
instruct
Filter
Filter_52791_I
I need to create a Python script that monitors a specific directory and logs any changes (file creation, deletion, or modification) to a log file. How can I do this?
import os import time from datetime import datetime def monitor_directory(directory_path, log_file_path): """ Monitors the specified directory for any changes (file creation, deletion, or modification) and logs these changes to a log file. Parameters: - directory_path (str): The path to the di...
import os import time import pytest from solution import monitor_directory, log_change @pytest.fixture def create_test_directory_and_files(tmp_path): # Setup phase: create a temporary directory and log file test_dir = tmp_path / "test_dir" test_dir.mkdir() log_file = tmp_path / "log.txt" test_file...
[ { "docstring": "Monitors the specified directory for any changes (file creation, deletion, or modification)\nand logs these changes to a log file.\n\nParameters:\n- directory_path (str): The path to the directory to be monitored.\n- log_file_path (str): The path to the log file where changes will be recorded.",...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\nimport logging\n\nclass DirectoryMonitorHandler(FileSystemEventHandler):\n def __in...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00052791", "row_id": 52791, "seed_ids": "['Qwen2.5-72B-Instruct_108770']" }
0.575087
Filter_52791
I
[ "monitor_directory", "log_change" ]
2
[ [ "monitor_directory", "log_change" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9e5c4c4599fd6004172c5731552fd561de7d71e8
204681366b63c3514a99c9bfa08673c407f734c5
v1.0
instruct
Filter
Filter_52897_I
Can you help me with a Python script that downloads images from a list of URLs and saves them to a specified directory? I want to ensure that the script can handle a large number of URLs efficiently and also manage any potential errors, such as broken links or network issues, gracefully. Additionally, it would be great...
import os import requests from concurrent.futures import ThreadPoolExecutor import logging def download_image(url, save_dir): """ Downloads an image from a URL and saves it to the specified directory. Args: url (str): URL of the image to download. save_dir (str): Directory where the im...
import os import shutil import tempfile from solution import download_image, download_images def test_download_image_success(monkeypatch): class MockResponse: @staticmethod def raise_for_status(): pass @staticmethod def iter_content(chunk_size): retu...
[ { "docstring": "Downloads an image from a URL and saves it to the specified directory.\n\nArgs:\n url (str): URL of the image to download.\n save_dir (str): Directory where the image will be saved.\n \nReturns:\n str: Path where the image was saved or error message.", "function_declaration": "de...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport requests\nimport logging\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef setup_logger():\n logging.basicConfig(\n level=logging.INFO,\n format='%(a...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00052897", "row_id": 52897, "seed_ids": "['Qwen2.5-72B-Instruct_108941']" }
0.565808
Filter_52897
I
[ "download_image", "download_images" ]
2
[ [ "download_images", "download_image" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
65ebb1f6f92f17fefb2ab0935bff07896747dbad
24b593a574c12af4dbe45274bf91d136dff768c6
v1.0
instruct
Filter
Filter_52902_I
Write a Python program to implement a simple recommendation system using collaborative filtering on a movie dataset. The program should be able to take a user's movie ratings and suggest movies that they might like based on the ratings of similar users. Please include a brief explanation of the collaborative filtering ...
import numpy as np from scipy.spatial.distance import cosine def compute_similarity(user_ratings, target_user_index): """ Compute the similarity score between a target user and other users using cosine similarity. """ target_ratings = user_ratings[target_user_index] similarities = [] for i...
from solution import compute_similarity, recommend_movies import numpy as np def test_similarity(): user_ratings = np.array([[5, 3, 0, 0], [4, 0, 0, 2], [1, 1, 0, 5], [0, 0, 5, 3], [0, 0, 4, 4], ...
[ { "docstring": "Compute the similarity score between a target user and other users using cosine similarity.", "function_declaration": "def compute_similarity(user_ratings, target_user_index):", "function_name": "compute_similarity", "parameter_list": "(user_ratings, target_user_index)" }, { ...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.metrics.pairwise import cosine_similarity\n\ndef recommend_movies(user_ratings, all_user_ratings, num_recommendations=5):\n \"\"\"\n Recommend movies to ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00052902", "row_id": 52902, "seed_ids": "['Qwen2.5-72B-Instruct_108950']" }
0.412491
Filter_52902
I
[ "compute_similarity", "recommend_movies" ]
2
[ [ "recommend_movies", "compute_similarity" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "scipy" ]
false
69e70cfc65c1cffc7de234479761dd926bf91579
7c63c48cf548ce18f884babab672a56f93d5f380
v1.0
instruct
Filter
Filter_52999_I
How can I calculate the implied volatility of a stock option using Python? I have the market price of the option, the strike price, the risk-free interest rate, the time to maturity, and the current stock price. Can you provide me with a Python code snippet to achieve this?
from scipy.stats import norm from scipy.optimize import brentq import numpy as np def black_scholes_call(S, K, T, r, sigma): """ Calculates the Black-Scholes price for a call option. :param S: Current stock price :param K: Option strike price :param T: Time to maturity (in years) :param r: Ris...
import pytest from solution import black_scholes_call, implied_volatility_call def test_black_scholes_call(): assert black_scholes_call(100, 100, 1, 0.05, 0.2) == pytest.approx(10.4506, rel=1e-4) def test_implied_volatility_call(): S = 100 # Current stock price K = 100 # Option strike price T = 1 #...
[ { "docstring": "Calculates the Black-Scholes price for a call option.\n\n:param S: Current stock price\n:param K: Option strike price\n:param T: Time to maturity (in years)\n:param r: Risk-free interest rate (as a decimal)\n:param sigma: Volatility of the underlying stock (as a decimal)\n:return: Black-Scholes ...
[ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from scipy.stats import norm\nimport numpy as np\nimport scipy.optimize as opt\n\ndef black_scholes_call_price(S, K, T, r, sigma):\n \"\"\"\n Calculate the price of a European call optio...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00052999", "row_id": 52999, "seed_ids": "['Qwen2.5-72B-Instruct_109127']" }
0.416443
Filter_52999
I
[ "black_scholes_call", "implied_volatility_call" ]
2
[ [ "implied_volatility_call", "black_scholes_call" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "scipy" ]
false
9e270f6658bdf63e24cc663d8b026913285aa03a
1e96fd7c7165e2e66654f39eb632ba1686eac84c
v1.0
instruct
Filter
Filter_53205_I
I am trying to solve a problem using the A* search algorithm. I have a grid that is 5x5, and I need to find the shortest path from the start point (0,0) to the goal point (4,4). The grid contains obstacles at the following positions: (1,1), (2,1), (2,2), (3,2), (3,3). I can move in four directions: up, down, left, and ...
import heapq def heuristic(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def a_star_search(start, goal, obstacles, grid_size): open_set = [(0, start)] heapq.heapify(open_set) came_from = {} g_score = {start: 0} f_score = {start: heuristic(start, goal)} while open_set: cur...
from solution import a_star_search def test_a_star_no_obstacles(): start = (0, 0) goal = (4, 4) obstacles = set() grid_size = 5 path = a_star_search(start, goal, obstacles, grid_size) assert path == [(0, 0), (0,1), (0,2), (0,3), (0,4), (1,4), (2,4), (3,4), (4,4)] def test_a_star_with_obstacles...
[ { "docstring": null, "function_declaration": "def heuristic(a, b):", "function_name": "heuristic", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def a_star_search(start, goal, obstacles, grid_size):", "function_name": "a_star_search", "parameter_list...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\n\ndef heuristic(a, b):\n return abs(a[0] - b[0]) + abs(a[1] - b[1])\n\ndef a_star_search(grid, start, goal):\n neighbors = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n \n clo...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00053205", "row_id": 53205, "seed_ids": "['Qwen2.5-72B-Instruct_109466']" }
0.494718
Filter_53205
I
[ "heuristic", "a_star_search", "get_neighbors", "reconstruct_path" ]
4
[ [ "a_star_search", "get_neighbors" ], [ "a_star_search", "heuristic" ], [ "a_star_search", "reconstruct_path" ] ]
3
[]
false
[]
false
pytest
true
[]
true
81c2241ea41f995c0fe7edd2d57d380523232d07
dd41002f283dcf2b0df3ce600285f238e4dd1e9f
v1.0
instruct
Filter
Filter_53280_I
how can I create a simple Python script to monitor the availability of a website? The script should periodically check if the website is up and running by sending HTTP requests. If the website is down, the script should alert the user. How can I implement this?
import requests import time def is_website_up(url): """ Checks if the website is up and running by sending an HTTP GET request. Args: url (str): The URL of the website to be checked. Returns: bool: True if the website is up, False otherwise. """ try: response = requests.get(ur...
from solution import is_website_up # Mocking the requests.get function for testing purposes import requests from unittest.mock import patch def test_is_website_up_when_website_is_up(): with patch('requests.get') as mocked_get: mocked_get.return_value.status_code = 200 assert is_website_up("http://e...
[ { "docstring": "Checks if the website is up and running by sending an HTTP GET request.\n\nArgs:\nurl (str): The URL of the website to be checked.\n\nReturns:\nbool: True if the website is up, False otherwise.", "function_declaration": "def is_website_up(url):", "function_name": "is_website_up", "pa...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nimport time\n\ndef monitor_website(url, check_interval, alert_function):\n \"\"\"\n Monitors the availability of a website by periodically sending HTTP requests.\n\n ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00053280", "row_id": 53280, "seed_ids": "['Qwen2.5-72B-Instruct_109586']" }
0.631586
Filter_53280
I
[ "is_website_up", "monitor_website" ]
2
[ [ "monitor_website", "is_website_up" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
8222b519afece1a9bc29b9495e1b9ce68e138a30
322886a29ad5f913b8280ccc2a0d761a80e37fba
v1.0
instruct
Filter
Filter_53526_I
How can I generate a Huffman code for a given set of characters and their frequencies? Can you provide an example?
import heapq class HuffmanNode: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): # Override < to make it work with heapq return self.freq < other.freq def build_huffman_tree(char_freq)...
from solution import build_huffman_tree, generate_huffman_codes, get_huffman_codes def test_huffman_tree_structure(): char_freq = {'a': 5, 'b': 9, 'c': 12, 'd': 13, 'e': 16, 'f': 45} root = build_huffman_tree(char_freq) # The root node should have frequency equal to the sum of all frequencies. ass...
[]
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\n\nclass HuffmanNode:\n def __init__(self, char, freq):\n self.char = char\n self.freq = freq\n self.left = None\n self.right = None\n \n def ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00053526", "row_id": 53526, "seed_ids": "['Qwen2.5-72B-Instruct_109972']" }
0.478653
Filter_53526
I
[ "build_huffman_tree", "generate_huffman_codes", "get_huffman_codes" ]
3
[ [ "get_huffman_codes", "build_huffman_tree" ], [ "get_huffman_codes", "generate_huffman_codes" ] ]
2
[]
false
[ "HuffmanNode" ]
true
pytest
true
[]
true
705ed902d0df3583e38fb7f38035a9e4d83d3010
936940d1b3d203f2104a689bd4ebcf94033f2925
v1.0
instruct
Filter
Filter_53729_I
Can you help me with a Python script to automate the process of pinging multiple servers and checking their status? I want to input a list of IP addresses or hostnames and get a report on which ones are up and which are down.
import os import platform import subprocess def ping_server(address): """ Pings the given server address and returns True if the server is up, False otherwise. """ # Determine command based on the OS param = '-n' if platform.system().lower() == 'windows' else '-c' # Building the command ...
from solution import ping_server, check_servers_status # mocking subprocess.call for testing import subprocess def mock_subprocess_call(command, stdout, stderr): if '127.0.0.1' in command or 'localhost' in command or 'google.com' in command: return 0 else: return 1 subprocess.call = mock_subp...
[ { "docstring": "Pings the given server address and returns True if the server is up, False otherwise.", "function_declaration": "def ping_server(address):", "function_name": "ping_server", "parameter_list": "(address)" }, { "docstring": "Takes a list of server addresses and returns a diction...
[ 0, 0, 0, 1, 0, 1, 0, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import subprocess\n\ndef ping_servers(servers):\n \"\"\"\n Pings a list of servers and returns their status as a dictionary.\n Args:\n - servers (list): A list of IP addresses or h...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00053729", "row_id": 53729, "seed_ids": "['Qwen2.5-72B-Instruct_110310']" }
0.677949
Filter_53729
I
[ "ping_server", "check_servers_status" ]
2
[ [ "check_servers_status", "ping_server" ] ]
1
[]
false
[]
false
pytest
true
[]
true
67e7a6a78db8c161c1ba4186e1bfa6d78c09c8d4
b19273982eb48d0bfe9956da44273328d62dcedc
v1.0
instruct
Filter
Filter_53808_I
Design a Python function to calculate the multiplicative inverse of a number under a modulus. This function should take two arguments, `number` and `modulus`, and return the multiplicative inverse of `number` modulo `modulus`, or an error message if the inverse does not exist. The solution should use the Extended Eucli...
def extended_gcd(a, b): if a == 0: return b, 0, 1 gcd, x1, y1 = extended_gcd(b % a, a) x = y1 - (b // a) * x1 y = x1 return gcd, x, y def multiplicative_inverse(number, modulus): gcd, x, _ = extended_gcd(number, modulus) if gcd != 1: return "Inverse does not exist" else:...
from solution import multiplicative_inverse def test_multiplicative_inverse_exists(): assert multiplicative_inverse(3, 11) == 4 assert multiplicative_inverse(2, 5) == 3 assert multiplicative_inverse(7, 13) == 2 def test_multiplicative_inverse_does_not_exist(): assert multiplicative_inverse(6, 9) == "I...
[ { "docstring": null, "function_declaration": "def extended_gcd(a, b):", "function_name": "extended_gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def multiplicative_inverse(number, modulus):", "function_name": "multiplicative_inverse", "paramete...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def multiplicative_inverse(number, modulus):\n \"\"\"\n Returns the multiplicative inverse of `number` under `modulus` using the Extended Euclidean Algorithm.\n If the inverse does no...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00053808", "row_id": 53808, "seed_ids": "['Qwen2.5-72B-Instruct_110442']" }
0.617629
Filter_53808
I
[ "extended_gcd", "multiplicative_inverse" ]
2
[ [ "multiplicative_inverse", "extended_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4598846557e3811d8055f9a1aabb60b34ac4edb7
d2fd1ada22b18a74ca0e3b822f25e45223284505
v1.0
instruct
Filter
Filter_53865_I
Please write a Python script that lists the files in a specific directory, and for each file, checks if it is a text file and prints the number of lines in the file. If the file is not a text file, it should print a message saying that the file is not a text file.
import os def is_text_file(filename): """ Determines if a file is a text file by attempting to open it in text mode. """ try: with open(filename, 'r') as file: file.read() return True except Exception: return False def count_lines(filename): """ Counts t...
import os import pytest from solution import is_text_file, count_lines, list_files_and_count_lines # Setup temporary directory and files for testing TEST_DIR = "test_dir" TEXT_FILE = os.path.join(TEST_DIR, "test.txt") BINARY_FILE = os.path.join(TEST_DIR, "test.bin") @pytest.fixture(scope="module") def setup_test_dir(...
[ { "docstring": "Determines if a file is a text file by attempting to open it in text mode.", "function_declaration": "def is_text_file(filename):", "function_name": "is_text_file", "parameter_list": "(filename)" }, { "docstring": "Counts the number of lines in a text file.", "function_de...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\n\ndef list_files_and_check_text(directory):\n \"\"\"\n Lists the files in the specified directory and for each file, checks if it is a text file.\n Prints the number of lin...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00053865", "row_id": 53865, "seed_ids": "['Qwen2.5-72B-Instruct_110538']" }
0.618861
Filter_53865
I
[ "is_text_file", "count_lines", "list_files_and_count_lines" ]
3
[ [ "list_files_and_count_lines", "count_lines" ], [ "list_files_and_count_lines", "is_text_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9b6e82ea304cb5dcd21dfe62a19061ef043a90db
654cf0597bfa0964a0366c9118b7dda3fec0f2b9
v1.0
instruct
Filter
Filter_54098_I
How can I build a basic recommendation system for a book e-commerce platform using Python?
import numpy as np from sklearn.metrics.pairwise import cosine_similarity def create_user_item_matrix(ratings): """ Create a user-item matrix from the ratings data. Args: ratings (list of tuples): Each tuple contains (user_id, book_id, rating) Returns: numpy ndarray: User-item matrix """ ...
import pytest from solution import create_user_item_matrix, recommend_books def test_create_user_item_matrix(): ratings = [ (1, 101, 5), (1, 102, 3), (2, 101, 4), (2, 103, 2), (3, 101, 3), (3, 102, 4), (3, 103, 1) ] matrix, user_idx, book_idx = create...
[ { "docstring": "Create a user-item matrix from the ratings data.\n\nArgs:\nratings (list of tuples): Each tuple contains (user_id, book_id, rating)\n\nReturns:\nnumpy ndarray: User-item matrix", "function_declaration": "def create_user_item_matrix(ratings):", "function_name": "create_user_item_matrix", ...
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.125
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom scipy.spatial.distance import cosine\n\ndef calculate_similarity(user_ratings):\n \"\"\"\n Calculate the similarity between each pair of users.\n \n :param...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00054098", "row_id": 54098, "seed_ids": "['Qwen2.5-72B-Instruct_110920']" }
0.410026
Filter_54098
I
[ "create_user_item_matrix", "user_similarity", "recommend_books" ]
3
[ [ "recommend_books", "user_similarity" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
18eb59e45b1ad92aca12a22f69cf71e606bbcdd5
4874da4238224844eec2178d143ef20884d01e5c
v1.0
instruct
Filter
Filter_54153_I
How can I add a watermark to images using Python? I want to add a text watermark to the corner of some images, and I have around 500 images to process in a folder. How can I achieve this in a time-efficient way?
from PIL import Image, ImageDraw, ImageFont import os def add_watermark(input_image_path, output_image_path, watermark_text, position): """ Adds a text watermark to an image and saves it. Parameters: - input_image_path: str, path to the input image. - output_image_path: str, path to save the w...
import os from PIL import Image from solution import add_watermark, batch_add_watermark # Create a sample image for testing def create_sample_image(path): image = Image.new('RGB', (100, 100), color = (73, 109, 137)) image.save(path) def test_add_watermark(): input_image_path = 'sample_image.jpg' outpu...
[ { "docstring": "Adds a text watermark to an image and saves it.\n\nParameters:\n- input_image_path: str, path to the input image.\n- output_image_path: str, path to save the watermarked image.\n- watermark_text: str, text to be used as watermark.\n- position: tuple, (x, y) coordinates for the watermark position...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from PIL import Image, ImageDraw, ImageFont\nimport os\n\ndef add_watermark(input_image_path, output_image_path, watermark_text, position):\n \"\"\"\n Adds a text watermark to an image.\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00054153", "row_id": 54153, "seed_ids": "['Qwen2.5-72B-Instruct_111012']" }
0.453788
Filter_54153
I
[ "add_watermark", "batch_add_watermark" ]
2
[ [ "batch_add_watermark", "add_watermark" ] ]
1
[]
false
[]
false
pytest
true
[ "PIL" ]
false
ffd720b55e80ab2e04e4407895f003cdad2421a4
4305df1896cec01e39f760758b4540a4781314a2
v1.0
instruct
Filter
Filter_54405_I
How can I create an interactive web application using Flask, a micro web framework in Python, that allows users to input a question and get a response from a pre-trained Qwen model like you?
from flask import Flask, request, jsonify, render_template_string app = Flask(__name__) def get_response_from_model(question): """ Mock function to return a response from a pre-trained model. In a real-world scenario, this would interface with the actual model. """ return f"Mock response for quest...
import pytest from flask import Flask, request, jsonify from flask.testing import FlaskClient from solution import app, get_response_from_model def test_get_response_from_model(): question = "What is the capital of France?" expected_response = "Mock response for question: What is the capital of France?" a...
[ { "docstring": "Mock function to return a response from a pre-trained model.\nIn a real-world scenario, this would interface with the actual model.", "function_declaration": "def get_response_from_model(question):", "function_name": "get_response_from_model", "parameter_list": "(question)" }, { ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from flask import Flask, request, render_template_string\n\napp = Flask(__name__)\n\n# Mock function for the Qwen model response\ndef get_qwen_response(question):\n # In a real scenario, th...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00054405", "row_id": 54405, "seed_ids": "['Qwen2.5-72B-Instruct_111456']" }
0.318246
Filter_54405
I
[ "get_response_from_model", "home", "get_answer" ]
3
[ [ "get_answer", "get_response_from_model" ] ]
1
[]
false
[]
false
pytest
true
[ "flask" ]
false
8febcda88bbe916211eb9328e595cb05c42f93e9
6ccf3d2486a03b6a412465107ead41043463ac77
v1.0
instruct
Filter
Filter_54438_I
I have a series of images that I want to use for batch processing through a machine learning model. How would I go about setting up a pipeline for this in Python, particularly using PyTorch and OpenCV? I'm hoping to load the images, preprocess them, run them through a pre-trained model, and then save the outputs.
import os import cv2 import torch import torchvision.transforms as transforms from torchvision.models import resnet18 def load_images_from_folder(folder): images = [] for filename in os.listdir(folder): img = cv2.imread(os.path.join(folder, filename)) if img is not None: images.appe...
import os import numpy as np from solution import ( load_images_from_folder, preprocess_image, load_pretrained_model, save_output, predict_and_save, ) def test_load_images_from_folder(tmp_path): img_path = tmp_path / "image.jpg" image = np.zeros((100, 100, 3), dtype=np.uint8) cv2.imwrit...
[ { "docstring": null, "function_declaration": "def load_images_from_folder(folder):", "function_name": "load_images_from_folder", "parameter_list": "(folder)" }, { "docstring": null, "function_declaration": "def preprocess_image(img):", "function_name": "preprocess_image", "parame...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport cv2\nimport torch\nimport torchvision.transforms as transforms\nfrom torchvision.models import resnet50\n\ndef load_images_from_folder(folder):\n \"\"\"\n Load all imag...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00054438", "row_id": 54438, "seed_ids": "['Qwen2.5-72B-Instruct_111500']" }
0.434314
Filter_54438
I
[ "load_images_from_folder", "preprocess_image", "load_pretrained_model", "save_output", "predict_and_save", "process_images" ]
6
[ [ "predict_and_save", "preprocess_image" ], [ "predict_and_save", "save_output" ], [ "process_images", "load_images_from_folder" ], [ "process_images", "load_pretrained_model" ], [ "process_images", "predict_and_save" ] ]
5
[]
false
[]
false
pytest
true
[ "cv2", "numpy", "torch", "torchvision" ]
false
f161c78e53209e22d50215eeb3fe0b8b5ebbe47e
5a6d75ae96d76e8b7451b8dfed67b37f8cb989cf
v1.0
instruct
Filter
Filter_54461_I
Write a simple Python script to monitor a website's uptime. The script should check if the website is reachable and log the status (up or down) along with the timestamp. Save the logs to a text file. The script should run every 5 minutes.
import time import requests from datetime import datetime def check_website_status(url): """ Checks if the website is reachable. Args: url (str): The URL of the website to check. Returns: str: 'up' if the website is reachable, 'down' otherwise. """ try: response = requ...
import os from solution import check_website_status, log_status def test_check_website_status_up(monkeypatch): def mock_get(*args, **kwargs): class MockResponse: status_code = 200 return MockResponse() monkeypatch.setattr('requests.get', mock_get) status = check_website_sta...
[ { "docstring": "Checks if the website is reachable.\n\nArgs:\nurl (str): The URL of the website to check.\n\nReturns:\nstr: 'up' if the website is reachable, 'down' otherwise.", "function_declaration": "def check_website_status(url):", "function_name": "check_website_status", "parameter_list": "(url...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nimport time\nfrom datetime import datetime\n\ndef check_website(url):\n try:\n response = requests.get(url)\n if response.status_code == 200:\n ret...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00054461", "row_id": 54461, "seed_ids": "['Qwen2.5-72B-Instruct_111532']" }
0.533541
Filter_54461
I
[ "check_website_status", "log_status", "monitor_website" ]
3
[ [ "log_status", "check_website_status" ], [ "monitor_website", "log_status" ] ]
2
[]
false
[]
false
pytest
true
[ "requests" ]
false
4c59bba33bc03897bcb252825c644189ae10242f
56639d09dd02ca8afa113e9c3e8ed41a98dd92f3
v1.0
instruct
Filter
Filter_54468_I
How can I design a simple game using Python for beginners? Can you provide an example?
import random def pick_random_number(min_val, max_val): """ Picks a random number between min_val and max_val (inclusive). """ return random.randint(min_val, max_val) def is_guess_correct(guess, target): """ Checks if the player's guess is correct, too high, or too low. Returns a string in...
from solution import pick_random_number, is_guess_correct def test_pick_random_number(): # Testing if the random number is within the specified range for _ in range(100): # Running multiple times for randomness number = pick_random_number(1, 10) assert 1 <= number <= 10 def test_is_guess_corr...
[ { "docstring": "Picks a random number between min_val and max_val (inclusive).", "function_declaration": "def pick_random_number(min_val, max_val):", "function_name": "pick_random_number", "parameter_list": "(min_val, max_val)" }, { "docstring": "Checks if the player's guess is correct, too ...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef guess_number_game(max_tries=10):\n \"\"\"\n This function runs a simple number guessing game.\n The player has 'max_tries' attempts to guess the number between 1 ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00054468", "row_id": 54468, "seed_ids": "['Qwen2.5-72B-Instruct_111541']" }
0.418742
Filter_54468
I
[ "pick_random_number", "is_guess_correct", "play_guessing_game" ]
3
[ [ "play_guessing_game", "is_guess_correct" ], [ "play_guessing_game", "pick_random_number" ] ]
2
[]
false
[]
false
pytest
true
[]
true
6c600bde07eae3c3d4774dc8516a23ad99572fea
40642509e577d747591dca37909fcbcbe720fda0
v1.0
instruct
Filter
Filter_54717_I
Write a Python function that takes a list of positive integers and returns the most frequent prime factor among all the integers in the list. If there are multiple prime factors with the same highest frequency, return the smallest one. If the list contains no prime factors, the function should return -1.
from collections import Counter import math def prime_factors(n): """Returns the list of prime factors of a given number n.""" i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n...
from solution import most_frequent_prime_factor def test_most_frequent_prime_factor_single_number(): assert most_frequent_prime_factor([30]) == 2 # prime factors 2, 3, 5; all equally frequent (once), smallest is 2 def test_most_frequent_prime_factor_multiple_numbers(): assert most_frequent_prime_factor([30, ...
[ { "docstring": "Returns the list of prime factors of a given number n.", "function_declaration": "def prime_factors(n):", "function_name": "prime_factors", "parameter_list": "(n)" }, { "docstring": "Returns the most frequent prime factor among all the integers in the list.\nIf there are mult...
[ 0, 0, 0, 0, 1, 1, 1, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import defaultdict, Counter\nfrom math import isqrt\n\ndef is_prime(n):\n \"\"\"\n Check if a number is a prime\n \"\"\"\n if n <= 1:\n return False\n if...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00054717", "row_id": 54717, "seed_ids": "['Qwen2.5-72B-Instruct_111971']" }
0.709665
Filter_54717
I
[ "prime_factors", "most_frequent_prime_factor" ]
2
[ [ "most_frequent_prime_factor", "prime_factors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
452f2268a4bd201c42de3a19d1a522aafc2684f2
393b1731715970fba83870ecb8c812be8ae37403
v1.0
instruct
Filter
Filter_54915_I
Write a Python program that implements a simple Guess the Number game. The program should generate a random number between 1 and 100, and the player will have 7 tries to guess the number. The program should give hints like "Too high!" or "Too low!" if the guess is not correct. After 7 unsuccessful guesses, the game sho...
import random def guess_the_number(): number_to_guess = random.randint(1, 100) attempts = 7 print("Welcome to Guess the Number!") print("You have 7 attempts to guess the number between 1 and 100.") for attempt in range(1, attempts + 1): try: guess = int(input(f"Attempt...
# As the game is interactive and relies on random number generation, # we can't directly unit test the game flow with standard methods. # Instead, we will provide mock inputs and simulate unit tests. from unittest.mock import patch from solution import guess_the_number, start_new_game def test_guess_correct_on_first_...
[ { "docstring": null, "function_declaration": "def guess_the_number():", "function_name": "guess_the_number", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def start_new_game():", "function_name": "start_new_game", "parameter_list": "()" } ]
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef guess_the_number():\n number = random.randint(1, 100)\n attempts = 7\n print(\"Guess the Number Game\")\n print(\"You have 7 tries to guess the number between ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00054915", "row_id": 54915, "seed_ids": "['Qwen2.5-72B-Instruct_112296']" }
0.553507
Filter_54915
I
[ "guess_the_number", "start_new_game" ]
2
[ [ "start_new_game", "guess_the_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2227a4e6cae31f0f1dbdab15201b182247bba4b6
576a4e90433bf4110b082f991d5f97c7c56cf735
v1.0
instruct
Filter
Filter_54994_I
How can I program a simple digital clock using Python?
import time import tkinter as tk def update_time(clock_label): """ Updates the clock label with the current time. """ current_time = time.strftime('%H:%M:%S') clock_label.config(text=current_time) clock_label.after(1000, update_time, clock_label) def run_clock(): """ Creates and runs t...
import pytest import time from unittest.mock import patch from solution import update_time def test_update_time(): class MockLabel: def __init__(self): self.text = "" def config(self, text): self.text = text def after(self, ms, func, *args): assert ms =...
[ { "docstring": "Updates the clock label with the current time.", "function_declaration": "def update_time(clock_label):", "function_name": "update_time", "parameter_list": "(clock_label)" }, { "docstring": "Creates and runs the tkinter clock window.", "function_declaration": "def run_clo...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import tkinter as tk\nimport time\n\ndef update_time():\n \"\"\"Updates the time displayed on the label.\"\"\"\n current_time = time.strftime('%H:%M:%S')\n clock_label.config(text=cur...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00054994", "row_id": 54994, "seed_ids": "['Qwen2.5-72B-Instruct_112421']" }
0.461817
Filter_54994
I
[ "update_time", "run_clock" ]
2
[ [ "run_clock", "update_time" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c0302dea9c22dad4832b011275ac4c4cc68b5b34
240d659af02e991e02855af027577fa1d071691c
v1.0
instruct
Filter
Filter_55039_I
How can I create a Python program that reads and processes images for a machine learning project?
from PIL import Image import numpy as np def load_image(image_path): """ Loads an image from the specified path. Parameters: image_path (str): Path to the image file. Returns: Image: Loaded image object. """ return Image.open(image_path) def convert_to_grayscale(image): """ C...
from solution import load_image, convert_to_grayscale, resize_image, normalize_image, preprocess_image import numpy as np import os from PIL import Image def test_load_image(tmp_path): # Create a temporary image temp_image_path = os.path.join(tmp_path, "temp_image.jpg") Image.new('RGB', (10, 10)).save(temp...
[ { "docstring": "Loads an image from the specified path.\n\nParameters:\nimage_path (str): Path to the image file.\n\nReturns:\nImage: Loaded image object.", "function_declaration": "def load_image(image_path):", "function_name": "load_image", "parameter_list": "(image_path)" }, { "docstring"...
[ 0, 0, 0, 0, 0, 1, 0, 1, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cv2\n\ndef process_image(image_path, target_size=(224, 224)):\n \"\"\"\n Reads an image from the given path, resizes it to the target size,\n and returns the image as a numpy a...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00055039", "row_id": 55039, "seed_ids": "['Qwen2.5-72B-Instruct_112484']" }
0.451439
Filter_55039
I
[ "load_image", "convert_to_grayscale", "resize_image", "normalize_image", "preprocess_image" ]
5
[ [ "preprocess_image", "convert_to_grayscale" ], [ "preprocess_image", "load_image" ], [ "preprocess_image", "normalize_image" ], [ "preprocess_image", "resize_image" ] ]
4
[]
false
[]
false
pytest
true
[ "PIL", "numpy" ]
false
f7e821c840a4253febac1e7ba7249de77e252194
9ffcf71f43ac03bead38170b457232d0b3a12752
v1.0
instruct
Filter
Filter_55307_I
I have a list of phone numbers and I need to format them to a standard international format. Can you provide a Python script that takes a CSV file with a column of local phone numbers and outputs a CSV file with the numbers formatted in the international format? The script should handle North American and European phon...
import csv import re def format_phone_number(number): """ Formats a phone number to international format. Assumes North American numbers are 10 digits European numbers starting with '+' are considered valid. Args: - number (str): The phone number to format. Returns: - str: The...
from solution import format_phone_number, format_phone_numbers_in_csv import csv import tempfile def test_format_phone_number_north_american(): assert format_phone_number("1234567890") == "+11234567890" assert format_phone_number("(123) 456-7890") == "+11234567890" def test_format_phone_number_european(): ...
[ { "docstring": "Formats a phone number to international format.\nAssumes North American numbers are 10 digits\nEuropean numbers starting with '+' are considered valid.\n\nArgs:\n- number (str): The phone number to format.\n\nReturns:\n- str: The formatted phone number.", "function_declaration": "def format_...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\nimport re\n\ndef format_phone_number(number):\n \"\"\"\n Format the phone number to international format.\n Assumes North American and European numbers. Uses +1 for North ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00055307", "row_id": 55307, "seed_ids": "['Qwen2.5-72B-Instruct_112940']" }
0.518074
Filter_55307
I
[ "format_phone_number", "format_phone_numbers_in_csv" ]
2
[ [ "format_phone_numbers_in_csv", "format_phone_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0780b8aad156cad45e47e14543a33feec64555e6
eb6ff633023079edf22fefad333007877f290366
v1.0
instruct
Filter
Filter_55360_I
Design a Python script to automate the process of checking a website's availability and responsiveness. The script should log any issues and notify the user via email if the website is down. Also, include a feature to check the website at regular intervals.
import smtplib import logging import requests from time import sleep from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_email(subject, body, to_email, from_email, smtp_server, smtp_port, smtp_user, smtp_password): msg = MIMEMultipart() msg['From'] = from_email msg[...
import requests from unittest.mock import patch, MagicMock from solution import send_email, check_website def test_check_website(): # Mock request.get to always return a mock response with status_code 200 with patch('requests.get') as mock_get: mock_response = MagicMock(status_code=200) mock_ge...
[ { "docstring": null, "function_declaration": "def send_email(subject, body, to_email, from_email, smtp_server, smtp_port, smtp_user, smtp_password):", "function_name": "send_email", "parameter_list": "(subject, body, to_email, from_email, smtp_server, smtp_port, smtp_user, smtp_password)" }, { ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import smtplib\nimport requests\nimport time\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\ndef send_email(subject, body, to_email):\n from_email =...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00055360", "row_id": 55360, "seed_ids": "['Qwen2.5-72B-Instruct_113028']" }
0.537852
Filter_55360
I
[ "send_email", "check_website", "monitor_website" ]
3
[ [ "monitor_website", "check_website" ], [ "monitor_website", "send_email" ] ]
2
[]
false
[]
false
pytest
true
[ "requests" ]
false
9644a19cc1dfb733dd3306df6ab0a10463d42a74
f243c7b678f5bf284cebac382331a5ec7d374236
v1.0
instruct
Filter
Filter_55379_I
Create a Python function that determines the convex hull of a set of 2D points using the Gift Wrapping Algorithm (also known as Jarvis march). The function should take a list of points as input and return the list of points that form the convex hull, in the order they appear on the hull. Each point is a list or tuple o...
import matplotlib.pyplot as plt def cross_product(o, a, b): """ Cross product of vector OA and OB A positive cross product indicates a counter-clockwise turn, and a negative cross product indicates a clockwise turn. """ return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) def ...
from solution import gift_wrapping def test_gift_wrapping_basic(): points = [(0, 0), (1, 1), (2, 2), (3, 1), (2, 0), (1, 2)] hull = gift_wrapping(points) expected_hull = [(0, 0), (2, 0), (3, 1), (2, 2), (1, 2)] assert sorted(hull) == sorted(expected_hull) def test_gift_wrapping_triangle(): points ...
[ { "docstring": "Cross product of vector OA and OB\nA positive cross product indicates a counter-clockwise turn, \nand a negative cross product indicates a clockwise turn.", "function_declaration": "def cross_product(o, a, b):", "function_name": "cross_product", "parameter_list": "(o, a, b)" }, {...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import matplotlib.pyplot as plt\n\ndef orientation(p, q, r):\n \"\"\"\n This function determines the orientation of the triplet (p, q, r).\n Returns following values:\n 0 -> p, q ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00055379", "row_id": 55379, "seed_ids": "['Qwen2.5-72B-Instruct_113064']" }
0.484733
Filter_55379
I
[ "cross_product", "gift_wrapping", "plot_convex_hull" ]
3
[ [ "gift_wrapping", "cross_product" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib" ]
false
a9cfccd0b1d4d085b7b340db09e0b7932ba80d49
cfbcbc7c606a9765ba266f0c8ee0c6b391a69356
v1.0
instruct
Filter
Filter_55471_I
Write a Python script that takes a sentence as input and prints the longest word in the sentence along with its length. If there are multiple words with the same maximum length, it should print all of them. For example, given the sentence "The quick brown fox jumps over the lazy dog", the script should output: "The lon...
def find_longest_words(sentence): """ Returns the longest word(s) in the sentence along with its length. """ words = sentence.split() max_length = 0 longest_words = [] for word in words: word_length = len(word) if word_length > max_length: max_length = word_l...
from solution import find_longest_words, print_longest_words def test_find_longest_words_single_longest(): sentence = "The quick brown fox" expected_words = ["quick", "brown"] expected_length = 5 assert find_longest_words(sentence) == (expected_words, expected_length) def test_find_longest_words_multi...
[ { "docstring": "Returns the longest word(s) in the sentence along with its length.", "function_declaration": "def find_longest_words(sentence):", "function_name": "find_longest_words", "parameter_list": "(sentence)" }, { "docstring": "Prints the longest word(s) in the sentence along with its...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def longest_words(sentence):\n \"\"\"\n Given a sentence, returns the longest word(s) in the sentence along with its length.\n If there are multiple words with the same maximum length...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00055471", "row_id": 55471, "seed_ids": "['Qwen2.5-72B-Instruct_113207']" }
0.790305
Filter_55471
I
[ "find_longest_words", "print_longest_words" ]
2
[ [ "print_longest_words", "find_longest_words" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3c1d3781206c56429b3caecb4bc43721013ec57a
0499c8bd72031dd7e803c5bca53aa1fa6056d3ca
v1.0
instruct
Filter
Filter_55473_I
Design a simple neural network from scratch in Python for classifying handwritten digits using the MNIST dataset. Use only standard Python libraries and NumPy. Include comments and explanations for each step, including the structure of the neural network, the initialization of weights, the forward and backward propagat...
import numpy as np # Sigmoid activation function def sigmoid(x): return 1 / (1 + np.exp(-x)) # Derivative of the sigmoid function def sigmoid_derivative(x): return x * (1 - x) # ReLU activation function def relu(x): return np.maximum(0, x) # Derivative of the ReLU function def relu_derivative(x): re...
import numpy as np def test_sigmoid(): assert np.isclose(sigmoid(0.0), 0.5) def test_sigmoid_derivative(): x = np.array([0.5, 0.25, 0.0]) y = sigmoid(x) dy = sigmoid_derivative(y) assert np.allclose(dy, y * (1 - y)) def test_relu(): x = np.array([-1.0, 0.0, 1.0]) y = relu(x) assert np...
[ { "docstring": null, "function_declaration": "def sigmoid(x):", "function_name": "sigmoid", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def sigmoid_derivative(x):", "function_name": "sigmoid_derivative", "parameter_list": "(x)" }, { "docstring...
[ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport gzip\nimport pickle\n\ndef load_mnist():\n with gzip.open('mnist.pkl.gz', 'rb') as f:\n train_set, valid_set, test_set = pickle.load(f, encoding='latin1')\...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00055473", "row_id": 55473, "seed_ids": "['Qwen2.5-72B-Instruct_113212']" }
0.423002
Filter_55473
I
[ "sigmoid", "sigmoid_derivative", "relu", "relu_derivative", "initialize_weights", "forward_propagation", "compute_loss", "backward_propagation", "update_weights", "train", "predict", "accuracy" ]
12
[ [ "backward_propagation", "relu_derivative" ], [ "forward_propagation", "relu" ], [ "forward_propagation", "sigmoid" ], [ "predict", "forward_propagation" ], [ "train", "backward_propagation" ], [ "train", "compute_loss" ], [ "train", "...
9
[]
false
[]
false
pytest
false
[ "numpy" ]
false
1ec4e3dd1e17e3d2a8054ef4c9c454f1122e8141
e18538a55601174c8a416ef916729585dc7d543f
v1.0
instruct
Filter
Filter_55598_I
Implement a radix sort algorithm to sort a list of numbers. Explain your code and the steps involved.
def radix_sort(arr): """ Perform radix sort on a list of integers. """ if len(arr) == 0: return arr # Determine the maximum number to know the number of digits max_num = max(arr) exp = 1 # Represents the digit we are currently sorting by (1 for units, 10 for tens, etc.) # Perf...
from solution import radix_sort def test_radix_sort_empty(): assert radix_sort([]) == [] def test_radix_sort_single_element(): assert radix_sort([5]) == [5] def test_radix_sort_sorted_list(): assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_radix_sort_reverse_sorted_list(): assert radi...
[ { "docstring": "Perform radix sort on a list of integers.", "function_declaration": "def radix_sort(arr):", "function_name": "radix_sort", "parameter_list": "(arr)" }, { "docstring": "Helper function to perform counting sort based on the digit represented by exp.", "function_declaration"...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def counting_sort(arr, exp):\n \"\"\"\n A function to perform counting sort on arr[] according to the digit represented by exp.\n \"\"\"\n n = len(arr)\n output = [0] * n # out...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00055598", "row_id": 55598, "seed_ids": "['Qwen2.5-72B-Instruct_113435']" }
0.576239
Filter_55598
I
[ "radix_sort", "counting_sort_by_digit" ]
2
[ [ "radix_sort", "counting_sort_by_digit" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3904023c7798fba31514c4c29fa788dad80b66da
bde349f46aabab692d034e4096ff5512fa30c46f
v1.0
instruct
Filter
Filter_55727_I
Write a Python script to monitor the temperature of a CPU using the psutil library and send an email alert if the temperature exceeds a certain threshold. Assume you have access to an SMTP server for sending emails. Include necessary error handling and make the script efficient and clean.
import psutil import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def get_cpu_temperature(): """ Retrieve the current CPU temperature. """ temps = psutil.sensors_temperatures() if 'coretemp' in temps: core_temps = temps['coretemp'] for ...
import pytest from unittest.mock import patch, MagicMock from solution import get_cpu_temperature, send_email_alert, monitor_cpu_temperature @patch('psutil.sensors_temperatures') def test_get_cpu_temperature(mock_sensors): mock_sensors.return_value = { 'coretemp': [MagicMock(label='Package id 0', current=6...
[ { "docstring": "Retrieve the current CPU temperature.", "function_declaration": "def get_cpu_temperature():", "function_name": "get_cpu_temperature", "parameter_list": "()" }, { "docstring": "Send an email alert with the specified subject and body.", "function_declaration": "def send_ema...
[ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import psutil\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef get_cpu_temp():\n \"\"\"\n Returns the current temperature of t...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00055727", "row_id": 55727, "seed_ids": "['Qwen2.5-72B-Instruct_113637']" }
0.468145
Filter_55727
I
[ "get_cpu_temperature", "send_email_alert", "monitor_cpu_temperature" ]
3
[ [ "monitor_cpu_temperature", "get_cpu_temperature" ], [ "monitor_cpu_temperature", "send_email_alert" ] ]
2
[]
false
[]
false
pytest
true
[ "psutil" ]
false
6925a610012177c95af754a6cc9819e979ef7c09
c8f4e284c2f2481a31ed1f2c22e372046144c52f
v1.0
instruct
Filter
Filter_55815_I
Design a Python function that reads a JSON file and converts it into a well-structured XML string. Ensure that the function is robust, handling invalid file paths and JSON format errors gracefully. Additionally, include a feature to escape any special characters that might interfere with the XML formatting. Provide a b...
import json import xml.etree.ElementTree as ET import os def json_to_xml(json_dict, root_tag_name='root'): """ Converts a JSON dictionary to an XML string. json_dict : dict The JSON dictionary to convert. root_tag_name : str The name of the root tag for the XML. Returns an...
from solution import read_json_file, json_to_xml import pytest import json def test_invalid_file_path(): result = read_json_file('non_existent_file.json') assert result == "Invalid file path" def test_invalid_json_format(tmp_path): invalid_json_file = tmp_path / "invalid.json" invalid_json_file.write...
[ { "docstring": "Converts a JSON dictionary to an XML string.\n\njson_dict : dict\n The JSON dictionary to convert.\nroot_tag_name : str\n The name of the root tag for the XML.\n\nReturns an XML string.", "function_declaration": "def json_to_xml(json_dict, root_tag_name='root'):", "function_name": ...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\nimport xml.etree.ElementTree as ET\nfrom xml.sax.saxutils import escape\n\ndef json_to_xml(json_file_path, xml_root_element=\"root\"):\n \"\"\"\n Converts a JSON file to a w...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00055815", "row_id": 55815, "seed_ids": "['Qwen2.5-72B-Instruct_113788']" }
0.733837
Filter_55815
I
[ "json_to_xml", "read_json_file" ]
2
[ [ "read_json_file", "json_to_xml" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3073fc5babf77962de58964b0b7c81f482dab315
74e1c5f47a0488cbd83d06f7cdca4c168f44c454
v1.0
instruct
Filter
Filter_55933_I
Create an analog clock face with Roman numerals using ASCII art. The clock should be able to display time in 12-hour format. Make sure the hour and minute hands are distinguishable, and the clock can be updated to show different times. Additionally, provide a simple mechanism to update the clock's time.
def create_clock_face(hour, minute): """ Creates an analog clock face with roman numerals using ASCII art. The clock shows the time in 12-hour format. Parameters: hour (int): The hour to be displayed on the clock (1-12). minute (int): The minute to be displayed on the clock (0-59). Ret...
from solution import create_clock_face, update_time def test_create_clock_face(): clock_face = create_clock_face(3, 30) expected_face = """\ 12 11 1 10 2 9 3 8 4 6 """ assert clock_face == expected_face # Add more...
[ { "docstring": "Creates an analog clock face with roman numerals using ASCII art.\nThe clock shows the time in 12-hour format.\n\nParameters:\nhour (int): The hour to be displayed on the clock (1-12).\nminute (int): The minute to be displayed on the clock (0-59).\n\nReturns:\nstr: A string representing the cloc...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def ascii_analog_clock(hour, minute):\n \"\"\"\n Generate a string representing an analog clock face with the given hour and minute.\n The clock is represented using ASCII art with Ro...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00055933", "row_id": 55933, "seed_ids": "['Qwen2.5-72B-Instruct_114000']" }
0.389142
Filter_55933
I
[ "create_clock_face", "update_time" ]
2
[ [ "update_time", "create_clock_face" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cf6ad9a56d9ac6e111c28d150e5c458c18712840
9f32c5d43a740303a9e5a1d622c59e28a569d799
v1.0
instruct
Filter
Filter_56142_I
Write a Python script that can convert CSV files to JSON format. The script should be able to handle large files and multiple files at once. It should also be able to specify the output directory. The script should have clear and helpful usage instructions and error handling.
import csv import json import os from pathlib import Path def csv_to_json(csv_file, output_dir='.'): """ Convert a CSV file to JSON format and save it to the specified output directory. Parameters: - csv_file: str or Path, path to the input CSV file - output_dir: str or Path, directory where t...
import os import json import pytest from tempfile import TemporaryDirectory from solution import csv_to_json, convert_multiple_csv_to_json def test_csv_to_json(): with TemporaryDirectory() as tmpdir: csv_content = "id,name,age\n1,John Doe,30\n2,Jane Doe,25\n" csv_path = os.path.join(tmpdir, "test.c...
[ { "docstring": "Convert a CSV file to JSON format and save it to the specified output directory.\n\nParameters:\n- csv_file: str or Path, path to the input CSV file\n- output_dir: str or Path, directory where the output JSON file will be saved\n\nReturns:\n- output_file_path: Path, path to the generated JSON fi...
[ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\nimport json\nimport os\nimport glob\n\ndef convert_csv_to_json(input_directory, output_directory):\n \"\"\"\n Converts all CSV files in the input_directory to JSON format and...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00056142", "row_id": 56142, "seed_ids": "['Qwen2.5-72B-Instruct_114354']" }
0.686662
Filter_56142
I
[ "csv_to_json", "convert_multiple_csv_to_json" ]
2
[ [ "convert_multiple_csv_to_json", "csv_to_json" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cc94e78adf971da3e783259d3c2a4f026d7c0dc1
3842b064595f412a03857805fd82d46faebca9a1
v1.0
instruct
Filter
Filter_56150_I
Write a Python script that converts a given file from one format to another. The source and target formats should be specified as command-line arguments. Assume the conversion can be done using a dummy conversion function that you will define in the script. Ensure your script checks for the correct number of arguments ...
import sys def dummy_conversion(content, source_format, target_format): """ Dummy conversion function that simply returns the content prefixed with a message showing conversion from source_format to target_format. """ return f"Converted from {source_format} to {target_format}:\n{content}" def con...
import os import pytest from solution import convert_file, dummy_conversion def test_dummy_conversion(): assert dummy_conversion("Hello, world!", "txt", "md") == "Converted from txt to md:\nHello, world!" def test_convert_file(tmp_path): source_file = tmp_path / "source.txt" target_file = tmp_path / "targ...
[ { "docstring": "Dummy conversion function that simply returns the content prefixed \nwith a message showing conversion from source_format to target_format.", "function_declaration": "def dummy_conversion(content, source_format, target_format):", "function_name": "dummy_conversion", "parameter_list":...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\n\ndef dummy_conversion(content, source_format, target_format):\n \"\"\"\n This dummy conversion function simulates converting content from one format to another.\n It simp...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00056150", "row_id": 56150, "seed_ids": "['Qwen2.5-72B-Instruct_114363']" }
0.580399
Filter_56150
I
[ "dummy_conversion", "convert_file" ]
2
[ [ "convert_file", "dummy_conversion" ] ]
1
[]
false
[]
false
pytest
true
[]
true
016b7202a50e1f2a6448d0f121056ced5be98c36
7a675f2430914462e15c954574ff5ac4eca2a4e4
v1.0
instruct
Filter
Filter_56156_I
Create a Python program to simulate Conway's Game of Life with a random initial population and display the evolution for 100 generations. Use the `matplotlib` library to visualize the grid at each step. The size of the grid should be 50x50.
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def initialize_grid(size): """ Returns a randomly initialized grid of given size. """ return np.random.choice([1, 0], size*size, p=[0.2, 0.8]).reshape(size, size) def update_grid(grid): """ Computes one...
from solution import initialize_grid, update_grid def test_initialize_grid(): grid = initialize_grid(50) assert grid.shape == (50, 50) assert set(np.unique(grid)) == {0, 1} def test_update_grid_no_changes(): grid = np.zeros((5, 5)) new_grid = update_grid(grid) assert np.array_equal(grid, new_g...
[ { "docstring": "Returns a randomly initialized grid of given size.", "function_declaration": "def initialize_grid(size):", "function_name": "initialize_grid", "parameter_list": "(size)" }, { "docstring": "Computes one step in the Game of Life.", "function_declaration": "def update_grid(g...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\ndef initialize_grid(size):\n \"\"\"\n Initialize the grid with a random initial populatio...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00056156", "row_id": 56156, "seed_ids": "['Qwen2.5-72B-Instruct_114372']" }
0.376475
Filter_56156
I
[ "initialize_grid", "update_grid", "animate", "simulate_game_of_life" ]
4
[ [ "animate", "update_grid" ], [ "simulate_game_of_life", "animate" ], [ "simulate_game_of_life", "initialize_grid" ] ]
3
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
c9963047389a24cb7f2f7fefda6813b345b5ed02
6894101d9669fac2cb36d19c7c691d302023b3f4
v1.0
instruct
Filter
Filter_56234_I
How can I develop a simple chatbot using Python and natural language processing libraries?
import random class SimpleChatbot: def __init__(self): self.greetings = ["Hello!", "Hi there!", "Hey!", "Hi! How can I help you today?"] self.farewells = ["Goodbye!", "See you later!", "Have a nice day!", "Bye!"] self.default_responses = [ "I'm not sure I understand.", ...
from solution import SimpleChatbot def test_generate_response_greeting(): bot = SimpleChatbot() response = bot.generate_response("Hi there") assert response in bot.greetings def test_generate_response_farewell(): bot = SimpleChatbot() response = bot.generate_response("Goodbye") assert response...
[]
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import nltk\nfrom nltk.chat.util import Chat, reflections\n\ndef create_chatbot():\n \"\"\"\n Creates a simple chatbot using predefined patterns and responses.\n \"\"\"\n pairs = [...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00056234", "row_id": 56234, "seed_ids": "['Qwen2.5-72B-Instruct_114503']" }
0.399448
Filter_56234
I
[ "create_chatbot", "chat_with_bot" ]
2
[ [ "chat_with_bot", "create_chatbot" ] ]
1
[]
false
[ "SimpleChatbot" ]
true
pytest
true
[]
true
60851840b052424d7afb3381a5a2133424203fb5
b429eea6cab8fa1879081e7d4ec80dc0992c8a07
v1.0
instruct
Filter
Filter_56280_I
Design a Python function to calculate the sum of a peculiar series for a given input $x$. The series is defined as $S_n = x - \frac{x^2}{2} + \frac{x^3}{3} - \frac{x^4}{4} + \cdots + (-1)^{n+1}\frac{x^n}{n}$. The function should calculate the sum of the series $S_n$ for a given $x$ and a positive integer $n$. Additiona...
def series_sum(x, n): """ Calculate the sum of the series S_n defined as: S_n = x - x^2/2 + x^3/3 - x^4/4 + ... + (-1)^(n+1) * x^n / n Args: x : float : The value of x n : int : The number of terms to include in the series Returns: float : The sum of the series up to n terms ...
from solution import series_sum, check_series_sum def test_series_sum_basic(): assert series_sum(1, 1) == 1 assert series_sum(1, 2) == 0.5 assert abs(series_sum(1, 3) - 0.833333) < 1e-6 def test_series_sum_negative(): assert series_sum(-1, 1) == -1 assert series_sum(-1, 2) == -1.5 assert abs(s...
[ { "docstring": "Calculate the sum of the series S_n defined as:\nS_n = x - x^2/2 + x^3/3 - x^4/4 + ... + (-1)^(n+1) * x^n / n\n\nArgs:\nx : float : The value of x\nn : int : The number of terms to include in the series\n\nReturns:\nfloat : The sum of the series up to n terms", "function_declaration": "def s...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def peculiar_series_sum(x, n):\n \"\"\"\n Calculate the sum of the series S_n for a given x and a positive integer n.\n\n The series is defined as:\n S_n = x - x^2/2 + x^3/3 - x^4/...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00056280", "row_id": 56280, "seed_ids": "['Qwen2.5-72B-Instruct_114574']" }
0.532563
Filter_56280
I
[ "series_sum", "check_series_sum" ]
2
[ [ "check_series_sum", "series_sum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f04b24d2d26af22a465362013610b8c5f7f7199c
1f020abe8545255e59b74aa13bd2151ddb665383
v1.0
instruct
Filter
Filter_56304_I
Write a Python function that simulates the roll of two six-sided dice, calculates the sum of the two dice, and returns the result. Also, simulate this process 100 times and print the distribution of the sums. Remember to use a seed value of 42 for reproducibility.
import random def roll_two_dice(): """ Simulates the roll of two six-sided dice and returns the sum. """ die1 = random.randint(1, 6) die2 = random.randint(1, 6) return die1 + die2 def simulate_rolls(num_rolls=100, seed=42): """ Simulates rolling two dice `num_rolls` times and returns a...
from solution import roll_two_dice, simulate_rolls def test_roll_two_dice_within_range(): sum_of_dice = roll_two_dice() assert 2 <= sum_of_dice <= 12 def test_simulate_rolls_length(): distribution = simulate_rolls(100) assert sum(distribution.values()) == 100 def test_simulate_rolls_reproducibility()...
[ { "docstring": "Simulates the roll of two six-sided dice and returns the sum.", "function_declaration": "def roll_two_dice():", "function_name": "roll_two_dice", "parameter_list": "()" }, { "docstring": "Simulates rolling two dice `num_rolls` times and returns a distribution of the sums.\nUs...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom collections import Counter\n\ndef roll_two_dice():\n \"\"\"\n Simulates the roll of two six-sided dice and returns the sum of the two dice.\n \"\"\"\n die1 = ra...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00056304", "row_id": 56304, "seed_ids": "['Qwen2.5-72B-Instruct_114627']" }
0.668009
Filter_56304
I
[ "roll_two_dice", "simulate_rolls" ]
2
[ [ "simulate_rolls", "roll_two_dice" ] ]
1
[]
false
[]
false
pytest
true
[]
true
437ec7a987850c4dce2794d6d28f1a7968466bcb
fbe37fc522c35f7492eab7e8f8862a2230efb4aa
v1.0
instruct
Filter
Filter_56428_I
Can you assist me with creating a basic algorithm for a recommendation system based on user ratings in Python? I'm looking for something simple that uses item-based collaborative filtering.
import numpy as np def cosine_similarity(matrix): """ Compute the cosine similarity between each pair of rows in the given matrix. Parameters: matrix (np.array): 2D matrix where each row is a vector of ratings. Returns: np.array: 2D array of cosine similarity scores. """ dot_p...
from solution import item_based_recommendations import numpy as np def test_cosine_similarity(): matrix = np.array([[1, 0, 0], [0, 1, 0], [1, 1, 0]]) expected = np.array([[1.0, 0.0, 0.70710678], [0.0, 1.0, 0.70710678], [0.70710678, 0.70710678, 1.0]]) result...
[ { "docstring": "Compute the cosine similarity between each pair of rows in the given matrix.\n\nParameters:\nmatrix (np.array): 2D matrix where each row is a vector of ratings.\n\nReturns:\nnp.array: 2D array of cosine similarity scores.", "function_declaration": "def cosine_similarity(matrix):", "funct...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import defaultdict\nimport numpy as np\n\ndef calculate_similarity(item_ratings):\n \"\"\"\n Calculate the cosine similarity between items.\n \"\"\"\n similarity =...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00056428", "row_id": 56428, "seed_ids": "['Qwen2.5-72B-Instruct_114841']" }
0.455526
Filter_56428
I
[ "cosine_similarity", "item_based_recommendations" ]
2
[ [ "item_based_recommendations", "cosine_similarity" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
def62fd36788c3c823120733ad0c11f09be95433
1871b23e9eda12ccc248a9c87e9f9006b105d54e
v1.0
instruct
Filter
Filter_56772_I
I want to create a simple web application that allows users to upload images, and the application will display the dominant colors of the image. How can I achieve this using Python and a web framework like Flask?
from flask import Flask, request, render_template, redirect from PIL import Image import numpy as np import io from sklearn.cluster import KMeans import matplotlib.pyplot as plt app = Flask(__name__) def get_dominant_colors(image, k=5): """ Gets the dominant colors of the image using KMeans clustering. :...
from solution import get_dominant_colors from PIL import Image import numpy as np def test_get_dominant_colors_single_color(): # Create an image with a single color (red) red_image = Image.new('RGB', (100, 100), 'red') colors = get_dominant_colors(red_image, k=1) assert len(colors) == 1 assert np....
[ { "docstring": "Gets the dominant colors of the image using KMeans clustering.\n\n:param image: Input image as a PIL image object\n:param k: Number of dominant colors to find\n:return: List of the RGB values of the dominant colors", "function_declaration": "def get_dominant_colors(image, k=5):", "functi...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from flask import Flask, request, render_template, redirect, url_for\nfrom werkzeug.utils import secure_filename\nimport os\nfrom PIL import Image\nimport numpy as np\nfrom sklearn.cluster imp...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00056772", "row_id": 56772, "seed_ids": "['Qwen2.5-72B-Instruct_115420']" }
0.384945
Filter_56772
I
[ "get_dominant_colors", "upload_file", "result_page" ]
3
[ [ "upload_file", "get_dominant_colors" ] ]
1
[]
false
[]
false
pytest
true
[ "PIL", "flask", "matplotlib", "numpy", "sklearn" ]
false
89f0406fe443563406da22132ed9d7dad4b51931
81d21bc0f5cfa135a882a494c03a060cd69c8aa0
v1.0
instruct
Filter
Filter_56805_I
Write a Python code that calculates the factorial of a number and returns the result modulo a given prime. Use this function to define another function that calculates the binomial coefficient (\( \binom{n}{k} \)) modulo a prime number. Ensure to use efficient algorithms to handle large numbers.
def factorial_mod(n, prime): """ Returns the factorial of n modulo a prime number. """ result = 1 for i in range(2, n + 1): result = (result * i) % prime return result def mod_inverse(a, prime): """ Returns the modular inverse of a under modulo prime using Fermat's Little Theore...
from solution import factorial_mod, binomial_coefficient_mod def test_factorial_mod(): # Testing factorial_mod function assert factorial_mod(5, 13) == 120 % 13 assert factorial_mod(6, 17) == 720 % 17 assert factorial_mod(0, 7) == 1 assert factorial_mod(1, 7) == 1 def test_binomial_coefficient_mod_...
[ { "docstring": "Returns the factorial of n modulo a prime number.", "function_declaration": "def factorial_mod(n, prime):", "function_name": "factorial_mod", "parameter_list": "(n, prime)" }, { "docstring": "Returns the modular inverse of a under modulo prime using Fermat's Little Theorem.\n...
[ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def factorial_mod(n, prime):\n \"\"\"\n Returns the factorial of n modulo prime.\n \"\"\"\n if n == 0 or n == 1:\n return 1\n result = 1\n for i in range(2, n + 1):\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00056805", "row_id": 56805, "seed_ids": "['Qwen2.5-72B-Instruct_115473']" }
0.588324
Filter_56805
I
[ "factorial_mod", "mod_inverse", "binomial_coefficient_mod" ]
3
[ [ "binomial_coefficient_mod", "factorial_mod" ], [ "binomial_coefficient_mod", "mod_inverse" ] ]
2
[]
false
[]
false
pytest
true
[]
true
958be1e139238cfca76693671d11b99a72b84b0e
061eaac43e2142063aeab7efb3e169ca816e94ab
v1.0
instruct
Filter
Filter_56834_I
Can you help me with a script in Python to resize a large set of images in a folder to a specific width and height?
from PIL import Image import os def resize_images_in_folder(folder_path, width, height): """ Resizes all images in the specified folder to the specified width and height. Parameters: folder_path (str): Path to the folder containing images. width (int): The width to resize the images to. he...
import pytest from PIL import Image import os import shutil from solution import resize_images_in_folder, is_image_file # Helper functions for testing def setup_test_folder(): os.makedirs('test_images', exist_ok=True) for size in [(100, 200), (400, 400), (300, 600)]: img = Image.new('RGB', size, color...
[ { "docstring": "Resizes all images in the specified folder to the specified width and height.\n\nParameters:\nfolder_path (str): Path to the folder containing images.\nwidth (int): The width to resize the images to.\nheight (int): The height to resize the images to.", "function_declaration": "def resize_ima...
[ 0, 0, 0, 0, 0, 1, 0, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from PIL import Image\nimport os\n\ndef resize_images_in_folder(input_folder, output_folder, target_width, target_height):\n \"\"\"\n Resizes all images in the input_folder to the specif...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00056834", "row_id": 56834, "seed_ids": "['Qwen2.5-72B-Instruct_115525']" }
0.530096
Filter_56834
I
[ "resize_images_in_folder", "is_image_file" ]
2
[ [ "resize_images_in_folder", "is_image_file" ] ]
1
[]
false
[]
false
pytest
true
[ "PIL" ]
false
7fc1e9927c7a801406c3393890be1de3a1b2b411
7b86e21e5f081bc72e4bb2361b691fb94b283a93
v1.0
instruct
Filter
Filter_56888_I
How do I create a basic sentiment analysis model using Python?
import re from collections import Counter def preprocess_text(text): """ Preprocess the input text by removing special characters and lowercasing the text. """ text = re.sub(r'[^\w\s]', '', text) # Remove special characters text = text.lower() # Convert to lowercase return text def get_senti...
import pytest from solution import preprocess_text, get_sentiment, sentiment_analysis def test_preprocess_text(): assert preprocess_text("Hello, World!") == "hello world" assert preprocess_text("This is a TEST.") == "this is a test" assert preprocess_text("Python is awesome!!") == "python is awesome" def ...
[ { "docstring": "Preprocess the input text by removing special characters and lowercasing the text.", "function_declaration": "def preprocess_text(text):", "function_name": "preprocess_text", "parameter_list": "(text)" }, { "docstring": "Calculate sentiment based on the presence of positive a...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "# Basic Sentiment Analysis Model using Python and TextBlob\n\nfrom textblob import TextBlob\n\ndef basic_sentiment_analysis(text):\n \"\"\"\n Analyzes the sentiment of the given text usi...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00056888", "row_id": 56888, "seed_ids": "['Qwen2.5-72B-Instruct_115628']" }
0.599106
Filter_56888
I
[ "preprocess_text", "get_sentiment", "sentiment_analysis" ]
3
[ [ "sentiment_analysis", "get_sentiment" ], [ "sentiment_analysis", "preprocess_text" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f3a51454c6c0dae4b7870634b1a2337e3ad34df4
23833a7026e66d981121e033b3888424838897d1
v1.0
instruct
Filter
Filter_57102_I
Write a Python function that simulates the process of encoding and decoding a message using a Vigenere cipher. Ensure that your function can handle both uppercase and lowercase letters, and non-alphabetic characters should remain unchanged. Additionally, provide a check function to test the correctness of the encoding ...
def vigenere_cipher_encode(message, key): """ Encodes a message using the Vigenere cipher with the provided key. """ encoded_message = [] key_length = len(key) key = key.lower() key_index = 0 for char in message: if char.isalpha(): shift = ord(key[key_index % key...
from solution import vigenere_cipher_encode, vigenere_cipher_decode, check_vigenere_cipher def test_vigenere_cipher_encode(): assert vigenere_cipher_encode("HELLO WORLD", "KEY") == "RIJVS UYVJN" assert vigenere_cipher_encode("hello world", "key") == "rijvs uyvjn" assert vigenere_cipher_encode("Hello World!...
[ { "docstring": "Encodes a message using the Vigenere cipher with the provided key.", "function_declaration": "def vigenere_cipher_encode(message, key):", "function_name": "vigenere_cipher_encode", "parameter_list": "(message, key)" }, { "docstring": "Decodes a message using the Vigenere ciph...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def vigenere_cipher(message, key, mode='encode'):\n def shift_char(c, k, encode=True):\n if c.isalpha():\n o = ord('A') if c.isupper() else ord('a')\n k_shift =...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00057102", "row_id": 57102, "seed_ids": "['Qwen2.5-72B-Instruct_116005']" }
0.662932
Filter_57102
I
[ "vigenere_cipher_encode", "vigenere_cipher_decode", "check_vigenere_cipher" ]
3
[ [ "check_vigenere_cipher", "vigenere_cipher_decode" ], [ "check_vigenere_cipher", "vigenere_cipher_encode" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a4bdcaab2afd8c6d533d7d64fcd4186e726b46e2
c67f11a940ef00ed4eaac4a9c61e66df0e59410c
v1.0
instruct
Filter
Filter_57682_I
How can you assist me with creating a simple web application using Flask, a micro web framework for Python? I want to create a web app that displays a list of items and allows users to add new items to the list.
from flask import Flask, request, render_template_string app = Flask(__name__) # In-memory list to hold the items items = [] @app.route('/') def home(): return render_template_string(''' <h1>Item List</h1> <ul> {% for item in items %} <li>{{ item }}</li> {%...
import pytest from flask import Flask from solution import app, items @pytest.fixture def client(): app.config['TESTING'] = True client = app.test_client() yield client items.clear() # Clear the items after each test def test_home_page(client): """Test that the home page displays correctly.""" ...
[ { "docstring": null, "function_declaration": "def home():", "function_name": "home", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def add_item():", "function_name": "add_item", "parameter_list": "()" } ]
[ 0, 0, 0, 1, 0, 0, 1, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\n# This will store our items\nitems = []\n\n@app.route(\"/\")\ndef home():\n return jsonify({\"items\": items})\n\n@app....
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00057682", "row_id": 57682, "seed_ids": "['Qwen2.5-72B-Instruct_116982']" }
0.447052
Filter_57682
I
[ "home", "add_item" ]
2
[ [ "add_item", "home" ] ]
1
[]
false
[]
false
pytest
true
[ "flask" ]
false
f0d0c5f6d1366ba4bc1f10b07aa7844c1d1d4b34
8aa9b0e4437fe80acff0804ca0620e55f880f427
v1.0
instruct
Filter
Filter_57825_I
How can I create a dynamic pie chart using Python and Matplotlib that updates its data every second?
import matplotlib.pyplot as plt import numpy as np from matplotlib.animation import FuncAnimation import random def generate_data(): """ Generates random data for the pie chart. """ return [random.randint(1, 20) for _ in range(4)] def update_pie_chart(frame, wedges, texts, autotexts): """ Upda...
from solution import generate_data def test_generate_data_range(): # Check if the generated data is within the specified range data = generate_data() assert all(1 <= value <= 20 for value in data) def test_generate_data_length(): # Check if the generated data has the correct length data = generate...
[ { "docstring": "Generates random data for the pie chart.", "function_declaration": "def generate_data():", "function_name": "generate_data", "parameter_list": "()" }, { "docstring": "Update function for the animation, which updates the pie chart's data.", "function_declaration": "def upd...
[ 0, 0, 0, 0, 0, 1, 0, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import matplotlib.pyplot as plt\nimport numpy as np\nimport time\n\ndef update_pie_chart():\n plt.ion() # Turn on interactive mode\n \n fig, ax = plt.subplots()\n \n # Initial ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00057825", "row_id": 57825, "seed_ids": "['Qwen2.5-72B-Instruct_117241']" }
0.625621
Filter_57825
I
[ "generate_data", "update_pie_chart" ]
2
[ [ "update_pie_chart", "generate_data" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
748b6ea64cd7579f0428797a2d9927f718a08937
295e97d660a0c85259231967138fa164752acf78
v1.0
instruct
Filter
Filter_57826_I
Could you generate a script for a simple chatbot in Python, which can respond to greetings and answer basic questions about the weather? Assume there's an API for weather data that the chatbot can query.
import random import requests def chatbot_response(user_input): greetings = ["hello", "hi", "greetings", "sup", "what's up"] weather_questions = ["what's the weather like", "how's the weather", "weather", "forecast"] if any(greet in user_input.lower() for greet in greetings): return random.cho...
import pytest from unittest.mock import patch from solution import chatbot_response, get_weather_response @patch('solution.requests.get') def test_get_weather_response(mock_get): mock_response = { 'current': {'temp_c': 20, 'condition': {'text': 'Sunny'}} } mock_get.return_value.json.return_value = ...
[ { "docstring": null, "function_declaration": "def chatbot_response(user_input):", "function_name": "chatbot_response", "parameter_list": "(user_input)" }, { "docstring": null, "function_declaration": "def get_weather_response():", "function_name": "get_weather_response", "paramet...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\n\n# Assuming there's an API for weather data\nWEATHER_API_URL = \"https://api.example.com/weather\"\nWEATHER_API_KEY = \"YOUR_API_KEY\"\n\ndef get_weather(city):\n \"\"\"\n...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00057826", "row_id": 57826, "seed_ids": "['Qwen2.5-72B-Instruct_117242']" }
0.399021
Filter_57826
I
[ "chatbot_response", "get_weather_response" ]
2
[ [ "chatbot_response", "get_weather_response" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
f46c4da5b8586280f3cde0e1722b97fdc51cf29b
062d42b9b35bb7dd6401c000b9826b9376272a61
v1.0
instruct
Filter
Filter_58085_I
Implement a simple skip gram model in Python using PyTorch, then compare its performance with a continuous bag of words (CBOW) model implemented in the same manner and environment. Discuss the differences in their performance and potential reasons for these differences.
import torch import torch.nn as nn import torch.optim as optim from collections import Counter import random import numpy as np # Skip-gram Model class SkipGramModel(nn.Module): def __init__(self, vocab_size, embed_size): super(SkipGramModel, self).__init__() self.embeddings = nn.Embedding(vocab_si...
import pytest import torch from solution import prepare_data, SkipGramModel, CBOWModel, train_skipgram, train_cbow def test_prepare_data(): corpus = ["We are testing the models", "This is a simple corpus"] tokenized_corpus, word_to_idx, idx_to_word, vocab_size = prepare_data(corpus) assert len(tokenized_co...
[]
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom collections import defaultdict\nimport random\nimport numpy as np\n\n# Building a simple Skip-gram model\nclass SkipGramM...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00058085", "row_id": 58085, "seed_ids": "['Qwen2.5-72B-Instruct_117719']" }
0.520239
Filter_58085
I
[ "prepare_data", "train_skipgram", "train_cbow" ]
3
[ [ "train_cbow", "prepare_data" ], [ "train_skipgram", "prepare_data" ] ]
2
[]
false
[ "SkipGramModel", "CBOWModel" ]
true
pytest
true
[ "numpy", "torch" ]
false
eb92b68611dd4f9bf1ef5bf662debc1145dadb67
cd1867d97ac63d23a8e565849637a9551cc3f86f
v1.0
instruct
Filter
Filter_58116_I
How can I solve a Sudanese puzzle using Python code? The puzzle is a numerical 4 by 4 matrix where each row, column, and 2 by 2 subsquare must add up to 34, and all the numbers from 1 to 16 must be used exactly once. Can you provide a Python script that finds a solution to this puzzle?
def is_magic_square(matrix): """ Check if a 4x4 matrix is a magic square where each row, column, and 2x2 subsquare add up to 34 and contains all numbers from 1 to 16. """ target_sum = 34 n = len(matrix) # Check rows and columns sum for i in range(n): if sum(matrix[i]) ...
from solution import solve_sudanese_puzzle, is_magic_square def test_is_magic_square(): magic_square = [ [16, 3, 2, 13], [ 5, 10, 11, 8], [ 9, 6, 7, 12], [ 4, 15, 14, 1] ] assert is_magic_square(magic_square) == True def test_solve_sudanese_puzzle(): result = solv...
[ { "docstring": "Check if a 4x4 matrix is a magic square where each row, column, \nand 2x2 subsquare add up to 34 and contains all numbers from 1 to 16.", "function_declaration": "def is_magic_square(matrix):", "function_name": "is_magic_square", "parameter_list": "(matrix)" }, { "docstring":...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from itertools import permutations\n\ndef is_magic_square(square):\n \"\"\"\n Check if the given 4x4 square is a magic square where the sum of\n the numbers in each row, column, and 2...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00058116", "row_id": 58116, "seed_ids": "['Qwen2.5-72B-Instruct_117766']" }
0.469162
Filter_58116
I
[ "is_magic_square", "solve_sudanese_puzzle" ]
2
[ [ "solve_sudanese_puzzle", "is_magic_square" ] ]
1
[]
false
[]
false
pytest
true
[]
true
df32c0f12e46359576a9feb6f74d950baa3699a8
cd73f04b6e695a5f0caede07c0ee4f8ec38ef144
v1.0
instruct
Filter
Filter_58254_I
How would I simulate a simple double pendulum system in Python using the `scipy.integrate.solve_ivp` method? Please provide the code that sets up the initial conditions, equations of motion, and solves for the angles and angular velocities of the two bobs over time. Also, explain how to visualize the simulation results...
import numpy as np from scipy.integrate import solve_ivp import matplotlib.pyplot as plt def double_pendulum_derivs(t, state, l1, l2, m1, m2, g): theta1, z1, theta2, z2 = state c, s = np.cos(theta1 - theta2), np.sin(theta1 - theta2) theta1_dot = z1 z1_dot = (m2 * g * np.sin(theta2) * c - m2 * s * ...
import numpy as np from solution import double_pendulum_derivs, simulate_double_pendulum def test_double_pendulum_derivs(): l1, l2 = 1.0, 1.0 m1, m2 = 1.0, 1.0 g = 9.81 t = 0 state = [np.pi / 4, 0, np.pi / 4, 0] derivs = double_pendulum_derivs(t, state, l1, l2, m1, m2, g) assert len(derivs)...
[ { "docstring": null, "function_declaration": "def double_pendulum_derivs(t, state, l1, l2, m1, m2, g):", "function_name": "double_pendulum_derivs", "parameter_list": "(t, state, l1, l2, m1, m2, g)" }, { "docstring": null, "function_declaration": "def simulate_double_pendulum(t_max=10, dt...
[ 0, 0, 0, 1, 0, 0, 1, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom scipy.integrate import solve_ivp\nimport matplotlib.pyplot as plt\n\ndef double_pendulum_derivs(t, y, m1, m2, L1, L2, g):\n theta1, z1, theta2, z2 = y\n delta_th...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00058254", "row_id": 58254, "seed_ids": "['Qwen2.5-72B-Instruct_117995']" }
0.26994
Filter_58254
I
[ "double_pendulum_derivs", "simulate_double_pendulum", "plot_double_pendulum" ]
3
[ [ "simulate_double_pendulum", "double_pendulum_derivs" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "scipy" ]
false
48337176b7a38ac03f83bdc03724ce553d83f2a5
ddcd7c1a97d39f91779f6dd0474c9f8b7cc6ad88
v1.0
instruct
Filter
Filter_58348_I
Can you help me set up a timing script in Python that runs a function every hour and logs the output to a text file?
import time from datetime import datetime def function_to_run(): """ This is the function that will be run every hour. Replace the content of this function with the actual task you want to perform. """ return "Function executed successfully" def log_output_to_file(output): """ Logs the giv...
import pytest from solution import function_to_run, log_output_to_file from datetime import datetime import os def test_function_to_run(): assert function_to_run() == "Function executed successfully" def test_log_output_to_file(): output = "Test log entry" log_output_to_file(output) # Read the la...
[ { "docstring": "This is the function that will be run every hour.\nReplace the content of this function with the actual task you want to perform.", "function_declaration": "def function_to_run():", "function_name": "function_to_run", "parameter_list": "()" }, { "docstring": "Logs the given o...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\nimport logging\nfrom datetime import datetime\n\n# Set up logging configuration\nlogging.basicConfig(filename='function_output.log', level=logging.INFO)\n\ndef example_function():...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00058348", "row_id": 58348, "seed_ids": "['Qwen2.5-72B-Instruct_118188']" }
0.580256
Filter_58348
I
[ "function_to_run", "log_output_to_file", "run_every_hour" ]
3
[ [ "run_every_hour", "function_to_run" ], [ "run_every_hour", "log_output_to_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
6815c417a80de3d57f9a220e5e7474899bc409d8
534ee6c2910450fb5d33865552d51bdc4b528329
v1.0
instruct
Filter
Filter_58364_I
I need to create a simple web application using Flask, a micro web framework for Python. Can you guide me on how to set it up, especially focusing on user authentication and role-based access control?
from flask import Flask, request, jsonify, abort from functools import wraps app = Flask(__name__) # In-memory storage for simplicity users = { "user1": {"password": "password1", "role": "admin"}, "user2": {"password": "password2", "role": "user"} } # Decorator for authentication def authenticate(f): @wr...
import pytest from solution import app @pytest.fixture def client(): with app.test_client() as client: yield client def test_public_access(client): response = client.get('/public') assert response.status_code == 200 assert response.get_json() == {"message": "Welcome, public!"} def test_user_a...
[ { "docstring": null, "function_declaration": "def authenticate(f):", "function_name": "authenticate", "parameter_list": "(f)" }, { "docstring": null, "function_declaration": "def authorize(roles):", "function_name": "authorize", "parameter_list": "(roles)" }, { "docstring...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from flask import Flask, render_template, redirect, url_for, request, session\nfrom werkzeug.security import generate_password_hash, check_password_hash\n\napp = Flask(__name__)\napp.secret_ke...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00058364", "row_id": 58364, "seed_ids": "['Qwen2.5-72B-Instruct_118216']" }
0.418999
Filter_58364
I
[ "authenticate", "authorize", "verify_credentials", "admin", "user", "public" ]
6
[ [ "admin", "authorize" ], [ "authenticate", "verify_credentials" ], [ "user", "authorize" ] ]
3
[]
false
[]
false
pytest
true
[ "flask" ]
false
4fb483857f5a3bbade6b021fa5962ac374180110
2a9c160dbf41ac50915e7b00e0aa0956bb34f81d
v1.0
instruct
Filter
Filter_58424_I
I need help with a coding project. I want to create a simple web application using Flask that reads and analyzes file content. Can you guide me through the basic steps to set up this application?
from flask import Flask, request, render_template_string app = Flask(__name__) HTML_TEMPLATE = ''' <!doctype html> <title>Upload File</title> <h1>Upload a file and see the analysis results</h1> <form action="" method=post enctype=multipart/form-data> <input type=file name=file> <input type=submit value=Upload> </...
import pytest from io import BytesIO from solution import app, analyze_file # Helper function to simulate file upload def simulate_file_upload(client, file_content): data = { 'file': (BytesIO(file_content.encode('utf-8')), 'test.txt') } return client.post('/', data=data, content_type='multipart/for...
[ { "docstring": "Analyzes the content of the file.\nFor simplicity, we'll just count the number of lines in the file.", "function_declaration": "def analyze_file(file_content):", "function_name": "analyze_file", "parameter_list": "(file_content)" }, { "docstring": null, "function_declarat...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from flask import Flask, request, render_template, redirect, url_for\nimport os\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = './uploads'\n\nif not os.path.isdir(app.config['UPLOAD_F...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00058424", "row_id": 58424, "seed_ids": "['Qwen2.5-72B-Instruct_118325']" }
0.491866
Filter_58424
I
[ "analyze_file", "upload_file" ]
2
[ [ "upload_file", "analyze_file" ] ]
1
[]
false
[]
false
pytest
true
[ "flask" ]
false
a23b926d9fa49a68bbc5bac9653c17999c11c865
708185996d4bab9548b1f65135e05916eff3d029
v1.0
instruct
Filter
Filter_58548_I
Create a Python program that can encrypt and decrypt messages using the RSA algorithm. The program should allow the user to generate a public and private key pair, encrypt a message using the public key, and decrypt the message using the private key. Make sure to include comments in your code to explain each step. Also...
import random from sympy import isprime def gcd(a, b): """ Compute the greatest common divisor of a and b. """ while b: a, b = b, a % b return a def modinv(a, m): """ Compute the modular inverse of a under modulo m. """ m0, x0, x1 = m, 0, 1 if m == 1: return 0 ...
from solution import generate_keypair, encrypt, decrypt import pytest def test_generate_keypair(): public_key, private_key = generate_keypair(61, 53) assert len(public_key) == 2 assert len(private_key) == 2 assert public_key[1] == private_key[1] assert public_key[0] != private_key[0] def test_keyp...
[ { "docstring": "Compute the greatest common divisor of a and b.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Compute the modular inverse of a under modulo m.", "function_declaration": "def modinv(a, m):", "function_...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from Crypto.PublicKey import RSA\nfrom Crypto.Cipher import PKCS1_OAEP\nfrom Crypto.Random import get_random_bytes\nimport base64\n\ndef generate_keys():\n \"\"\"\n Generates a pair of R...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00058548", "row_id": 58548, "seed_ids": "['Qwen2.5-72B-Instruct_118544']" }
0.630105
Filter_58548
I
[ "gcd", "modinv", "generate_keypair", "encrypt", "decrypt" ]
5
[ [ "generate_keypair", "gcd" ], [ "generate_keypair", "modinv" ] ]
2
[]
false
[]
false
pytest
true
[ "sympy" ]
false
ad8c67eea05ad1c1d82f2151fedb1707829dc341
f7c85e3ee318062fada31d39ad2a160527eaf2bf
v1.0
instruct
Filter
Filter_58643_I
Design a Python function that dynamically generates SQL queries for updating a table. The function should take a list of columns to be updated, their corresponding new values, and additional conditions for the WHERE clause to uniquely identify the rows to be updated. The function should handle converting Python values ...
from datetime import date def sql_escape(value): """Escapes single quotes in a string for SQL.""" return value.replace("'", "''") def format_value(value): """Formats a Python value for use in an SQL query.""" if isinstance(value, str): return f"'{sql_escape(value)}'" elif isinstance(value,...
from datetime import date import pytest from solution import generate_update_query, sql_escape, format_value def test_sql_escape(): assert sql_escape("O'Reilly") == "O''Reilly" def test_format_value(): assert format_value("O'Reilly") == "'O''Reilly'" assert format_value(123) == "123" assert format...
[ { "docstring": "Escapes single quotes in a string for SQL.", "function_declaration": "def sql_escape(value):", "function_name": "sql_escape", "parameter_list": "(value)" }, { "docstring": "Formats a Python value for use in an SQL query.", "function_declaration": "def format_value(value):...
[ 0, 0, 0, 1, 0, 0, 1, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from datetime import datetime\n\ndef format_sql_value(value):\n \"\"\"\n Converts a Python value to a SQL-friendly string format, handling different data types accordingly.\n \"\"\"\n...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00058643", "row_id": 58643, "seed_ids": "['Qwen2.5-72B-Instruct_118718']" }
0.489137
Filter_58643
I
[ "sql_escape", "format_value", "generate_update_query" ]
3
[ [ "format_value", "sql_escape" ], [ "generate_update_query", "format_value" ] ]
2
[]
false
[]
false
pytest
true
[]
true
fdb7b715b85472e769b10250dc93bf0c04e015a1
a08d7395cdc4f1be6040d04721706cf69881dfc4
v1.0
instruct
Filter
Filter_58721_I
Develop a Python script that sends out emails to a list of recipients from a spreadsheet. The spreadsheet contains columns for the recipient's name, their email address, and a personalized message. The script should send a personalized email to each recipient and log the outcome of each email sent (e.g., success, failu...
import smtplib from email.mime.text import MIMEText import pandas as pd def send_email(recipient_email, recipient_name, message_body, smtp_server, smtp_port, smtp_user, smtp_password): subject = "Personalized Email" msg = MIMEText(message_body, 'plain') msg['Subject'] = subject msg['From'] = smtp_user...
import pytest from unittest.mock import patch, MagicMock from solution import send_emails_from_spreadsheet, send_email # Mock CSV data mock_data = pd.DataFrame({ 'Name': ['Test1', 'Test2'], 'Email': ['test1@example.com', 'test2@example.com'], 'Message': ['Hello Test1', 'Hello Test2'] }) def test_send_emai...
[ { "docstring": null, "function_declaration": "def send_email(recipient_email, recipient_name, message_body, smtp_server, smtp_port, smtp_user, smtp_password):", "function_name": "send_email", "parameter_list": "(recipient_email, recipient_name, message_body, smtp_server, smtp_port, smtp_user, smtp_p...
[ 0, 0, 0, 0, 0, 1, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\ndef send_email(recipient_name, recipient_email, personalized_messag...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00058721", "row_id": 58721, "seed_ids": "['Qwen2.5-72B-Instruct_118858']" }
0.527167
Filter_58721
I
[ "send_email", "send_emails_from_spreadsheet" ]
2
[ [ "send_emails_from_spreadsheet", "send_email" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas" ]
false
7ac5aa9001cfec378e50fbbff6b35f5fc649f6fb
90059596af6e0a7ed96a10f37c1f105e01198bcf
v1.0
instruct
Filter
Filter_58759_I
Make a python code for a simple blog post system. The posts are from markdown text and will be served in a minimal HTML page. The system should be able to list posts, read a post, and it should run locally.
from flask import Flask, render_template_string, request import os app = Flask(__name__) # Directory to store our markdown blog posts POSTS_DIR = 'posts' # Ensure the posts directory exists os.makedirs(POSTS_DIR, exist_ok=True) # Basic HTML template for displaying posts blog_template = """ <!DOCTYPE html> <html> <h...
import os import pytest from flask import Flask from flask.testing import FlaskClient from solution import app, POSTS_DIR, get_posts, read_post @pytest.fixture def client(): app.config['TESTING'] = True with app.test_client() as client: with app.app_context(): yield client def test_get_pos...
[ { "docstring": null, "function_declaration": "def get_posts():", "function_name": "get_posts", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def read_post(post_name):", "function_name": "read_post", "parameter_list": "(post_name)" }, { "docstring...
[ 0, 0, 0, 1, 0, 1, 1, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport markdown\nfrom flask import Flask, render_template_string, abort\n\napp = Flask(__name__)\n\nPOSTS_DIR = 'posts'\n\n# Helper function to get post titles\ndef get_post_titles(...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00058759", "row_id": 58759, "seed_ids": "['Qwen2.5-72B-Instruct_118930']" }
0.3914
Filter_58759
I
[ "get_posts", "read_post", "list_posts", "show_post" ]
4
[ [ "list_posts", "get_posts" ], [ "show_post", "read_post" ] ]
2
[]
false
[]
false
pytest
true
[ "flask" ]
false
f7e415df979853363e39066986748298c1b1cdcb
b86ff201449bc4ef4b9bdc3d53ea3127b96f68e9
v1.0
instruct
Filter
Filter_58793_I
Write a program to implement a simple chatbot that greets users, asks for their name, and then asks them about their day. The chatbot should then respond with a comment about their response. Use Python for the implementation.
def chatbot_greet(): """ Function to simulate a simple chatbot conversation. """ greeting = "Hello! How can I assist you today?" return greeting def chatbot_ask_name(): """ Function to ask for the user's name. """ name_request = "May I know your name?" return name_request def c...
from solution import chatbot_greet, chatbot_ask_name, chatbot_ask_day, chatbot_response_about_day, chatbot_conversation def test_chatbot_greet(): assert chatbot_greet() == "Hello! How can I assist you today?" def test_chatbot_ask_name(): assert chatbot_ask_name() == "May I know your name?" def test_chatbot_a...
[ { "docstring": "Function to simulate a simple chatbot conversation.", "function_declaration": "def chatbot_greet():", "function_name": "chatbot_greet", "parameter_list": "()" }, { "docstring": "Function to ask for the user's name.", "function_declaration": "def chatbot_ask_name():", ...
[ 0, 0, 0, 0, 1, 1, 1, 1, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def greet_user():\n \"\"\"\n Greets the user and asks for their name. Then asks about their day and responds with a comment\n \"\"\"\n greeting = \"Hello! What's your name?\"\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00058793", "row_id": 58793, "seed_ids": "['Qwen2.5-72B-Instruct_118984']" }
0.418493
Filter_58793
I
[ "chatbot_greet", "chatbot_ask_name", "chatbot_ask_day", "chatbot_response_about_day", "chatbot_conversation" ]
5
[ [ "chatbot_conversation", "chatbot_ask_day" ], [ "chatbot_conversation", "chatbot_ask_name" ], [ "chatbot_conversation", "chatbot_greet" ], [ "chatbot_conversation", "chatbot_response_about_day" ] ]
4
[]
false
[]
false
pytest
true
[]
true
2e8312f5394d6987d9c71af9df8ed866a3dc6eba
760e5f5b6e4c7e8d2dc43d056d3c47bbd27fb3f0
v1.0
instruct
Filter
Filter_58933_I
How do I add a watermark to a batch of images using Python?
from PIL import Image, ImageDraw, ImageFont def add_watermark(input_image_path, output_image_path, watermark_text, position=None): """ Adds a watermark to an image. :param input_image_path: str, path to the input image file :param output_image_path: str, path to save the watermarked image file :pa...
import os from PIL import Image from solution import add_watermark, add_watermark_batch def test_add_watermark(): # Create a simple image img = Image.new('RGB', (100, 100), color=(73, 109, 137)) img.save('test_image.jpg') add_watermark('test_image.jpg', 'test_watermarked.jpg', 'Test Watermark') ...
[ { "docstring": "Adds a watermark to an image.\n\n:param input_image_path: str, path to the input image file\n:param output_image_path: str, path to save the watermarked image file\n:param watermark_text: str, text to be added as watermark\n:param position: tuple, an optional (x, y) tuple to define the position ...
[ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from PIL import Image, ImageDraw, ImageFont\n\ndef add_watermark(input_images, watermark_text, output_folder, font_path='arial.ttf', font_size=30):\n \"\"\"\n Add given watermark text to...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00058933", "row_id": 58933, "seed_ids": "['Qwen2.5-72B-Instruct_119235']" }
0.400979
Filter_58933
I
[ "add_watermark", "add_watermark_batch" ]
2
[ [ "add_watermark_batch", "add_watermark" ] ]
1
[]
false
[]
false
pytest
true
[ "PIL" ]
false
c82741824e96f5d245404be5bd109465f085243b
00e074536e6702f902fa76617f6baa1838d8e9ab
v1.0
instruct
Filter
Filter_58992_I
Write a function in Python that can dynamically adjust the grid size on a scatter plot as you zoom in or out. This function should be designed as a callback function for a plot that is interactive, meaning as you change the view, the grid adjusts accordingly to stay useful and not clutter the plot.
import matplotlib.pyplot as plt import numpy as np def adjust_grid(event, ax, scatter): """ Adjusts the grid size on a scatter plot dynamically as you zoom in or out. Parameters: event : matplotlib event The zoom event object. ax : matplotlib axis The axis object of the scatter plo...
import matplotlib.pyplot as plt import numpy as np from solution import adjust_grid def test_adjust_grid_zoom_in(): fig, ax = plt.subplots() scatter = ax.scatter(np.random.randn(100), np.random.randn(100)) ax.set_xlim(-1, 1) ax.set_ylim(-1, 1) # Simulate zooming in event = type('test', (o...
[ { "docstring": "Adjusts the grid size on a scatter plot dynamically as you zoom in or out.\n\nParameters:\nevent : matplotlib event\n The zoom event object.\nax : matplotlib axis\n The axis object of the scatter plot.\nscatter : matplotlib scatter\n The scatter plot object.", "function_declaration"...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import matplotlib.pyplot as plt\nfrom matplotlib.ticker import AutoMinorLocator\nimport numpy as np\n\ndef adjust_grid(event):\n \"\"\"\n Adjusts the grid size on a scatter plot dynamica...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00058992", "row_id": 58992, "seed_ids": "['Qwen2.5-72B-Instruct_119352']" }
0.521134
Filter_58992
I
[ "adjust_grid", "plot_with_dynamic_grid" ]
2
[ [ "plot_with_dynamic_grid", "adjust_grid" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
af036d4396eab1f6c042a3f190ca05fc80af5e2c
c6292846a9216194a60a5a5b73ec43cb5ac3f7a4
v1.0
instruct
Filter
Filter_59055_I
Create a Python 3 script that checks the efficiency of various sorting algorithms (Bubble Sort, Quick Sort, Merge Sort, and Selection Sort) on two datasets: a random collection of 10,000 numbers and an already sorted collection of 10,000 numbers. The script should output the average time taken to sort the datasets over...
import time import random def bubble_sort(arr): """ Bubble Sort implementation. """ n = len(arr) for i in range(n): for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] def quick_sort(arr): """ Quick Sort implemen...
from solution import bubble_sort, quick_sort, merge_sort, selection_sort def test_bubble_sort(): arr = [3, 1, 2] bubble_sort(arr) assert arr == [1, 2, 3] def test_quick_sort(): arr = [3, 1, 2] sorted_arr = quick_sort(arr) assert sorted_arr == [1, 2, 3] def test_merge_sort(): arr = [3, 1, ...
[ { "docstring": "Bubble Sort implementation.", "function_declaration": "def bubble_sort(arr):", "function_name": "bubble_sort", "parameter_list": "(arr)" }, { "docstring": "Quick Sort implementation.", "function_declaration": "def quick_sort(arr):", "function_name": "quick_sort", ...
[ 0, 0, 0, 1, 1, 0, 1, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport time\n\ndef bubble_sort(arr):\n n = len(arr)\n for i in range(n):\n for j in range(0, n-i-1):\n if arr[j] > arr[j+1]:\n arr[j], arr...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00059055", "row_id": 59055, "seed_ids": "['Qwen2.5-72B-Instruct_119463']" }
0.524471
Filter_59055
I
[ "bubble_sort", "quick_sort", "merge_sort", "merge", "selection_sort", "measure_sorting_time", "main" ]
7
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
18d4907ca823bfd383a06e980cf40ec6abdf74ea
df837bdbca794eabad06d7cd3e34574faf700571
v1.0
instruct
Filter
Filter_59106_I
Can you write a program in Python that automatically sends out email reminders for due deadlines? The program should be able to read a list of deadlines from a file, compare the current date with the deadlines, and send an email if a deadline is due tomorrow. Assume the file format and email credentials are provided. P...
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from datetime import datetime, timedelta import csv def read_deadlines(file_path): """ Reads a list of deadlines from a CSV file. Expects the file to have columns: 'task', 'deadline_date' """ deadline...
from datetime import datetime, timedelta import tempfile import os from solution import read_deadlines, send_reminders def create_temp_csv(content): """ Creates a temporary CSV file for testing. """ temp_file = tempfile.NamedTemporaryFile(delete=False, mode='w+', newline='') header = ['task', 'dead...
[ { "docstring": "Reads a list of deadlines from a CSV file.\nExpects the file to have columns: 'task', 'deadline_date'", "function_declaration": "def read_deadlines(file_path):", "function_name": "read_deadlines", "parameter_list": "(file_path)" }, { "docstring": "Sends an email.", "funct...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom datetime import datetime, timedelta\nimport csv\n\ndef send_email(to_email, subject, ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00059106", "row_id": 59106, "seed_ids": "['Qwen2.5-72B-Instruct_119549']" }
0.443504
Filter_59106
I
[ "read_deadlines", "send_email", "send_reminders" ]
3
[ [ "send_reminders", "read_deadlines" ], [ "send_reminders", "send_email" ] ]
2
[]
false
[]
false
pytest
true
[]
true
413145b23f9d671fe65790fa6a09a446c206449d
53aac612b3ca0f3cc50e0fc8c35a31e85355a231
v1.0
instruct
Filter
Filter_59411_I
Write a Python script that calculates the square root of a given number using the Newton-Raphson method, and includes a function to test the accuracy of the result by comparing it to the math.sqrt() function from the Python standard library.
def newton_raphson_sqrt(n, tolerance=1e-7): """ Computes the square root of a number using Newton-Raphson method. :param n: A non-negative number to find the square root of. :param tolerance: Tolerance level to determine the accuracy of the result. :return: Approximated square root of the n...
import pytest from solution import newton_raphson_sqrt, compare_with_math_sqrt def test_newton_raphson_sqrt_positive_numbers(): assert abs(newton_raphson_sqrt(4) - 2) < 1e-7 assert abs(newton_raphson_sqrt(16) - 4) < 1e-7 assert abs(newton_raphson_sqrt(9) - 3) < 1e-7 assert abs(newton_raphson_sqrt(25) -...
[ { "docstring": "Computes the square root of a number using Newton-Raphson method.\n \n:param n: A non-negative number to find the square root of.\n:param tolerance: Tolerance level to determine the accuracy of the result.\n:return: Approximated square root of the number.", "function_declaration": "def ne...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef newton_raphson_sqrt(x, tolerance=1e-10, max_iterations=1000):\n \"\"\"\n Calculate the square root of a number using the Newton-Raphson method.\n :param x: The numb...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00059411", "row_id": 59411, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_120132']" }
0.584451
Filter_59411
I
[ "newton_raphson_sqrt", "compare_with_math_sqrt" ]
2
[ [ "compare_with_math_sqrt", "newton_raphson_sqrt" ] ]
1
[]
false
[]
false
pytest
true
[]
true
99b1326dfcbfc7afdbca92a8d7155eccf837b76a
ffd1831321fbeb280604235c9307b89a9c03ff72
v1.0
instruct
Filter
Filter_59563_I
Write a Python function that checks if a given string represents a valid IP address. The function should return `True` if the string is a valid IPv4 or IPv6 address, and `False` otherwise.
import re def is_valid_ipv4(ip): """ Check if the given IP is valid IPv4 address. """ pattern = re.compile(r'^(\d{1,3}\.){3}\d{1,3}$') if pattern.match(ip): parts = ip.split('.') if all(0 <= int(part) <= 255 for part in parts): return True return False def is_valid_...
from solution import is_valid_ip def test_valid_ipv4_addresses(): assert is_valid_ip("192.168.0.1") == True assert is_valid_ip("255.255.255.255") == True assert is_valid_ip("0.0.0.0") == True def test_invalid_ipv4_addresses(): assert is_valid_ip("256.256.256.256") == False assert is_valid_ip("192....
[ { "docstring": "Check if the given IP is valid IPv4 address.", "function_declaration": "def is_valid_ipv4(ip):", "function_name": "is_valid_ipv4", "parameter_list": "(ip)" }, { "docstring": "Check if the given IP is valid IPv6 address.", "function_declaration": "def is_valid_ipv6(ip):", ...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef is_valid_ip(ip):\n \"\"\"\n Returns True if the given string ip is a valid IPv4 or IPv6 address, False otherwise.\n \"\"\"\n # Regular expression for validating an...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00059563", "row_id": 59563, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_120439']" }
0.732327
Filter_59563
I
[ "is_valid_ipv4", "is_valid_ipv6", "is_valid_ip" ]
3
[ [ "is_valid_ip", "is_valid_ipv4" ], [ "is_valid_ip", "is_valid_ipv6" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2d558ede5de857fc70450320badb1a50230a82ab
530bda899e55fdd66aee35c4abf40f9ebc940800
v1.0
instruct
Filter
Filter_59577_I
How can I implement a simple chat application using Python and WebSocket?
import asyncio import websockets # List to keep track of connected clients clients = set() async def handler(websocket, path): # Add connecting client to clients list clients.add(websocket) try: async for message in websocket: # Broadcast message to all connected clients aw...
import asyncio import websockets import pytest # Import the solution module from solution import handler, clients @pytest.mark.asyncio async def test_client_connection(): uri = "ws://localhost:8765" async def client(uri): async with websockets.connect(uri) as websocket: await websocket.se...
[ { "docstring": null, "function_declaration": "def start_server():", "function_name": "start_server", "parameter_list": "()" } ]
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport websockets\n\nclients = set()\n\nasync def handler(websocket, path):\n # Register the client\n clients.add(websocket)\n try:\n async for message in webso...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00059577", "row_id": 59577, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_120464']" }
0.512644
Filter_59577
I
[ "handler", "start_server" ]
2
[ [ "start_server", "handler" ] ]
1
[]
false
[]
false
pytest
true
[ "websockets" ]
false
9bca2ba49ea9afaf2ff332f78673a924c16649cb
ba981d5a83806a2237af53b2f2d8ecf3b5da6251
v1.0
instruct
Filter
Filter_59808_I
Can you provide a Python implementation of the K-Nearest Neighbors (KNN) algorithm from scratch without using any external libraries?
import math from collections import Counter def euclidean_distance(point1, point2): """ Calculate the Euclidean distance between two points. Both points should be tuples of equal length. """ distance = 0 for i in range(len(point1)): distance += (point1[i] - point2[i]) ** 2 return ma...
from solution import euclidean_distance, knn_predict def test_euclidean_distance(): assert euclidean_distance((0,0), (3,4)) == 5.0 assert euclidean_distance((1,1), (4,5)) == 5.0 assert euclidean_distance((2,2), (5,6)) == 5.0 assert euclidean_distance((1,2), (1,2)) == 0.0 def test_knn_predict(): X_...
[]
[ 0, 0, 0, 0, 1, 1, 0, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom collections import Counter\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculated the Euclidean distance between two points.\n \"\"\"\n return math.sqrt...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00059808", "row_id": 59808, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_120935']" }
0.464171
Filter_59808
I
[ "euclidean_distance", "knn_predict" ]
2
[ [ "knn_predict", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
93565193cce9acb2ea8bf63a1e4beee05163bf9e
5cd729cd86311d9bf80c1e30c314c74f08dd6d48
v1.0
instruct
Filter
Filter_59976_I
Write a Python function that takes an integer as input and returns the smallest positive integer that has a larger Hamming distance with the input number than any other positive integer up to the input number. The Hamming distance between two integers is defined as the number of positions at which the corresponding bit...
def hamming_distance(x, y): """ Compute the Hamming distance between two integers. """ return bin(x ^ y).count('1') def max_hamming_distance(n): """ Returns the smallest positive integer that has the largest Hamming distance with the input number n. """ max_distance = -1 number_with...
from solution import max_hamming_distance, hamming_distance def test_hamming_distance(): assert hamming_distance(1, 4) == 2 # 0001 and 0100 assert hamming_distance(3, 8) == 3 # 0011 and 1000 assert hamming_distance(5, 9) == 2 # 0101 and 1001 assert hamming_distance(0, 0) == 0 # 0000 and 0000 def t...
[ { "docstring": "Compute the Hamming distance between two integers.", "function_declaration": "def hamming_distance(x, y):", "function_name": "hamming_distance", "parameter_list": "(x, y)" }, { "docstring": "Returns the smallest positive integer that has the largest Hamming distance with the ...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def max_hamming_distance_number(n):\n \"\"\"\n Returns the smallest positive integer that has the largest Hamming distance\n with the input number 'n' from all positive integers up to...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00059976", "row_id": 59976, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_121261']" }
0.811404
Filter_59976
I
[ "hamming_distance", "max_hamming_distance" ]
2
[ [ "max_hamming_distance", "hamming_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a8a7a1415af6cdebfa43216191ff581a19365ac4
8ba9f012bf1d9c3dc7bb5e1aa39ed105070e2a11
v1.0
instruct
Filter
Filter_60215_I
Can you provide a detailed explanation of how to implement a concave polygonal boundary using a quadtree spatial index for collision detection in a 2D game environment? Implementing this from scratch would be helpful.
class Quadtree: def __init__(self, boundary, capacity): self.boundary = boundary self.capacity = capacity self.points = [] self.divided = False def subdivide(self): x, y, w, h = self.boundary nw = (x, y, w/2, h/2) ne = (x + w/2, y, w/2, h/2) ...
from solution import Quadtree, point_in_polygon, collision_detection def test_quadtree_insert_and_contains(): qt = Quadtree((0, 0, 100, 100), 4) assert qt.insert((25, 25)) assert qt.insert((75, 75)) assert len(qt.points) == 2 def test_point_in_polygon(): poly = [(0, 0), (4, 0), (4, 4), (0, 4)]...
[]
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\nclass Boundary:\n def __init__(self, x, y, w, h):\n self.x = x\n self.y = y\n sel...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00060215", "row_id": 60215, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_121732']" }
0.406893
Filter_60215
I
[ "point_in_polygon", "collision_detection" ]
2
[ [ "collision_detection", "point_in_polygon" ] ]
1
[]
false
[ "Quadtree" ]
true
pytest
true
[]
true
9018103514063f2824627d6f1b9f84e26e3e78ed
de741491c8627f4b4a8ef6f433c4f12a4041df16
v1.0
instruct
Filter
Filter_60228_I
Can you provide a Python code snippet to perform integer factorization using the Pollard's rho algorithm?
import math import random def gcd(a, b): while b: a, b = b, a % b return a def pollards_rho(n): if n % 2 == 0: return 2 x = random.randint(2, n-1) y = x c = random.randint(1, n-1) g = 1 f = lambda x: (x*x + c) % n while g == 1: x = f(x) y = f(f(y)...
from solution import pollards_rho, integer_factorization, is_prime def test_pollards_rho_prime_factorization(): result = integer_factorization(10403) # 101 * 103 assert sorted(result) == [101, 103] def test_pollards_rho_single_value(): result = integer_factorization(101) # A prime number assert resu...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def pollards_rho(n):", "function_name": "pollards_rho", "parameter_list": "(n)" }, { "docstring": null, "...
[ 0, 0, 0, 1, 1, 0, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nimport random\n\ndef gcd(a, b):\n \"\"\"\n Compute the greatest common divisor of a and b.\n \"\"\"\n while b:\n a, b = b, a % b\n return a\n\ndef pollards_r...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00060228", "row_id": 60228, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_121765']" }
0.537602
Filter_60228
I
[ "gcd", "pollards_rho", "integer_factorization", "is_prime" ]
4
[ [ "integer_factorization", "is_prime" ], [ "integer_factorization", "pollards_rho" ], [ "pollards_rho", "gcd" ] ]
3
[]
false
[]
false
pytest
true
[]
true
991a36f81facc9c26148ae955eadae641ea7ee67
0327b29bfde3543a46a78884dd04acf434139131
v1.0
instruct
Filter
Filter_60313_I
How can I create a Python script that verifies a list of email addresses against a set of rules to ensure they are valid and properly formatted before sending an email campaign?
import re def is_valid_email(email): """ Verifies if the email address is valid based on a set of rules. Rules: 1. Email should not be empty or whitespace. 2. Email must have a proper format: local-part@domain. 3. Local part must be alphanumeric, allowing dots, underscores, and hyphens. 4. ...
from solution import is_valid_email, filter_valid_emails def test_is_valid_email(): assert is_valid_email("valid.email@example.com") assert is_valid_email("another.valid@example.co.uk") assert not is_valid_email("invalid-email.com") assert not is_valid_email("invalid-email@com") assert not is_valid...
[ { "docstring": "Verifies if the email address is valid based on a set of rules.\nRules:\n1. Email should not be empty or whitespace.\n2. Email must have a proper format: local-part@domain.\n3. Local part must be alphanumeric, allowing dots, underscores, and hyphens.\n4. Domain must have at least one dot, with d...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef validate_email(email):\n \"\"\"\n Validate the email address using regex to ensure it follows the correct format.\n \n Accepted format: username@domain.extension\n...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00060313", "row_id": 60313, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_121943']" }
0.520788
Filter_60313
I
[ "is_valid_email", "filter_valid_emails" ]
2
[ [ "filter_valid_emails", "is_valid_email" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c35491ae00519bf705fe0632ab2be0d126a7f34f
e2a75ef9f34257a25a1729ab3236a18e4858e409
v1.0
instruct
Filter
Filter_60427_I
How can I create a Python program that listens for mouse events in a GUI application using Sympy for any mathematical computation if needed?
import tkinter as tk from sympy import symbols, sin, cos def on_left_click(event): x, y = event.x, event.y x_sym, y_sym = symbols('x y') # Example computation: sine and cosine values based on x, y coordinates sin_val = sin(x) cos_val = cos(y) print(f"Mouse clicked at ({x}, {y})") ...
from sympy import sin, cos from solution import on_left_click def test_on_left_click_computations(monkeypatch): class Event: def __init__(self, x, y): self.x = x self.y = y # Mock the print function to capture output import builtins prints = [] def mock_print(*args)...
[ { "docstring": null, "function_declaration": "def on_left_click(event):", "function_name": "on_left_click", "parameter_list": "(event)" }, { "docstring": null, "function_declaration": "def create_gui():", "function_name": "create_gui", "parameter_list": "()" } ]
[ 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import tkinter as tk\nfrom sympy import symbols, sqrt\n\ndef on_click(event):\n \"\"\"\n Handles mouse click events, logs the coordinates,\n and computes the distance from the origin....
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00060427", "row_id": 60427, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_122175']" }
0.330158
Filter_60427
I
[ "on_left_click", "create_gui" ]
2
[ [ "create_gui", "on_left_click" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
206824ae8c32dfa2bdb775ecf5241d7a39b85b70
3ea008cdc7b4438cd06e6ce34fa904b3e2acbac9
v1.0
instruct
Filter
Filter_60431_I
How can I identify and list all the local web servers running on my network using Python?
import socket import concurrent.futures import requests def is_port_open(ip, port): """ Check if the port is open on the given IP address. """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.settimeout(1) try: s.connect((ip, port)) return True ...
def test_is_port_open(): assert not is_port_open("192.168.1.1", 9999) # Assuming port 9999 is not open assert isinstance(is_port_open("192.168.1.1", 80), bool) # Check if the function returns a boolean def test_check_for_web_server(): result = check_for_web_server("192.168.1.1") # This test result will ...
[ { "docstring": "Check if the port is open on the given IP address.", "function_declaration": "def is_port_open(ip, port):", "function_name": "is_port_open", "parameter_list": "(ip, port)" }, { "docstring": "Check if a web server is running on the given IP address (checking common ports 80 an...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl", "solution_code": "import socket\nfrom contextlib import closing\n\ndef is_port_open(ip, port):\n with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:\n soc...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00060431", "row_id": 60431, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_122180']" }
0.556064
Filter_60431
I
[ "is_port_open", "check_for_web_server", "list_local_web_servers" ]
3
[ [ "check_for_web_server", "is_port_open" ], [ "list_local_web_servers", "check_for_web_server" ] ]
2
[]
false
[]
false
pytest
false
[ "requests" ]
false
5feedb056f9a093b689a8cd68355f02bd1a16895
3eebf11723c9adafcf83ffdac240e8a3d884667d
v1.0
instruct
Filter
Filter_60457_I
I need to read a file that contains a list of names and their corresponding ages, but the file is encrypted using a simple Caesar cipher with a shift of 3. How can I decrypt the file and read the contents?
def decrypt_caesar_cipher(text, shift=3): """ Decrypts a Caesar cipher encrypted text. """ decrypted_text = [] for char in text: if char.isalpha(): shift_amount = 65 if char.isupper() else 97 decrypted_char = chr((ord(char) - shift_amount - shift) % 26 + shift_amount)...
from solution import decrypt_caesar_cipher, read_and_decrypt_file def test_decrypt_caesar_cipher(): assert decrypt_caesar_cipher('Khoor Zruog!', 3) == 'Hello World!' assert decrypt_caesar_cipher('d', 3) == 'a' assert decrypt_caesar_cipher('D', 3) == 'A' assert decrypt_caesar_cipher('Ebiil tloia!', 23) ...
[ { "docstring": "Decrypts a Caesar cipher encrypted text.", "function_declaration": "def decrypt_caesar_cipher(text, shift=3):", "function_name": "decrypt_caesar_cipher", "parameter_list": "(text, shift=3)" }, { "docstring": "Reads a file encrypted with a Caesar cipher and decrypts its conten...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def caesar_decrypt(text, shift):\n \"\"\"\n Decrypts text encrypted with the Caesar cipher with the given shift.\n \"\"\"\n decrypted_text = []\n for char in text:\n if c...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00060457", "row_id": 60457, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_122231']" }
0.421951
Filter_60457
I
[ "decrypt_caesar_cipher", "read_and_decrypt_file" ]
2
[ [ "read_and_decrypt_file", "decrypt_caesar_cipher" ] ]
1
[]
false
[]
false
pytest
true
[]
true
62d8de99dad17b7449f552034169811dc85327f6
01a847f3315a51dc979efca61dd0594c90a9bb54
v1.0
instruct
Filter
Filter_60754_I
I want to build a recommendation system for movies using collaborative filtering with Python. Can you guide me through the process?
import numpy as np import pandas as pd # Dummy data for demonstration # User-item ratings matrix data = { 'User': ['User1', 'User1', 'User1', 'User2', 'User2', 'User3', 'User3', 'User3', 'User4', 'User4'], 'Item': ['Item1', 'Item2', 'Item3', 'Item1', 'Item2', 'Item2', 'Item3', 'Item4', 'Item1', 'Item3'], '...
from solution import user_similarity, predict_ratings, recommend import pandas as pd # Dummy data for testing data = { 'User': ['User1', 'User1', 'User1', 'User2', 'User2', 'User3', 'User3', 'User3', 'User4', 'User4'], 'Item': ['Item1', 'Item2', 'Item3', 'Item1', 'Item2', 'Item2', 'Item3', 'Item4', 'Item1', 'I...
[ { "docstring": "Calculates and returns the user similarity matrix.", "function_declaration": "def user_similarity(matrix):", "function_name": "user_similarity", "parameter_list": "(matrix)" }, { "docstring": "Predicts the ratings for the user using the similarity matrix and returns the predi...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom scipy.spatial.distance import cosine\n\ndef load_ratings(file_path):\n \"\"\"\n Load the movie ratings data.\n \"\"\"\n return pd.read_csv(file_path)\n\nd...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00060754", "row_id": 60754, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_122823']" }
0.356785
Filter_60754
I
[ "user_similarity", "predict_ratings", "recommend" ]
3
[ [ "recommend", "predict_ratings" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "pandas" ]
false
478b9c793044457619480611ce4d3b6abfe3f878
7e35e872f05765a0351bc9f050eac1d0a314010e
v1.0
instruct
Filter
Filter_61154_I
How can I create a program in Python to draw a fractal tree using the L-system?
import turtle def generate_l_system(iterations, axiom, rules): """ Generate the L-System string after a given number of iterations. :param iterations: Number of iterations to apply the rules. :param axiom: The initial string. :param rules: A dictionary containing the transformation rules. :retu...
from solution import generate_l_system def test_generate_l_system_single_iteration(): axiom = "F" rules = {"F": "F+F"} assert generate_l_system(1, axiom, rules) == "F+F" def test_generate_l_system_multiple_iterations(): axiom = "F" rules = {"F": "F+F"} assert generate_l_system(2, axiom, rules)...
[ { "docstring": "Generate the L-System string after a given number of iterations.\n:param iterations: Number of iterations to apply the rules.\n:param axiom: The initial string.\n:param rules: A dictionary containing the transformation rules.\n:return: The final L-System string.", "function_declaration": "de...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import turtle\n\ndef draw_fractal_tree(axiom, rules, iterations, angle, length):\n \"\"\"\n Draw a fractal tree using the L-system.\n \n Args:\n axiom (str): The initial state o...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00061154", "row_id": 61154, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_123625']" }
0.359758
Filter_61154
I
[ "generate_l_system", "draw_l_system", "draw_fractal_tree" ]
3
[ [ "draw_fractal_tree", "draw_l_system" ], [ "draw_fractal_tree", "generate_l_system" ] ]
2
[]
false
[]
false
pytest
true
[]
true
16a543356cb0e2d4091da2b5aa700b9a8b2d6ed5
e9321e784d4ca05183ceb7e289826184b0d03337
v1.0
instruct
Filter
Filter_61263_I
How can I implement the A* algorithm for pathfinding in a grid-based environment using Python?
from queue import PriorityQueue def heuristic(a, b): """ Returns the Manhattan distance between point a and point b. """ return abs(a[0] - b[0]) + abs(a[1] - b[1]) def neighbors(node, grid): """ Returns the list of valid neighbors for the given node in the grid. """ dirs = [(0, 1), (1,...
from solution import a_star def test_a_star_simple_path(): grid = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] start = (0, 0) goal = (2, 2) expected_path = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)] assert a_star(grid, start, goal) == expected_path def test_a_star_with_obstacle():...
[ { "docstring": "Returns the Manhattan distance between point a and point b.", "function_declaration": "def heuristic(a, b):", "function_name": "heuristic", "parameter_list": "(a, b)" }, { "docstring": "Returns the list of valid neighbors for the given node in the grid.", "function_declar...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\n\ndef heuristic(a, b):\n return abs(a[0] - b[0]) + abs(a[1] - b[1])\n\ndef a_star(grid, start, goal):\n \"\"\"\n Implements the A* algorithm for pathfinding in a grid-ba...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00061263", "row_id": 61263, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_123850']" }
0.477595
Filter_61263
I
[ "heuristic", "neighbors", "a_star" ]
3
[ [ "a_star", "heuristic" ], [ "a_star", "neighbors" ] ]
2
[]
false
[]
false
pytest
true
[]
true
68aaad396e0a30479ae759857e41fe8d59fa2d74
d42549189c53b08ee6f18f6a0d2e10c4bc397f4f
v1.0
instruct
Filter
Filter_61347_I
I need help with creating a Python script that can send an email notification when a specific file is created in a directory. How can I achieve this?
import os import smtplib from time import sleep from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_email(subject, body, to_email): from_email = "your_email@example.com" password = "your_password" # Create the container email message. msg = MIMEMultipart() ...
import pytest import os from threading import Thread from time import sleep # Assuming the functions send_email and notify_on_file_creation were saved into solution.py from solution import notify_on_file_creation def test_notify_on_file_creation(monkeypatch): # Path setup test_dir = '/tmp/test_directory' ...
[ { "docstring": null, "function_declaration": "def send_email(subject, body, to_email):", "function_name": "send_email", "parameter_list": "(subject, body, to_email)" }, { "docstring": null, "function_declaration": "def notify_on_file_creation(directory, file_name, interval, to_email):", ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport time\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.application import MIMEApplication\n\ndef send_ema...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00061347", "row_id": 61347, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_124023']" }
0.486208
Filter_61347
I
[ "send_email", "notify_on_file_creation" ]
2
[ [ "notify_on_file_creation", "send_email" ] ]
1
[]
false
[]
false
pytest
true
[]
true
91d4d9dfc9be62befb1c2f0a3638bd06e47df472
00cb047b5998c7bf1a301b34c9df4809606a07a9
v1.0
instruct
Filter
Filter_61574_I
Can you provide a Python script to perform the divide and conquer algorithm to find the closest pair of points in a 2D plane?
import math # Define a Point class for convenience class Point: def __init__(self, x, y): self.x = x self.y = y def distance(p1, p2): """ Calculate the Euclidean distance between two points p1 and p2. """ return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2) def closest_pair_o...
from solution import find_closest_pair def test_find_closest_pair_basic(): points = [(0, 0), (1, 1), (2, 2)] assert math.isclose(find_closest_pair(points), math.sqrt(2)) def test_find_closest_pair_multiple_points(): points = [(0, 0), (5, 4), (3, 1), (12, 30), (4, 5), (2, 3)] assert math.isclose(find_c...
[]
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef dist(p1, p2):\n return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)\n\ndef brute_force(points):\n min_distance = float('inf')\n n = len(points)\n for i...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00061574", "row_id": 61574, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_124489']" }
0.54937
Filter_61574
I
[ "distance", "closest_pair_of_points", "find_closest_pair" ]
3
[ [ "closest_pair_of_points", "distance" ], [ "find_closest_pair", "closest_pair_of_points" ] ]
2
[]
false
[ "Point" ]
true
pytest
true
[]
true
3b78b7e9d281ab31a71ddb205831f36c5bd6223a
969ddd0336212163e8b177176dfbc82a274ef88d
v1.0
instruct
Filter
Filter_62075_I
How can I modify the code snippet to handle a specific case where the sum of the first and last elements in a list is a prime number? In this case, I want to perform a specific action, such as printing a message. How can I implement this check and action in my code?
def is_prime(n): """ Check if a number is prime. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False max_divisor = int(n ** 0.5) + 1 for d in range(3, max_divisor, 2): if n % d == 0: return False return True def ...
from solution import is_prime, check_sum_of_first_and_last_is_prime def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(17) == True assert is_prime(18) == False assert is_prime(1) == False assert is_prime(0) == False ass...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Check if the sum of the first and last elements in a list is a prime number.\nIf true, print a specific message.", "function_d...
[ 0, 0, 0, 0, 1, 1, 0, 1, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"\n Returns True if the number is prime, False otherwise.\n \"\"\"\n if num <= 1:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00062075", "row_id": 62075, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_125537']" }
0.528353
Filter_62075
I
[ "is_prime", "check_sum_of_first_and_last_is_prime" ]
2
[ [ "check_sum_of_first_and_last_is_prime", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
df091a33357a29c4db18247c02b297d0c88fe317
fc764cc55c30f6b54b91ed9d4db46ac01432a29c
v1.0
instruct
Filter
Filter_62110_I
How can I use Python to create a real-time data stream processing system that can handle high volumes of data and perform complex operations on the fly?
import datetime import random import time import threading import queue # Define a processing function that simulates complex operations def process_data(data): """ Simulate some complex data processing operation. """ # Add a delay to simulate time-consuming processing time.sleep(0.01) processe...
import queue import pytest import threading import time from solution import start_real_time_processing, stop_real_time_processing def test_data_streaming_and_processing(): stop_event = threading.Event() data_queue, processed_queue, streaming_thread, worker_thread = start_real_time_processing(stop_event) ...
[ { "docstring": "Simulate some complex data processing operation.", "function_declaration": "def process_data(data):", "function_name": "process_data", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def data_stream_generator(data_queue, stop_event):", "fun...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from pyspark import SparkConf, SparkContext\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\n\ndef process_stream(rdd):\n \"\"\"\n Process...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00062110", "row_id": 62110, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_125601']" }
0.369269
Filter_62110
I
[ "process_data", "data_stream_generator", "worker", "start_real_time_processing", "stop_real_time_processing" ]
5
[ [ "worker", "process_data" ] ]
1
[ "process_data" ]
false
[]
false
pytest
true
[]
true
77d5d5166d4320e1af2a2ef13e73e34505229c8b
c3f87a3bc80d19af6c72ed0a9569f7605c97205f
v1.0
instruct
Filter
Filter_62359_I
Can you generate a Python script that simulates a simple stock trading bot? This bot should be able to buy and sell stocks based on a simple moving average crossover strategy. The script should include functions for generating random stock prices, checking the moving averages, and executing trades. The goal is to buy w...
import numpy as np import random def generate_random_stock_prices(num_days, start_price=100): """ Generates random stock prices for a given number of days. """ prices = [start_price] for _ in range(1, num_days): change_percent = random.uniform(-2.0, 2.0) new_price = prices[-1] * (1 ...
from solution import generate_random_stock_prices, moving_average, simulate_trading def test_generate_random_stock_prices(): prices = generate_random_stock_prices(10) assert len(prices) == 10 assert all(isinstance(price, (int, float)) for price in prices) def test_moving_average(): prices = [1, 2, 3, ...
[ { "docstring": "Generates random stock prices for a given number of days.", "function_declaration": "def generate_random_stock_prices(num_days, start_price=100):", "function_name": "generate_random_stock_prices", "parameter_list": "(num_days, start_price=100)" }, { "docstring": "Calculates t...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom collections import deque\n\ndef generate_random_stock_prices(length, start_price=100):\n \"\"\"\n Generates a list of random stock prices.\n \"\"\"\n prices = [...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00062359", "row_id": 62359, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_126125']" }
0.421993
Filter_62359
I
[ "generate_random_stock_prices", "moving_average", "simulate_trading" ]
3
[ [ "simulate_trading", "moving_average" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
92c19017533a87c12d7c677b69a45903da7037dc
3d5fac78e8a17101d93e1bf8334668e5415fa679
v1.0
instruct
Filter
Filter_62701_I
Can you help me implement A* search algorithm in Python for a grid-based pathfinding problem?
import heapq def heuristic(a, b): """ Calculate the heuristic, here we'll use Manhattan distance which is suitable for a grid-based pathfinding problem. """ (x1, y1) = a (x2, y2) = b return abs(x1 - x2) + abs(y1 - y2) def a_star_search(grid, start, goal): """ Perform A* search on a...
from solution import a_star_search def test_empty_grid_pathfinding(): grid = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] start = (0, 0) goal = (2, 2) expected_path = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)] assert a_star_search(grid, start, goal) == expected_path def test_grid_...
[ { "docstring": "Calculate the heuristic, here we'll use Manhattan distance\nwhich is suitable for a grid-based pathfinding problem.", "function_declaration": "def heuristic(a, b):", "function_name": "heuristic", "parameter_list": "(a, b)" }, { "docstring": "Perform A* search on a grid.\n:par...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\n\ndef heuristic(a, b):\n return abs(b[0] - a[0]) + abs(b[1] - a[1])\n\ndef astar(grid, start, goal):\n \"\"\"\n A* pathfinding algorithm on a grid.\n \n :param grid:...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00062701", "row_id": 62701, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_126815']" }
0.519799
Filter_62701
I
[ "heuristic", "a_star_search" ]
2
[ [ "a_star_search", "heuristic" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7a6d37df0d1a61bc32f120999fbc7160a82b0f44
e516eca1c00f9012179c8b809d627c90d40e52c6
v1.0
instruct
Filter
Filter_62753_I
Can you provide a Python code snippet to solve the Traveling Salesman Problem (TSP) using a genetic algorithm?
import random import numpy as np def distance_matrix(cities): """Creates a distance matrix.""" n = len(cities) dist_matrix = np.zeros((n, n)) for i in range(n): for j in range(i + 1, n): dist_matrix[i, j] = dist_matrix[j, i] = np.linalg.norm(np.array(cities[i]) - np.array(cities[j])...
from solution import distance_matrix, create_individual, create_population, calculate_fitness, select_parents, crossover, mutate, genetic_algorithm def test_distance_matrix(): cities = [(0, 0), (1, 1), (2, 2)] dist_matrix = distance_matrix(cities) assert np.allclose(dist_matrix, [ [0, np.sqrt(2), n...
[ { "docstring": "Creates a distance matrix.", "function_declaration": "def distance_matrix(cities):", "function_name": "distance_matrix", "parameter_list": "(cities)" }, { "docstring": "Creates an individual for the population.", "function_declaration": "def create_individual(cities):", ...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl", "solution_code": "import random\nimport numpy as np\n\nclass TSPGeneticAlgorithm:\n def __init__(self, dist_matrix, population_size, generations, mutation_rate):\n self.dist_m...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00062753", "row_id": 62753, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_126912']" }
0.358114
Filter_62753
I
[ "distance_matrix", "create_individual", "create_population", "calculate_fitness", "select_parents", "crossover", "mutate", "genetic_algorithm" ]
8
[ [ "create_population", "create_individual" ], [ "genetic_algorithm", "calculate_fitness" ], [ "genetic_algorithm", "create_population" ], [ "genetic_algorithm", "crossover" ], [ "genetic_algorithm", "distance_matrix" ], [ "genetic_algorithm", "muta...
8
[]
false
[]
false
pytest
true
[ "numpy" ]
false
d71f9ab1c46b81c84f1e4d531813a55015de2123
1d3ed3b72a221fb535fae99b7a2b132502964ad0
v1.0
instruct
Filter
Filter_62848_I
Could you provide a detailed explanation of how to implement the K-Means clustering algorithm from scratch in Python? Certainly! Below is a step-by-step guide to implementing the K-Means clustering algorithm manually in Python. This explanation includes the necessary steps, code snippets, and the logic behind each step...
import numpy as np def initialize_centroids(X, k): """ Randomly initialize the centroids. Parameters: X (ndarray): The input data. k (int): The number of clusters. Returns: ndarray: Initial centroids. """ indices = np.random.choice(X.shape[0], k, replace=False) centroi...
import numpy as np from solution import initialize_centroids, assign_clusters, update_centroids, kmeans def test_initialize_centroids(): X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) k = 2 centroids = initialize_centroids(X, k) assert centroids.shape == (k, X.shape[1]) def test_assign_clusters(): ...
[ { "docstring": "Randomly initialize the centroids.\n\nParameters:\nX (ndarray): The input data.\nk (int): The number of clusters.\n\nReturns:\nndarray: Initial centroids.", "function_declaration": "def initialize_centroids(X, k):", "function_name": "initialize_centroids", "parameter_list": "(X, k)" ...
[ 0, 0, 0, 1, 1, 1, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef initialize_centroids(X, k):\n \"\"\"\n Randomly choose k unique data points from X as the initial centroids.\n \"\"\"\n n_samples, n_features = X.shape\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00062848", "row_id": 62848, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_127103']" }
0.6072
Filter_62848
I
[ "initialize_centroids", "assign_clusters", "update_centroids", "kmeans" ]
4
[ [ "kmeans", "assign_clusters" ], [ "kmeans", "initialize_centroids" ], [ "kmeans", "update_centroids" ] ]
3
[]
false
[]
false
pytest
true
[ "numpy" ]
false
c54363b69514ad18c296f807472d119904ba6177
be4ed4a51c8581c67b4e0b5ffabaa1773c2713dd
v1.0
instruct
Filter
Filter_63412_I
How can I train a Transformer model for text classification using Python and PyTorch?
import torch from torch.utils.data import DataLoader, Dataset from transformers import BertTokenizer, BertForSequenceClassification, AdamW from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score class TextDataset(Dataset): def __init__(self, texts, labels, tokenizer, max_len...
def test_text_dataset(): tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') texts = ["Hello world!", "PyTorch is great!"] labels = [0, 1] dataset = TextDataset(texts, labels, tokenizer, max_len=10) item = dataset[0] assert 'input_ids' in item assert 'attention_mask' in item ...
[]
[ 0, 0, 0, 1, 1, 0, 0, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nfrom transformers import BertTokenizer, BertForSequenceClassification\n\nclass TextClassifier:\n def __init__(self, model_name='bert-base-uncased', num_...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00063412", "row_id": 63412, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_128301']" }
0.455856
Filter_63412
I
[ "create_data_loader", "train_model" ]
2
[ [ "train_model", "create_data_loader" ] ]
1
[]
false
[ "TextDataset" ]
true
pytest
false
[ "sklearn", "torch", "transformers" ]
false
7ff95a8d859e95612ce5a1f3c0c1a017aacb1d59
3da76d21687d23d27e0dbc25847aff88cdde7706
v1.0
instruct
Filter
Filter_63507_I
Write a Python program for the game of Nim. The game is played by two players who take turns removing 1, 2, or 3 stones from a pile of n stones. The player who removes the last stone wins. The program should start with 15 stones and allow the user to choose how many stones to remove on their turn. The computer should p...
def player_turn(pile): """ This function handles the player's turn. It returns the number of stones the player will remove from the pile. """ while True: try: stones = int(input(f"There are {pile} stones left. How many would you like to remove (1, 2, or 3)? ")) if sto...
from solution import player_turn, computer_turn def test_player_turn(monkeypatch): monkeypatch.setattr('builtins.input', lambda _: "3") assert player_turn(15) == 3 monkeypatch.setattr('builtins.input', lambda _: "2") assert player_turn(14) == 2 monkeypatch.setattr('builtins.input', lambda _: "1")...
[ { "docstring": "This function handles the player's turn.\nIt returns the number of stones the player will remove from the pile.", "function_declaration": "def player_turn(pile):", "function_name": "player_turn", "parameter_list": "(pile)" }, { "docstring": "This function handles the computer...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def nim_game(human_moves):\n \"\"\"\n Simulates the game of Nim for human and computer.\n\n :param human_moves: List of integers indicating the human moves. Each integer is either 1, ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00063507", "row_id": 63507, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_128496']" }
0.721627
Filter_63507
I
[ "player_turn", "computer_turn", "play_nim" ]
3
[ [ "play_nim", "computer_turn" ], [ "play_nim", "player_turn" ] ]
2
[]
false
[]
false
pytest
true
[]
true
634bf2699b0b19f2798b30a2771c5dd3a20d24a0
1f54d364a1decb228a2ad6964684818a7ca760a2
v1.0
instruct
Filter
Filter_63522_I
Develop a Python script to calculate the total cost of groceries. The script should allow for user input of item names, prices, and quantities. It should also include a function to calculate the total cost and print a receipt. The script should be flexible to handle any number of items.
def calculate_total_cost(item_details): """ Calculate the total cost of items. Parameters: item_details (list of tuple): A list where each tuple contains (item_name, price, quantity) Returns: float: Total cost of all items. """ total_cost = 0 for item in item_details: ...
from solution import calculate_total_cost, print_receipt def test_calculate_total_cost(): assert calculate_total_cost([]) == 0 assert calculate_total_cost([("Apple", 1.0, 5)]) == 5.0 assert calculate_total_cost([("Apple", 1.0, 5), ("Banana", 0.5, 10)]) == 10.0 assert calculate_total_cost([("Apple", 1.0...
[ { "docstring": "Calculate the total cost of items.\n\nParameters:\nitem_details (list of tuple): A list where each tuple contains (item_name, price, quantity)\n\nReturns:\nfloat: Total cost of all items.", "function_declaration": "def calculate_total_cost(item_details):", "function_name": "calculate_tot...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_total_cost(items):\n \"\"\"\n Given a list of items where each item is a dictionary with 'name', 'price', and 'quantity',\n this function returns the total cost of the g...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00063522", "row_id": 63522, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_128536']" }
0.461405
Filter_63522
I
[ "calculate_total_cost", "print_receipt" ]
2
[ [ "print_receipt", "calculate_total_cost" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d19b48fc0faa1f4d1b2a116e7dfe093525704c54
e1366940147e7cf147bedc43c98a6db598cc0279
v1.0
instruct
Filter
Filter_63753_I
Can you explain how to implement a simple Face Recognition System using OpenCV in Python?
import cv2 import numpy as np def load_and_preprocess_image(image_path): """ Loads an image from the filesystem and converts it to grayscale. Parameters: image_path (str): The path to the image file. Returns: np.ndarray: The grayscale image. """ image = cv2.imread(image_path) ...
import pytest import cv2 from solution import load_and_preprocess_image, detect_faces, draw_faces, face_recognition def test_load_and_preprocess_image(): try: gray_image = load_and_preprocess_image('test_image.jpg') assert gray_image is not None assert len(gray_image.shape) == 2 # Should b...
[ { "docstring": "Loads an image from the filesystem and converts it to grayscale.\n\nParameters:\nimage_path (str): The path to the image file.\n\nReturns:\nnp.ndarray: The grayscale image.", "function_declaration": "def load_and_preprocess_image(image_path):", "function_name": "load_and_preprocess_image...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cv2\nimport os\n\ndef detect_faces(image_path, haar_cascade_path):\n \"\"\"\n Detects faces in an image using Haar Cascade Classifier.\n \n :param image_path: Path to the im...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00063753", "row_id": 63753, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129019']" }
0.434146
Filter_63753
I
[ "load_and_preprocess_image", "detect_faces", "draw_faces", "face_recognition" ]
4
[ [ "face_recognition", "detect_faces" ], [ "face_recognition", "draw_faces" ], [ "face_recognition", "load_and_preprocess_image" ] ]
3
[]
false
[]
false
pytest
true
[ "cv2", "numpy" ]
false
d9cd6f2c084f07781f050f78bdf7298479dc067c
f86dda72449e2eb3de3d4a4be8ec44e2a4091928
v1.0
instruct
Filter
Filter_63843_I
Write a Python function to calculate the sum of all the prime numbers within a given range, including the start and end values if they are prime. The function should be named `sum_of_primes` and take two arguments, `start` and `end`. It should return the sum of all prime numbers between `start` and `end` inclusive.
def is_prime(n): """ Helper function to check if a number is a prime. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True def sum_of_prim...
from solution import sum_of_primes def test_sum_of_primes_basic(): assert sum_of_primes(1, 10) == 17 # primes: 2, 3, 5, 7 assert sum_of_primes(10, 20) == 60 # primes: 11, 13, 17, 19 def test_sum_of_primes_single_prime(): assert sum_of_primes(2, 2) == 2 # single prime: 2 assert sum_of_primes(19, 19)...
[ { "docstring": "Helper function to check if a number is a prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Calculate the sum of all prime numbers in the given range inclusive", "function_declaration": "def sum_of...
[ 0, 0, 0, 0, 1, 0, 0, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00063843", "row_id": 63843, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129182']" }
0.620868
Filter_63843
I
[ "is_prime", "sum_of_primes" ]
2
[ [ "sum_of_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d3020920ccf1c85caad43514bc10d896b94061f6
24e367a5689d14fa06ce164a6a4a483c0dc02551