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_63935_I | I'm working on a chatbot using Python. I want to implement a feature that allows the chatbot to respond to a user's input with a personalized greeting based on their name. How can I achieve this in Python? Implementing this requires extracting the user's name from the input and then using it to form a personalized resp... | import re
def get_name_from_input(user_input):
"""
Extracts the name from the user's input.
Assumes the input format is 'My name is <name>' where <name> can be any word after 'My name is '.
"""
match = re.search(r'My name is (\w+)', user_input)
if match:
return match.group(1)
return... | from solution import get_name_from_input, personalized_greeting
def test_get_name_from_input():
assert get_name_from_input('My name is Alice') == 'Alice'
assert get_name_from_input('My name is Bob') == 'Bob'
assert get_name_from_input('My name is Charlie') == 'Charlie'
assert get_name_from_input('This ... | [
{
"docstring": "Extracts the name from the user's input.\nAssumes the input format is 'My name is <name>' where <name> can be any word after 'My name is '.",
"function_declaration": "def get_name_from_input(user_input):",
"function_name": "get_name_from_input",
"parameter_list": "(user_input)"
},
... | [
0,
0,
0,
1,
1,
1,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef extract_name_and_greet(input_string):\n \"\"\"\n Extracts the user's name from the input string and returns a personalized greeting.\n \n Parameters:\n inpu... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00063935",
"row_id": 63935,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_129351']"
} | 0.382437 | Filter_63935 | I | [
"get_name_from_input",
"personalized_greeting"
] | 2 | [
[
"personalized_greeting",
"get_name_from_input"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c06afc943d15de5ac5d1312685e153826ae8c8de | 1dbf2bbc5f0bc3de7b452f42bb1cfa0649406a7f | |||
v1.0 | instruct | Filter | Filter_64124_I | Can you provide a Python implementation of a simple genetic algorithm for solving the knapsack problem? | import random
def knapsack_value(weights, values, solution, capacity):
"""
Calculate the value of the knapsack for the given solution.
"""
total_weight = sum(w * s for w, s in zip(weights, solution))
total_value = sum(v * s for v, s in zip(values, solution))
if total_weight > capacity:
... | from solution import knapsack_value, genetic_algorithm_knapsack, create_individual
def test_knapsack_value():
weights = [10, 20, 30]
values = [60, 100, 120]
solution = [1, 1, 0]
capacity = 50
assert knapsack_value(weights, values, solution, capacity) == 160
def test_knapsack_value_exceeding_capaci... | [
{
"docstring": "Calculate the value of the knapsack for the given solution.",
"function_declaration": "def knapsack_value(weights, values, solution, capacity):",
"function_name": "knapsack_value",
"parameter_list": "(weights, values, solution, capacity)"
},
{
"docstring": "Create a random in... | [
0,
0,
0,
0,
0,
0,
1,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nclass Individual:\n def __init__(self, chromosome, fitness=0):\n self.chromosome = chromosome\n self.fitness = fitness\n\ndef initialize_population(pop_size, ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00064124",
"row_id": 64124,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_129765']"
} | 0.404215 | Filter_64124 | I | [
"knapsack_value",
"create_individual",
"selection",
"crossover",
"mutate",
"genetic_algorithm_knapsack"
] | 6 | [
[
"genetic_algorithm_knapsack",
"create_individual"
],
[
"genetic_algorithm_knapsack",
"crossover"
],
[
"genetic_algorithm_knapsack",
"knapsack_value"
],
[
"genetic_algorithm_knapsack",
"mutate"
],
[
"genetic_algorithm_knapsack",
"selection"
],
[
"sele... | 6 | [] | false | [] | false | pytest | true | [] | true | 6df9ca48471c3c3b5a148e0e06f13f5516260b15 | d84d9e607bbd7870227b06a9ff9a4bd035fd971e | |||
v1.0 | instruct | Filter | Filter_64165_I | Write a Python function that checks if the length of a given string is a prime number. The function should return `True` if the string length is prime, and `False` otherwise. | def is_prime(n):
"""
Helper function to check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i +... | from solution import is_length_prime
def test_is_length_prime_with_prime_length_strings():
assert is_length_prime("abc") == True # Length is 3, which is prime
assert is_length_prime("abcdefg") == True # Length is 7, which is prime
def test_is_length_prime_with_non_prime_length_strings():
assert is_lengt... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Checks if the length of the given string is a prime number.",
"function_declaration": "def is_length_prime(... | [
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 is_prime(n):\n \"\"\"\n Returns True if n is a prime number, otherwise returns False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00064165",
"row_id": 64165,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_129851']"
} | 0.928155 | Filter_64165 | I | [
"is_prime",
"is_length_prime"
] | 2 | [
[
"is_length_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0aaf7d572602adf2b7ec1fe549258d36e54a1da3 | 4b34a7976966b66ab836cffbfe9c35143d747cb7 | |||
v1.0 | instruct | Filter | Filter_64546_I | Generate a Python function that calculates the Moving Average Convergence Divergence (MACD) and the Exponential Moving Averages (EMA) for a given list of stock prices. The function should take a list of closing prices and return the MACD line, signal line, and histogram as well as the short-term and long-term EMAs. | def calculate_ema(prices, days):
"""
Calculate the Exponential Moving Average (EMA) for a given list of prices and period.
"""
ema = []
k = 2 / (days + 1)
# Start EMA with the first price
ema.append(prices[0])
for price in prices[1:]:
ema.append(price * k + ema[-1] * (1 - k))
... | from solution import calculate_ema, calculate_macd
def test_calculate_ema():
prices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ema = calculate_ema(prices, 3)
assert len(ema) == 10
# Check EMA smoothing works - this is a rough approximation test
assert ema[-1] > ema[-2] > ema[-3]
def test_calculate_macd():
... | [
{
"docstring": "Calculate the Exponential Moving Average (EMA) for a given list of prices and period.",
"function_declaration": "def calculate_ema(prices, days):",
"function_name": "calculate_ema",
"parameter_list": "(prices, days)"
},
{
"docstring": "Calculate the Moving Average Convergence... | [
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 numpy as np\n\ndef calculate_ema(prices, period):\n \"\"\"\n Calculate the Exponential Moving Average (EMA) for a given list of prices.\n \"\"\"\n ema = [np.mean(prices[:per... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00064546",
"row_id": 64546,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_130671']"
} | 0.550771 | Filter_64546 | I | [
"calculate_ema",
"calculate_macd"
] | 2 | [
[
"calculate_macd",
"calculate_ema"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 86d4c2b043d336d2bf33831d299f669f1c3fcaa9 | 7778fa01dcc4c762de976775a91172a082ee3017 | |||
v1.0 | instruct | Filter | Filter_64696_I | I need to create a Python program that checks the spelling of words in a text file and suggests corrections if any spelling mistakes are found. How can I accomplish this? | import difflib
def read_words_from_file(filename):
with open(filename, 'r') as file:
text = file.read()
return text.split()
def check_spelling(word, dictionary):
if word.lower() in dictionary:
return (word, None)
else:
# Find closest matches
suggestions = difflib.get_cl... | from solution import read_words_from_file, check_spelling, check_spelling_in_file
def test_read_words_from_file(tmp_path):
d = tmp_path / "sub"
d.mkdir()
file = d / "testfile.txt"
file.write_text("Hello world")
assert read_words_from_file(str(file)) == ["Hello", "world"]
def test_check_spelli... | [
{
"docstring": null,
"function_declaration": "def read_words_from_file(filename):",
"function_name": "read_words_from_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def check_spelling(word, dictionary):",
"function_name": "check_spelling",
... | [
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 difflib\n\nclass SpellChecker:\n def __init__(self, dictionary_file):\n with open(dictionary_file, 'r') as file:\n self.words = set(word.strip().lower() for word in... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00064696",
"row_id": 64696,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_130979']"
} | 0.495627 | Filter_64696 | I | [
"read_words_from_file",
"check_spelling",
"check_spelling_in_file"
] | 3 | [
[
"check_spelling_in_file",
"check_spelling"
],
[
"check_spelling_in_file",
"read_words_from_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4fc85e148fa21651b07eda49896a89fe849a1585 | 156287b8ae1387dc9a15a28cea1137f6414adb3d | |||
v1.0 | instruct | Filter | Filter_64937_I | Write a Python function to find the maximum depth, the minimum depth, and the average depth of a binary tree. The depth of a node is defined as the number of edges on the longest path from the root node to the leaf. The maximum depth is the number of nodes along the longest path from the root node down to the farthest ... | class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def max_depth(root):
if root is None:
return 0
else:
left_depth = max_depth(root.left)
right_depth = max_depth(root.right)
retur... | from solution import TreeNode, max_depth, min_depth, average_depth
def test_max_depth():
# Test case 1
tree = TreeNode(1, TreeNode(2), TreeNode(3))
assert max_depth(tree) == 2
# Test case 2
tree = None
assert max_depth(tree) == 0
# Test case 3
tree = TreeNode(1, TreeNode(2, TreeNode(3... | [] | [
0,
0,
0,
0,
1,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef max_depth(root):\n if not root:\n... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00064937",
"row_id": 64937,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_131469']"
} | 0.578574 | Filter_64937 | I | [
"max_depth",
"min_depth",
"sum_and_count_depths",
"average_depth"
] | 4 | [
[
"average_depth",
"sum_and_count_depths"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | f88d8dea7bd873343e948233522b8019a65dbb60 | 261892d8dc32f8dcde7f4b9a53b6ebb7441db41a | |||
v1.0 | instruct | Filter | Filter_64961_I | Write a Python function that calculates the score of a bowling game. The game consists of 10 frames, each frame allowing up to two rolls. If a player knocks down all 10 pins in the first roll of a frame, it's a strike, and the player scores 10 plus the points of the next two rolls. If a player knocks down all 10 pins i... | def calculate_bowling_score(rolls):
"""
Calculates the score of a bowling game.
Parameters:
rolls (list): List of integers representing the pins knocked down in each roll.
Returns:
int: The total score of the game.
"""
score = 0
frame_index = 0
for frame in range(10):
... | from solution import calculate_bowling_score, is_strike, is_spare
def test_perfect_game():
rolls = [10] * 12
assert calculate_bowling_score(rolls) == 300
def test_all_spares():
rolls = [5, 5] * 10 + [5]
assert calculate_bowling_score(rolls) == 150
def test_no_strikes_or_spares():
rolls = [9, 0] *... | [
{
"docstring": "Calculates the score of a bowling game.\n\nParameters:\nrolls (list): List of integers representing the pins knocked down in each roll.\n\nReturns:\nint: The total score of the game.",
"function_declaration": "def calculate_bowling_score(rolls):",
"function_name": "calculate_bowling_scor... | [
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": "def calculate_bowling_score(rolls):\n \"\"\"\n Calculate the total score of a bowling game given a list of pins knocked down in each roll.\n \"\"\"\n total_score = 0\n roll_inde... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00064961",
"row_id": 64961,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_131530']"
} | 0.573943 | Filter_64961 | I | [
"calculate_bowling_score",
"is_strike",
"is_spare"
] | 3 | [
[
"calculate_bowling_score",
"is_spare"
],
[
"calculate_bowling_score",
"is_strike"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 976de9b724838a6f8133880e25acb5b16570145a | 4e1e14058c10cd706244b1bb256bc9b719cd1d0e | |||
v1.0 | instruct | Filter | Filter_65243_I | How can I create a Python script that logs user activity on a web application when a specific page is accessed? | import logging
from flask import Flask, request
app = Flask(__name__)
# Configure logging
logging.basicConfig(filename='user_activity.log', level=logging.INFO,
format='%(asctime)s - %(message)s')
def log_user_activity(page):
"""
Logs user activity including IP address and accessed page.
... | import pytest
from flask import Flask, request
from solution import app, log_user_activity
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_log_user_activity(client, caplog):
caplog.set_level(logging.INFO)
# Mimic the request to a specific page
respons... | [
{
"docstring": "Logs user activity including IP address and accessed page.",
"function_declaration": "def log_user_activity(page):",
"function_name": "log_user_activity",
"parameter_list": "(page)"
},
{
"docstring": null,
"function_declaration": "def specific_page():",
"function_name... | [
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": "from flask import Flask, request\nimport logging\n\napp = Flask(__name__)\n\n# Configure logging\nlogging.basicConfig(filename='user_activity.log', level=logging.INFO, \n fo... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00065243",
"row_id": 65243,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_132133']"
} | 0.469226 | Filter_65243 | I | [
"log_user_activity",
"specific_page"
] | 2 | [
[
"specific_page",
"log_user_activity"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | e726572751cde163da9f0a726ac8e3166bdf680a | 1b29569cc61db9f76f1751e7d8bef5b5c8259c8d | |||
v1.0 | instruct | Filter | Filter_65353_I | Hello Qwen, could you provide a Python script to create a simple web application that allows users to upload and download files using Flask? | from flask import Flask, request, redirect, url_for, send_from_directory, render_template
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads' # Folder to store uploaded files
app.config['ALLOWED_EXTENSIONS'] = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
if not os.path.exists(app.config['UPLOAD_FO... | import os
import tempfile
import pytest
from solution import app
@pytest.fixture
def client():
db_fd, app.config['DATABASE'] = tempfile.mkstemp()
app.config['TESTING'] = True
client = app.test_client()
yield client
os.close(db_fd)
os.unlink(app.config['DATABASE'])
def test_upload_and_downloa... | [
{
"docstring": null,
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def index():",
"function_name": "index",
"parameter_list": "()"
},
{
"docstring": n... | [
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, redirect, url_for, send_from_directory, render_template\nimport os\n\napp = Flask(__name__)\nUPLOAD_FOLDER = 'uploads'\napp.config['UPLOAD_FOLDER'] = UPLOAD_F... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00065353",
"row_id": 65353,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_132338']"
} | 0.490127 | Filter_65353 | I | [
"allowed_file",
"index",
"upload_file",
"uploaded_file"
] | 4 | [
[
"upload_file",
"allowed_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 9361eac2cd78efe636fb54da8e9abeb447306025 | 93c30b89779c5c18c27a47ef98e1d66b06719e7c | |||
v1.0 | instruct | Filter | Filter_65691_I | Hello Qwen, how can I create a Python script to check the validity of email addresses from a list using regular expressions? | import re
def is_valid_email(email):
"""
Checks if the given email is valid.
A valid email is defined by the presence of one "@" symbol and at least one "." in the part after "@".
Parameters:
email (str): The email address to validate.
Returns:
bool: True if the email is valid, False othe... | from solution import is_valid_email, check_email_list
def test_is_valid_email_valid_cases():
assert is_valid_email("test@example.com")
assert is_valid_email("user.name@domain.co")
assert is_valid_email("user_name@domain.com")
assert is_valid_email("user-name@domain.com")
def test_is_valid_email_invali... | [
{
"docstring": "Checks if the given email is valid.\nA valid email is defined by the presence of one \"@\" symbol and at least one \".\" in the part after \"@\".\n\nParameters:\nemail (str): The email address to validate.\n\nReturns:\nbool: True if the email is valid, False otherwise.",
"function_declaratio... | [
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 re\n\ndef validate_email_addresses(email_list):\n \"\"\"\n Validates email addresses from a list using regular expressions.\n Returns a dictionary with email as key and validit... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00065691",
"row_id": 65691,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133020']"
} | 0.538269 | Filter_65691 | I | [
"is_valid_email",
"check_email_list"
] | 2 | [
[
"check_email_list",
"is_valid_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3d5f7ace27dc1151eb5ddb76da44f9e9f8d657e1 | 4006688018872f1c47d63c912c7ba9e17b1c6853 | |||
v1.0 | instruct | Filter | Filter_65760_I | Can you explain how to calculate the mantissa and exponent of a floating-point number in Python using the `struct` module? | import struct
def float_to_bits(f):
"""
Converts a floating point number to its binary representation.
"""
[d] = struct.unpack(">Q", struct.pack(">d", f))
return d
def calculate_mantissa_and_exponent(f):
"""
Calculate the mantissa and exponent of a floating-point number.
Args:
... | def test_calculate_mantissa_and_exponent():
# Test cases are taken considering the known mantissa and exponents
assert calculate_mantissa_and_exponent(1.0) == (1.0, 0)
assert calculate_mantissa_and_exponent(2.0) == (1.0, 1)
assert calculate_mantissa_and_exponent(0.5) == (1.0, -1)
assert calculate_ma... | [
{
"docstring": "Converts a floating point number to its binary representation.",
"function_declaration": "def float_to_bits(f):",
"function_name": "float_to_bits",
"parameter_list": "(f)"
},
{
"docstring": "Calculate the mantissa and exponent of a floating-point number.\n\nArgs:\nf (float): ... | [
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 struct\n\ndef get_mantissa_and_exponent(number: float):\n packed = struct.pack('!d', number) # Pack the float as 64-bit double in network byte order\n unpacked = struct.unpack('!... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00065760",
"row_id": 65760,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133147']"
} | 0.423021 | Filter_65760 | I | [
"float_to_bits",
"calculate_mantissa_and_exponent"
] | 2 | [
[
"calculate_mantissa_and_exponent",
"float_to_bits"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 08c3b74ded98366aad43c90fd58a4008ab5415f5 | 2e17ec9ddfb7bc161d1f606c8e79277bc64d0ba4 | |||
v1.0 | instruct | Filter | Filter_65958_I | Write a Python script that uses the `webbrowser` module to open a specified URL in the default web browser. Additionally, include a feature to open multiple URLs sequentially in the browser. You should also handle cases where the URL might be invalid or not accessible. Try to make the script robust against such errors. | import webbrowser
import urllib.request
def open_url(url):
"""
Opens the specified URL in the default web browser.
Handles invalid or inaccessible URLs.
"""
try:
# Verify the URL is accessible
urllib.request.urlopen(url)
webbrowser.open(url)
return True
except Ex... | from solution import open_url, open_urls_sequentially
def test_open_url_valid():
# Assuming example.com is always accessible for the test case
assert open_url("http://example.com") == True
def test_open_url_invalid():
assert open_url("http://thisurldoesnotexist.invalid") == False
def test_open_urls_seque... | [
{
"docstring": "Opens the specified URL in the default web browser.\nHandles invalid or inaccessible URLs.",
"function_declaration": "def open_url(url):",
"function_name": "open_url",
"parameter_list": "(url)"
},
{
"docstring": "Opens multiple URLs sequentially in the default web browser.",
... | [
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 webbrowser\nimport validators\n\ndef open_url(url):\n \"\"\"\n Opens a single URL in the default web browser.\n \"\"\"\n if validators.url(url):\n try:\n w... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00065958",
"row_id": 65958,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133568']"
} | 0.659621 | Filter_65958 | I | [
"open_url",
"open_urls_sequentially"
] | 2 | [
[
"open_urls_sequentially",
"open_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b00bf0050fd23e7724c3ade0686501c0a34e1dc4 | c93ab83e818f01be42e0f71962121e0148128640 | |||
v1.0 | instruct | Filter | Filter_65976_I | I want to create a Python program that converts temperatures between Celsius, Fahrenheit, and Kelvin. Could you provide a sample code for this? | def celsius_to_fahrenheit(celsius):
"""
Convert Celsius to Fahrenheit.
"""
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
"""
Convert Fahrenheit to Celsius.
"""
return (fahrenheit - 32) * 5/9
def celsius_to_kelvin(celsius):
"""
Convert Celsius to Kelvin.
... | from solution import celsius_to_fahrenheit, fahrenheit_to_celsius, celsius_to_kelvin, kelvin_to_celsius, fahrenheit_to_kelvin, kelvin_to_fahrenheit
def test_celsius_to_fahrenheit():
assert celsius_to_fahrenheit(0) == 32
assert celsius_to_fahrenheit(100) == 212
assert round(celsius_to_fahrenheit(-40), 2) ==... | [
{
"docstring": "Convert Celsius to Fahrenheit.",
"function_declaration": "def celsius_to_fahrenheit(celsius):",
"function_name": "celsius_to_fahrenheit",
"parameter_list": "(celsius)"
},
{
"docstring": "Convert Fahrenheit to Celsius.",
"function_declaration": "def fahrenheit_to_celsius(f... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def celsius_to_fahrenheit(celsius):\n \"\"\"\n Converts Celsius to Fahrenheit.\n \"\"\"\n return celsius * 9/5 + 32\n\ndef fahrenheit_to_celsius(fahrenheit):\n \"\"\"\n Conve... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00065976",
"row_id": 65976,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133589']"
} | 0.450149 | Filter_65976 | I | [
"celsius_to_fahrenheit",
"fahrenheit_to_celsius",
"celsius_to_kelvin",
"kelvin_to_celsius",
"fahrenheit_to_kelvin",
"kelvin_to_fahrenheit"
] | 6 | [
[
"fahrenheit_to_kelvin",
"celsius_to_kelvin"
],
[
"fahrenheit_to_kelvin",
"fahrenheit_to_celsius"
],
[
"kelvin_to_fahrenheit",
"celsius_to_fahrenheit"
],
[
"kelvin_to_fahrenheit",
"kelvin_to_celsius"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 947cc56b926c5aeea65385255d6f53fcbb06e0af | 7edaac3fddc1b49ee9bdf52f010a1e609740a22b | |||
v1.0 | instruct | Filter | Filter_66185_I | Can you provide a Python function that generates a triadic color scheme based on a given hex color? A triadic color scheme consists of three colors that are evenly spaced on the color wheel. | def hex_to_rgb(hex_color):
"""Convert a hex color to an RGB tuple."""
hex_color = hex_color.lstrip('#')
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
def rgb_to_hex(rgb_color):
"""Convert an RGB tuple to a hex color."""
return '#{:02x}{:02x}{:02x}'.format(*rgb_color)
def rotate_color(... | from solution import generate_triadic_scheme
def test_generate_triadic_scheme_basic():
assert generate_triadic_scheme('#ff0000') == ['#ff0000', '#00ff00', '#0000ff']
def test_generate_triadic_scheme_blue():
assert generate_triadic_scheme('#0000ff') == ['#0000ff', '#ff0000', '#00ff00']
def test_genera... | [
{
"docstring": "Convert a hex color to an RGB tuple.",
"function_declaration": "def hex_to_rgb(hex_color):",
"function_name": "hex_to_rgb",
"parameter_list": "(hex_color)"
},
{
"docstring": "Convert an RGB tuple to a hex color.",
"function_declaration": "def rgb_to_hex(rgb_color):",
... | [
0,
0,
0,
1,
0,
0,
1,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def hex_to_rgb(hex_color):\n \"\"\"\n Convert hex color to RGB.\n \"\"\"\n hex_color = hex_color.lstrip('#')\n return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))\n\ndef ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00066185",
"row_id": 66185,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134030']"
} | 0.520965 | Filter_66185 | I | [
"hex_to_rgb",
"rgb_to_hex",
"rotate_color",
"generate_triadic_scheme"
] | 4 | [
[
"generate_triadic_scheme",
"hex_to_rgb"
],
[
"generate_triadic_scheme",
"rgb_to_hex"
],
[
"generate_triadic_scheme",
"rotate_color"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 26a29158cdb2657ccfcc2d1fd2d2dd5a1daa3384 | 83bce9afe299ed247dd56e44ba7a53f99641076d | |||
v1.0 | instruct | Filter | Filter_66302_I | Given a string `s`, where `s` consists of lowercase English letters, find the longest palindromic substring in `s`. A palindromic substring is a substring that reads the same backward as forward. | def longest_palindromic_substring(s):
"""
Returns the longest palindromic substring in 's'.
"""
n = len(s)
if n == 0:
return ""
# Initialize the starting and ending indices of the longest palindrome.
start = 0
end = 0
for i in range(n):
# Odd length palindro... | from solution import longest_palindromic_substring
def test_longest_palindromic_substring():
assert longest_palindromic_substring("babad") in ["bab", "aba"]
assert longest_palindromic_substring("cbbd") == "bb"
assert longest_palindromic_substring("a") == "a"
assert longest_palindromic_substring("ac") i... | [
{
"docstring": "Returns the longest palindromic substring in 's'.",
"function_declaration": "def longest_palindromic_substring(s):",
"function_name": "longest_palindromic_substring",
"parameter_list": "(s)"
},
{
"docstring": "Expands around the center and returns the length of the palindrome... | [
0,
0,
0,
1,
1,
0,
0,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def longest_palindromic_substring(s):\n \"\"\"\n Returns the longest palindromic substring in s.\n \"\"\"\n n = len(s)\n if n < 2:\n return s\n\n start, max_length = 0... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00066302",
"row_id": 66302,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134252']"
} | 0.798776 | Filter_66302 | I | [
"longest_palindromic_substring",
"expand_around_center"
] | 2 | [
[
"longest_palindromic_substring",
"expand_around_center"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d63663057ded1c944dbf5b33e0eba91e0873edd8 | 1450ed60f6b44125fbb0e869855a6b4a7d033af0 | |||
v1.0 | instruct | Filter | Filter_66414_I | I have a Python code snippet that splits a string into parts and checks if a number is prime. How can I modify it to split the string into parts and check if we can split a number from the string into prime numbers? For example, given a string "137", it should check if "137" can be split into prime numbers, like "13" +... | def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def can_split_into_primes(s):
"""
Checks if the given string can be split into prime numbers.
"""
def helper(s, start):
if start =... | from solution import is_prime, can_split_into_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(13) == True
assert is_prime(17) == True
assert is_prime(20) == False
def test_can_split_into_primes():
assert can_spli... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Checks if the given string can be split into prime numbers.",
"function_declaration": "def can_split_into_primes(s):",
"function_name": "can_sp... | [
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 in (2, 3):\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00066414",
"row_id": 66414,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134465']"
} | 0.657579 | Filter_66414 | I | [
"is_prime",
"can_split_into_primes"
] | 2 | [
[
"can_split_into_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 97f9b61be2227f9405d4b345afade4638a2b2242 | b423be0f04373375edd77291ae9bbe0cc7defa4d | |||
v1.0 | instruct | Filter | Filter_66449_I | How can I efficiently find the nth prime number using Python? | def sieve_of_eratosthenes(limit):
"""
Generates all prime numbers up to the specified limit using the Sieve of Eratosthenes algorithm.
"""
is_prime = [True] * (limit + 1)
p = 2
while (p * p <= limit):
if (is_prime[p] == True):
for i in range(p * p, limit + 1, p):
... | from solution import nth_prime
def test_nth_prime_first_five():
assert nth_prime(1) == 2
assert nth_prime(2) == 3
assert nth_prime(3) == 5
assert nth_prime(4) == 7
assert nth_prime(5) == 11
def test_nth_prime_large_input():
assert nth_prime(100) == 541
assert nth_prime(1000) == 7919
as... | [
{
"docstring": "Generates all prime numbers up to the specified limit using the Sieve of Eratosthenes algorithm.",
"function_declaration": "def sieve_of_eratosthenes(limit):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(limit)"
},
{
"docstring": "Returns the nth prime numbe... | [
0,
0,
0,
1,
1,
0,
1,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def nth_prime(n):\n \"\"\"\n Returns the nth prime number.\n \"\"\"\n if n <= 0:\n raise ValueError(\"n must be a positive integer\")\n \n # Estimate upper bound for n... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00066449",
"row_id": 66449,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134546']"
} | 0.614354 | Filter_66449 | I | [
"sieve_of_eratosthenes",
"nth_prime"
] | 2 | [
[
"nth_prime",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0e1a2b441091317aae8d18586f114c2d11c1bb3d | bcd335649d65a02bcd0ff17e1658e57cbf712c34 | |||
v1.0 | instruct | Filter | Filter_66513_I | I want to create a Python script to automate some tasks on my computer. Can you guide me on how to get started with writing a Python script for automation, specifically focusing on file manipulation and task scheduling? | import os
def create_file(file_name):
"""
Creates an empty file with the given file name if it does not exist.
"""
if not os.path.isfile(file_name):
with open(file_name, 'w') as file:
pass
return file_name
def write_to_file(file_name, content):
"""
Writes the specified ... | import os
from solution import create_file, write_to_file, read_from_file, automate_task
def test_create_file():
file_name = 'test_file.txt'
create_file(file_name)
assert os.path.isfile(file_name)
os.remove(file_name)
def test_write_to_file():
file_name = 'test_file.txt'
content = 'Test conten... | [
{
"docstring": "Creates an empty file with the given file name if it does not exist.",
"function_declaration": "def create_file(file_name):",
"function_name": "create_file",
"parameter_list": "(file_name)"
},
{
"docstring": "Writes the specified content to the file.",
"function_declarati... | [
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 shutil\nimport schedule\nimport time\n\ndef create_directory(directory_path):\n \"\"\"\n Creates a directory if it does not exist.\n \"\"\"\n if not os.path.exist... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00066513",
"row_id": 66513,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134665']"
} | 0.510569 | Filter_66513 | I | [
"create_file",
"write_to_file",
"read_from_file",
"automate_task"
] | 4 | [
[
"automate_task",
"create_file"
],
[
"automate_task",
"read_from_file"
],
[
"automate_task",
"write_to_file"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 64cea143cedba984cb41a26a30e507fd1944a942 | 403cdc2d05c9dc31343b69b97af937f45f1b564c | |||
v1.0 | instruct | Filter | Filter_66553_I | Create a Python script to monitor and log the battery status of a laptop using the `psutil` library. The script should log the battery percentage and status (charged, charging, discharging) to a file every 10 seconds. Additionally, it should monitor for any changes in the battery status (e.g., starting to charge or dis... | import psutil
import time
import logging
# Set up logging
logging.basicConfig(filename='battery_log.txt', level=logging.INFO,
format='%(asctime)s - %(message)s')
# Constants
CRITICAL_THRESHOLD = 15
CHECK_INTERVAL = 10 # seconds
def get_battery_status():
battery = psutil.sensors_battery()
... | import pytest
import psutil
from unittest.mock import patch
from solution import get_battery_status, log_battery_status
def test_get_battery_status_discharging():
with patch('psutil.sensors_battery') as mock_battery:
mock_battery.return_value.percent = 50
mock_battery.return_value.power_plugged = F... | [
{
"docstring": null,
"function_declaration": "def get_battery_status():",
"function_name": "get_battery_status",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def log_battery_status():",
"function_name": "log_battery_status",
"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 psutil\nimport time\nimport datetime\n\ndef get_battery_status():\n battery = psutil.sensors_battery()\n percent = battery.percent\n charging = battery.power_plugged\n statu... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00066553",
"row_id": 66553,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134748']"
} | 0.535192 | Filter_66553 | I | [
"get_battery_status",
"log_battery_status"
] | 2 | [
[
"log_battery_status",
"get_battery_status"
]
] | 1 | [] | false | [] | false | pytest | true | [
"psutil"
] | false | daf0235fad777783fc4dc82a9c14c7b82b778f2f | 056a2e276f551add19155301e4898f326140afb2 | |||
v1.0 | instruct | Filter | Filter_66617_I | Could you explain the core logic of the code snippet that uses Trax and JAX for creating a simple wave generator and audio output? | import numpy as np
import matplotlib.pyplot as plt
def sine_wave(frequency, duration, samplerate=44100, amplitude=0.5):
"""
Generate a sine wave of a given frequency and duration.
:param frequency: Frequency of the sine wave in Hz.
:param duration: Duration of the sine wave in seconds.
:param ... | import numpy as np
from solution import sine_wave, generate_wave
def test_sine_wave_shape():
frequency = 440 # A4 note
duration = 1.0 # 1 second
sr = 44100 # 44100 samples per second
wave = sine_wave(frequency, duration, sr)
assert wave.shape == (sr * duration,), "The shape of the sine wave is i... | [
{
"docstring": "Generate a sine wave of a given frequency and duration.\n\n:param frequency: Frequency of the sine wave in Hz.\n:param duration: Duration of the sine wave in seconds.\n:param samplerate: Sample rate in samples per second.\n:param amplitude: Amplitude of the sine wave.\n:return: Numpy array conta... | [
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 numpy as np\nimport trax\n\ndef generate_sine_wave(frequency, duration, sample_rate=44100):\n \"\"\"\n Generate a sine wave of given frequency and duration.\n\n Args:\n freq... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00066617",
"row_id": 66617,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134888']"
} | 0.286664 | Filter_66617 | I | [
"sine_wave",
"generate_wave"
] | 2 | [
[
"generate_wave",
"sine_wave"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | f999e3feb12276e392e9e0b5b3186818803082b8 | 24b51dcc360c54670d823afd063a344f43ee84b8 | |||
v1.0 | instruct | Filter | Filter_66709_I | I want to create a Python script that captures images from a webcam and applies image processing techniques to enhance the quality of the images. Can you provide a basic outline of how to achieve this? | import cv2
def capture_and_enhance_webcam_image():
# Open a connection to the webcam (0 is the default camera)
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Error: Could not open webcam")
return
retval, frame = cap.read()
if not retval:
print("Error: Could not r... | import cv2
import numpy as np
from solution import enhance_image
def test_enhance_image_returns_array():
test_image = np.ones((100, 100, 3), dtype=np.uint8) * 255
processed_image = enhance_image(test_image)
assert isinstance(processed_image, np.ndarray)
def test_enhance_image_grayscale():
test_image =... | [
{
"docstring": null,
"function_declaration": "def capture_and_enhance_webcam_image():",
"function_name": "capture_and_enhance_webcam_image",
"parameter_list": "()"
},
{
"docstring": "Applies image processing techniques to enhance the quality of the given image.",
"function_declaration": ... | [
0,
0,
0,
1,
0,
0,
1,
0,
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 capture_and_process_image():\n \"\"\"\n Captures an image from the webcam and applies basic image processing techniques\n to enhance the quality of the image.\n \... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00066709",
"row_id": 66709,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135073']"
} | 0.45594 | Filter_66709 | I | [
"capture_and_enhance_webcam_image",
"enhance_image"
] | 2 | [
[
"capture_and_enhance_webcam_image",
"enhance_image"
]
] | 1 | [] | false | [] | false | pytest | true | [
"cv2",
"numpy"
] | false | 197dbe80e1e37db5fecb2d7a5c28ad6e7104e019 | 0effd43dc5150d27044254a00c3f69bbe26d2cee | |||
v1.0 | instruct | Filter | Filter_66741_I | How can I create a Python program that simulates a simple file sorting application using a graphical user interface (GUI)? The application should allow users to select a directory containing files, choose the sorting criteria (e.g., file name, file size), and then sort the files in that directory according to the selec... | import os
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter.ttk import Combobox
def sort_files(directory, criteria):
"""
Sorts the files in the directory based on the given criteria.
Parameters:
directory (str): The path to the directory to be sorted.
criteri... | import os
import pytest
from solution import sort_files
def test_sort_files_by_name(tmpdir):
# Setup
file1 = tmpdir.join("b.txt")
file1.write("File b content")
file2 = tmpdir.join("a.txt")
file2.write("File a content")
# Execute
result = sort_files(str(tmpdir), "name")
# Valid... | [
{
"docstring": "Sorts the files in the directory based on the given criteria.\n\nParameters:\n directory (str): The path to the directory to be sorted.\n criteria (str): The sorting criteria ('name' or 'size').\n \nReturns:\n list: Sorted file names.",
"function_declaration": "def sort_files(dir... | [
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 tkinter as tk\nfrom tkinter import filedialog, messagebox\n\ndef sort_files(directory, criteria):\n try:\n files = os.listdir(directory)\n files = [f for f i... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00066741",
"row_id": 66741,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135139']"
} | 0.482341 | Filter_66741 | I | [
"sort_files",
"browse_directory",
"sort_and_display_files",
"create_gui"
] | 4 | [
[
"sort_and_display_files",
"sort_files"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c5f8b8aac9fd21bb4401de9f035365c43506f5b7 | c755a335a9cb6e73e7c195e608ad059ecf64cc01 | |||
v1.0 | instruct | Filter | Filter_66902_I | Can you provide a Python code snippet that demonstrates how to implement bijective functions for symmetric encryption, specifically using the Feistel Network structure? | def feistel_round(left, right, subkey):
"""
Performs one round of the Feistel function.
"""
new_left = right
new_right = left ^ subkey_function(right, subkey)
return new_left, new_right
def subkey_function(right, subkey):
"""
A simple subkey function that simulates complex transformatio... | from solution import feistel_encrypt, feistel_decrypt
def test_feistel_symmetric_property():
plaintext = (0b1100, 0b1010)
keys = [0b1001, 0b0110, 0b1111] # Sample keys
# Encrypt the plaintext
ciphertext = feistel_encrypt(plaintext, keys)
# Decrypt the ciphertext
decrypted_text = feistel_... | [
{
"docstring": "Performs one round of the Feistel function.",
"function_declaration": "def feistel_round(left, right, subkey):",
"function_name": "feistel_round",
"parameter_list": "(left, right, subkey)"
},
{
"docstring": "A simple subkey function that simulates complex transformation.",
... | [
0,
0,
0,
1,
1,
1,
0,
1,
1
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "def feistel_network_encrypt(plain_text, round_keys, f_func):\n \"\"\"\n Encrypts the plain_text using the Feistel Network structure.\n \n :param plain_text... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00066902",
"row_id": 66902,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135496']"
} | 0.380673 | Filter_66902 | I | [
"feistel_round",
"subkey_function",
"feistel_encrypt",
"feistel_decrypt"
] | 4 | [
[
"feistel_decrypt",
"feistel_round"
],
[
"feistel_encrypt",
"feistel_round"
],
[
"feistel_round",
"subkey_function"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 3912a5210f65314977f08cf4c99fb7afe5044b04 | 8ef7acd6c3f2573c1b6b615d6e4228210a142604 | |||
v1.0 | instruct | Filter | Filter_66918_I | How can I create an ICMP Echo Request message in Python? | import socket
import struct
import time
import os
def checksum(source_string):
"""
A helper function to calculate checksum of the packet.
"""
count_to = (len(source_string) // 2) * 2
sum = 0
count = 0
while count < count_to:
this_val = source_string[count + 1] * 256 + source_string... | import struct
from solution import create_icmp_echo_request, checksum
def test_create_icmp_echo_request():
identifier = 1
sequence = 1
packet = create_icmp_echo_request(identifier, sequence)
assert len(packet) > 0
# Unpack the header part and check
icmp_header = struct.unpack('bbHHh', pac... | [
{
"docstring": "A helper function to calculate checksum of the packet.",
"function_declaration": "def checksum(source_string):",
"function_name": "checksum",
"parameter_list": "(source_string)"
},
{
"docstring": "Create an ICMP Echo Request packet.",
"function_declaration": "def create_i... | [
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 struct\nimport socket\nimport time\nimport os\n\ndef checksum(source_string):\n \"\"\"\n A function used to calculate the checksum of the ICMP packet\n :param source_string: Th... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00066918",
"row_id": 66918,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135526']"
} | 0.48607 | Filter_66918 | I | [
"checksum",
"create_icmp_echo_request"
] | 2 | [
[
"create_icmp_echo_request",
"checksum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 92babb0bad906ac54f91c0816d0a048c3a2e83f9 | 343c9d0110dce643e678589cdce18c9c1e204786 | |||
v1.0 | instruct | Filter | Filter_66927_I | Can you design a Python script that allows a user to modify the parameters of a configuration file using command-line arguments? The script should be able to parse JSON or YAML configuration files, modify specific parameters, and save the changes back to the file. It should also include error handling to manage differe... | import argparse
import json
import yaml
def load_config(file_path):
# Determine file type and load it
if file_path.endswith('.json'):
with open(file_path, 'r') as file:
config = json.load(file)
elif file_path.endswith('.yaml') or file_path.endswith('.yml'):
with open(file_path, ... | import os
import json
import yaml
from solution import modify_config
# Helper function to create a JSON config file for testing
def create_json_config(file_path):
config = {
"database": {
"host": "localhost",
"port": 3306
},
"api": {
"endpoint": "https://... | [
{
"docstring": null,
"function_declaration": "def load_config(file_path):",
"function_name": "load_config",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def save_config(file_path, config):",
"function_name": "save_config",
"parameter_list": "(f... | [
0,
0,
0,
1,
1,
1,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nimport yaml\nimport argparse\nimport os\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Modify parameters of a configuration file\")\n parser.add_argum... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00066927",
"row_id": 66927,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135545']"
} | 0.639999 | Filter_66927 | I | [
"load_config",
"save_config",
"modify_config"
] | 3 | [
[
"modify_config",
"load_config"
],
[
"modify_config",
"save_config"
]
] | 2 | [] | false | [] | false | pytest | true | [
"yaml"
] | false | 39bdc531a67e2fa23ae469d9fa5b7293bbdafc57 | 67298695a19d0e61978815c1d20a134c8acde0f6 | |||
v1.0 | instruct | Filter | Filter_67061_I | Write a Python function to radix sort an array of integers. Radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value. | def counting_sort(arr, exp):
"""
A function to do counting sort of arr[] according to
the digit represented by exp (10^i place value)
"""
n = len(arr)
output = [0] * n # output array
count = [0] * 10 # digit count array
# Store count of occurrences in count[]
for i in ra... | from solution import radix_sort
def test_radix_sort_sorted_array():
arr = [1, 2, 3, 4, 5]
radix_sort(arr)
assert arr == [1, 2, 3, 4, 5]
def test_radix_sort_reverse_sorted_array():
arr = [5, 4, 3, 2, 1]
radix_sort(arr)
assert arr == [1, 2, 3, 4, 5]
def test_radix_sort_random_array():
arr =... | [
{
"docstring": "A function to do counting sort of arr[] according to\nthe digit represented by exp (10^i place value)",
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": "The main function that sorts arr... | [
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": "def counting_sort(arr, exp):\n \"\"\"\n A utility function to perform counting sort on the array with respect to the digit at exp place.\n \"\"\"\n n = len(arr)\n output = [0] *... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00067061",
"row_id": 67061,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135814']"
} | 0.681126 | Filter_67061 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8e0507786f7c7d7db4f0c6cd5db721ea769a3257 | c15fd1637f878699e0779bf8874db2503c5eca56 | |||
v1.0 | instruct | Filter | Filter_67169_I | I want to create a Python script to generate random data for a dataset analysis project. The data should include customer information such as name, age, gender, and email. How can I do this using Python? | import random
import string
def generate_random_name():
first_names = ["John", "Jane", "Sam", "Mike", "Anna", "Emily", "Alex", "Linda", "Gary", "Ella"]
last_names = ["Smith", "Doe", "Brown", "Johnson", "White", "King", "Lee", "Williams", "Jones", "Davis"]
return f"{random.choice(first_names)} {random.choi... | from solution import (
generate_random_name,
generate_random_age,
generate_random_gender,
generate_random_email,
generate_random_customer,
generate_random_customers
)
def test_generate_random_name():
name = generate_random_name()
assert isinstance(name, str)
assert len(name.sp... | [
{
"docstring": null,
"function_declaration": "def generate_random_name():",
"function_name": "generate_random_name",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def generate_random_age(min_age=18, max_age=80):",
"function_name": "generate_random_age",
... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport faker\n\ndef generate_random_customer_data(num_customers=1):\n \"\"\"\n Generates random customer data including name, age, gender, and email.\n\n Parameters:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00067169",
"row_id": 67169,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136043']"
} | 0.556262 | Filter_67169 | I | [
"generate_random_name",
"generate_random_age",
"generate_random_gender",
"generate_random_email",
"generate_random_customer",
"generate_random_customers"
] | 6 | [
[
"generate_random_customer",
"generate_random_age"
],
[
"generate_random_customer",
"generate_random_email"
],
[
"generate_random_customer",
"generate_random_gender"
],
[
"generate_random_customer",
"generate_random_name"
],
[
"generate_random_customers",
"ge... | 5 | [] | false | [] | false | pytest | true | [] | true | 057be16db744e4b34dfd514f4dd695a806f869f4 | dd0ebe66f84e2c51d8c52893714f4700fed64f16 | |||
v1.0 | instruct | Filter | Filter_67172_I | Write a Python script that reads a text file, counts the occurrences of each word, and then writes the word counts to a new file. The script should ignore common stop words (e.g., "the", "and", "is", etc.). You can use Python's built-in libraries to accomplish this task. For simplicity, you can define a list of stop wo... | import re
from collections import Counter
def read_file(file_path):
"""
Reads a file and returns its content as a single string.
"""
with open(file_path, 'r') as file:
return file.read()
def write_file(file_path, content):
"""
Writes the given content to a file.
"""
with open(f... | import pytest
from solution import read_file, write_file, count_words, process_files
from collections import Counter
import tempfile
def test_read_file():
with tempfile.NamedTemporaryFile(delete=False, mode='w') as temp_file:
temp_file.write("Sample text")
temp_file_path = temp_file.name
a... | [
{
"docstring": "Reads a file and returns its content as a single string.",
"function_declaration": "def read_file(file_path):",
"function_name": "read_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Writes the given content to a file.",
"function_declaration": "def write_file(f... | [
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 re\nfrom collections import Counter\n\ndef count_words(input_file, output_file):\n \"\"\"\n Reads a text file, counts the occurrences of each word ignoring the stop words,\n an... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00067172",
"row_id": 67172,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136046']"
} | 0.721742 | Filter_67172 | I | [
"read_file",
"write_file",
"count_words",
"process_files"
] | 4 | [
[
"process_files",
"count_words"
],
[
"process_files",
"read_file"
],
[
"process_files",
"write_file"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 8be24a066b68e11411cd2c0ac071942f082854af | d6031e8033d8ff1c2837f71fb699d7f57ebc9d18 | |||
v1.0 | instruct | Filter | Filter_67252_I | Write a Python function that takes a list of tuples representing points in a 2D plane, where each tuple contains two integers: the x and y coordinates of the point. The function should return the perimeter of the convex hull formed by these points. Use the Gift Wrapping algorithm (also known as the Jarvis March) to fin... | import math
def distance(p1, p2):
"""
Returns the Euclidean distance between points p1 and p2.
"""
return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
def orientation(p, q, r):
"""
Returns the orientation of the ordered triplet (p, q, r).
0 -> p, q and r are collinear
1 -> Cl... | from solution import distance, orientation, convex_hull, perimeter_of_convex_hull
def test_distance():
assert distance((0, 0), (3, 4)) == 5.0
def test_orientation():
assert orientation((0, 0), (1, 1), (2, 2)) == 0
assert orientation((0, 0), (1, 1), (1, 0)) == 1
assert orientation((0, 0), (1, 1), (0, 1... | [
{
"docstring": "Returns the Euclidean distance between points p1 and p2.",
"function_declaration": "def distance(p1, p2):",
"function_name": "distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": "Returns the orientation of the ordered triplet (p, q, r).\n0 -> p, q and r are collinear\n1... | [
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 math\n\ndef distance(p1, p2):\n \"\"\"\n Returns the Euclidean distance between points p1 and p2.\n \"\"\"\n return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)\n\... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00067252",
"row_id": 67252,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136216']"
} | 0.508405 | Filter_67252 | I | [
"distance",
"orientation",
"convex_hull",
"perimeter_of_convex_hull"
] | 4 | [
[
"convex_hull",
"orientation"
],
[
"perimeter_of_convex_hull",
"convex_hull"
],
[
"perimeter_of_convex_hull",
"distance"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 6bd715625404c8d16e64704ea7d125f056cc4d78 | e70d58a55112be5a6a51ea3321a8b787e3f86c69 | |||
v1.0 | instruct | Filter | Filter_67322_I | Sure, please provide me with a Python script to monitor CPU usage and send an email alert if it exceeds a certain threshold. This script should use the `psutil` library for monitoring and `smtplib` for sending emails. The script should be able to run continuously in the background and should use threading to avoid bloc... | import psutil
import smtplib
from email.mime.text import MIMEText
import time
import threading
def send_email_alert(threshold, cpu_usage):
from_email = "youremail@example.com"
to_email = "alertemail@example.com"
subject = "CPU Usage Alert"
body = f"CPU usage has exceeded the threshold of {threshold}%. ... | from unittest.mock import patch, MagicMock
import pytest
# Mocking psutil library to simulate CPU usage
@patch('psutil.cpu_percent', return_value=85)
def test_monitor_cpu_high_usage(mock_cpu_percent):
with patch('smtplib.SMTP') as mock_smtp:
mock_smtp_instance = mock_smtp.return_value
mock_smtp_ins... | [
{
"docstring": null,
"function_declaration": "def send_email_alert(threshold, cpu_usage):",
"function_name": "send_email_alert",
"parameter_list": "(threshold, cpu_usage)"
},
{
"docstring": null,
"function_declaration": "def monitor_cpu(threshold, interval):",
"function_name": "monit... | [
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 psutil\nimport smtplib\nfrom email.mime.text import MIMEText\nimport threading\nimport time\n\ndef send_email_alert(subject, body, to_email):\n from_email = \"your_email@example.com\... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00067322",
"row_id": 67322,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136347']"
} | 0.614233 | Filter_67322 | I | [
"send_email_alert",
"monitor_cpu",
"start_monitoring"
] | 3 | [
[
"monitor_cpu",
"send_email_alert"
]
] | 1 | [] | false | [] | false | pytest | true | [
"psutil"
] | false | 9040e65b944a1c9096f4b5e08cda23b9ebe98578 | 5da4cdbd0b7b4867ebc50a45175cf4ab88759e93 | |||
v1.0 | instruct | Filter | Filter_67453_I | Can you show me how to calculate the Jaro-Winkler distance between two strings in Python? | def jaro_distance(s1, s2):
if s1 == s2:
return 1.0
len_s1 = len(s1)
len_s2 = len(s2)
if len_s1 == 0 or len_s2 == 0:
return 0.0
max_dist = int(max(len_s1, len_s2) // 2) - 1
match = 0
hash_s1 = [0] * len_s1
hash_s2 = [0] * len_s2
for i in range(len_s1):
... | import pytest
from solution import jaro_winkler_distance
def test_jaro_winkler_distance_identical_strings():
assert jaro_winkler_distance("same", "same") == 1.0
def test_jaro_winkler_distance_completely_different_strings():
assert jaro_winkler_distance("abc", "xyz") == pytest.approx(0.0, 0.01)
def test_jaro_... | [
{
"docstring": null,
"function_declaration": "def jaro_distance(s1, s2):",
"function_name": "jaro_distance",
"parameter_list": "(s1, s2)"
},
{
"docstring": null,
"function_declaration": "def jaro_winkler_distance(s1, s2, p=0.1):",
"function_name": "jaro_winkler_distance",
"parame... | [
0,
0,
0,
1,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def jaro_distance(s1, s2):\n \"\"\"\n Calculates the Jaro Distance between two strings.\n \"\"\"\n if s1 == s2:\n return 1.0\n\n len_s1 = len(s1)\n len_s2 = len(s2)\n\... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00067453",
"row_id": 67453,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136628']"
} | 0.580614 | Filter_67453 | I | [
"jaro_distance",
"jaro_winkler_distance"
] | 2 | [
[
"jaro_winkler_distance",
"jaro_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ec80d21140433bae359e04ad06879cf568c8244d | d096d50b7c491aef9b9bf2670411b5e2b5babd3c | |||
v1.0 | instruct | Filter | Filter_67467_I | What are the steps to develop a simple recommendation system using collaborative filtering in Python? | import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
def calculate_similarity(ratings):
"""
Calculates cosine similarity between users.
:param ratings: 2D numpy array with users as rows and items as columns.
:return: 2D numpy array representing user similarity matrix.
"""
... | from solution import calculate_similarity, predict_ratings, recommend_items
import numpy as np
def test_calculate_similarity():
ratings = np.array([
[5, 0, 0],
[4, 0, 0],
[1, 1, 0],
[0, 1, 5]
])
similarity = calculate_similarity(ratings)
assert similarity.shape == (4, 4)... | [
{
"docstring": "Calculates cosine similarity between users.\n\n:param ratings: 2D numpy array with users as rows and items as columns.\n:return: 2D numpy array representing user similarity matrix.",
"function_declaration": "def calculate_similarity(ratings):",
"function_name": "calculate_similarity",
... | [
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 numpy as np\nimport pandas as pd\nfrom sklearn.metrics.pairwise import cosine_similarity\n\ndef create_user_item_matrix(data):\n \"\"\"\n Creates a user-item matrix from the given... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00067467",
"row_id": 67467,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136652']"
} | 0.43937 | Filter_67467 | I | [
"calculate_similarity",
"predict_ratings",
"recommend_items"
] | 3 | [
[
"recommend_items",
"predict_ratings"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 4b648edf6762bbdbee01f513ab43d0daf09ac97b | 99729d9cc7c56418ba8cda63c445d337100f49ee | |||
v1.0 | instruct | Filter | Filter_67689_I | Generate a Python code snippet to find the longest word in a list of words, considering only alphabetic characters. This code should handle cases where there might be special characters or numbers mixed with the words. | import re
def clean_word(word):
"""
Removes non-alphabetic characters from the word.
"""
return re.sub(r'[^a-zA-Z]', '', word)
def longest_word(words):
"""
Returns the longest word in a list of words, considering only alphabetic characters.
"""
cleaned_words = [clean_word(word) for wor... | from solution import longest_word, clean_word
def test_clean_word():
assert clean_word("hello!") == "hello"
assert clean_word("world123") == "world"
assert clean_word("!@#Python$%^") == "Python"
def test_longest_word_basic():
assert longest_word(["hello", "world", "Python", "programming"]) == "program... | [
{
"docstring": "Removes non-alphabetic characters from the word.",
"function_declaration": "def clean_word(word):",
"function_name": "clean_word",
"parameter_list": "(word)"
},
{
"docstring": "Returns the longest word in a list of words, considering only alphabetic characters.",
"functio... | [
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 re\n\ndef longest_word(words):\n \"\"\"\n Returns the longest word consisting of only alphabetic characters in the list.\n If there are multiple words with the same length, ret... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00067689",
"row_id": 67689,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137111']"
} | 0.778533 | Filter_67689 | I | [
"clean_word",
"longest_word"
] | 2 | [
[
"longest_word",
"clean_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | be8c162cd476ff773c4c6529a3f5aec01fda0a7d | 82d3da812995c2a861523ace4ae4eb92eac0955b | |||
v1.0 | instruct | Filter | Filter_68087_I | Can you provide a Python script that simulates a simple artificial neural network (ANN) for regression using only basic Python libraries? No external libraries like TensorFlow or PyTorch. | import random
def initialize_weights(layer_sizes):
"""
Initialize weights and biases.
"""
weights = []
biases = []
for i in range(len(layer_sizes) - 1):
weight_matrix = [[random.uniform(-1, 1) for _ in range(layer_sizes[i+1])] for _ in range(layer_sizes[i])]
bias_vector = [rando... | from solution import initialize_weights, sigmoid, sigmoid_derivative, feedforward, backpropagate, train_network, predict
def test_initialize_weights():
weights, biases = initialize_weights([2, 3, 1])
assert len(weights) == 2
assert len(weights[0]) == 2
assert len(weights[0][0]) == 3
assert len(weig... | [
{
"docstring": "Initialize weights and biases.",
"function_declaration": "def initialize_weights(layer_sizes):",
"function_name": "initialize_weights",
"parameter_list": "(layer_sizes)"
},
{
"docstring": "Sigmoid activation function.",
"function_declaration": "def sigmoid(x):",
"func... | [
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\nimport math\n\nclass SimpleANN:\n def __init__(self, input_size, hidden_size, output_size, learning_rate=0.01):\n # Initializing weights and biases\n self.input... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00068087",
"row_id": 68087,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137901']"
} | 0.338439 | Filter_68087 | I | [
"initialize_weights",
"sigmoid",
"sigmoid_derivative",
"feedforward",
"backpropagate",
"train_network",
"predict"
] | 7 | [
[
"backpropagate",
"sigmoid_derivative"
],
[
"feedforward",
"sigmoid"
],
[
"predict",
"feedforward"
],
[
"train_network",
"backpropagate"
],
[
"train_network",
"feedforward"
],
[
"train_network",
"initialize_weights"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | cb55d8cb212c26402ce179e004cd09b4d0bc8bdc | 1820371aad205517b3fbaacdc2c1a543e4e328cb | |||
v1.0 | instruct | Filter | Filter_68274_I | Please provide a detailed explanation of how to implement a genetic algorithm in Python, including the necessary components and their interactions. | import random
def create_individual(length):
"""
Creates a random individual of 'length' genes.
"""
return [random.randint(0, 1) for _ in range(length)]
def create_population(size, length):
"""
Creates a population of 'size' individuals, each of 'length' genes.
"""
return [create_indiv... | from solution import create_individual, create_population, fitness, selection, crossover, mutate, genetic_algorithm
def test_create_individual():
individual = create_individual(10)
assert len(individual) == 10
assert all(gene in [0, 1] for gene in individual)
def test_create_population():
population =... | [
{
"docstring": "Creates a random individual of 'length' genes.",
"function_declaration": "def create_individual(length):",
"function_name": "create_individual",
"parameter_list": "(length)"
},
{
"docstring": "Creates a population of 'size' individuals, each of 'length' genes.",
"function... | [
0,
0,
0,
0,
0,
1,
1,
1,
1
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_individual(length, gene_pool):\n \"\"\"\n Creates a random individual or solution.\n \n :param length: Length of the individual.\n :param gene_pool... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00068274",
"row_id": 68274,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138286']"
} | 0.368307 | Filter_68274 | I | [
"create_individual",
"create_population",
"fitness",
"selection",
"crossover",
"mutate",
"genetic_algorithm"
] | 7 | [
[
"create_population",
"create_individual"
],
[
"genetic_algorithm",
"create_population"
],
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"fitness"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"selection"
],
[
... | 7 | [] | false | [] | false | pytest | true | [] | true | 295c0992fc1f4519fe8bd79aff933f0a4227faeb | 41eca92e8386460ff31d1446c080f371e0329fe9 | |||
v1.0 | instruct | Filter | Filter_68561_I | Given a string `s`, write a function `find_closest_palindrome` that returns the closest palindrome number to the given string `s`. A number is a palindrome if it reads the same backward as forward. The function should return the closest palindrome in lexicographical order if there are multiple closest palindromes. | def is_palindrome(num_str):
return num_str == num_str[::-1]
def find_closest_palindrome(s):
n = int(s)
# Handling edge cases where length of s is 1
if len(s) == 1:
return s
# Checking the palindromes prospected before and after the number
i = 0
while True:
if is_pa... | from solution import find_closest_palindrome
def test_palindrome_number():
assert find_closest_palindrome("121") == "121"
def test_nearby_smaller_palindrome():
assert find_closest_palindrome("123") == "121"
def test_nearby_larger_palindrome():
assert find_closest_palindrome("120") == "121"
def test_sing... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(num_str):",
"function_name": "is_palindrome",
"parameter_list": "(num_str)"
},
{
"docstring": null,
"function_declaration": "def find_closest_palindrome(s):",
"function_name": "find_closest_palindrome",
"parameter_li... | [
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 is_palindrome(num):\n \"\"\"\n Helper function to check if a number (in string format) is a palindrome.\n \"\"\"\n return num == num[::-1]\n\ndef find_closest_palindrome(s):\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00068561",
"row_id": 68561,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138931']"
} | 0.741691 | Filter_68561 | I | [
"is_palindrome",
"find_closest_palindrome"
] | 2 | [
[
"find_closest_palindrome",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6380dbcc93ab1a9a0e90a8e33d24babc931d666d | 2ef49cee5301c1070cc7c74c0bfd7a17d9ba8c96 | |||
v1.0 | instruct | Filter | Filter_68701_I | Could you provide a simple example of how to create a new wallet for a digital currency like Bitcoin using Python? | import hashlib
import os
import binascii
def generate_private_key():
"""
Generates a new private key using 32 bytes of os randomness
"""
return binascii.hexlify(os.urandom(32)).decode('utf-8')
def private_key_to_public_key(private_key):
"""
Converts a private key to a public key using elliptic... | from solution import generate_private_key, private_key_to_public_key, public_key_to_address, create_wallet
def test_generate_private_key():
private_key = generate_private_key()
assert len(private_key) == 64
assert isinstance(private_key, str)
def test_private_key_to_public_key():
private_key = 'a1b2c3... | [
{
"docstring": "Generates a new private key using 32 bytes of os randomness",
"function_declaration": "def generate_private_key():",
"function_name": "generate_private_key",
"parameter_list": "()"
},
{
"docstring": "Converts a private key to a public key using elliptic curve multiplication.\... | [
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 bitcoin import *\n\ndef create_wallet():\n \"\"\"\n Creates a new Bitcoin wallet including a private key, public key, and an address.\n \"\"\"\n private_key = random_key()\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00068701",
"row_id": 68701,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139241']"
} | 0.416587 | Filter_68701 | I | [
"generate_private_key",
"private_key_to_public_key",
"public_key_to_address",
"create_wallet"
] | 4 | [
[
"create_wallet",
"generate_private_key"
],
[
"create_wallet",
"private_key_to_public_key"
],
[
"create_wallet",
"public_key_to_address"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ff8ef0484e0b38482b7d7fe97ac92dfce137c72f | 14fe186a8ded2b335d259a35d2dea4b4b8506f16 | |||
v1.0 | instruct | Filter | Filter_68738_I | Provide a Python script that generates a report on the memory usage of a specific process by its process ID (PID). The script should output the memory usage details in a formatted report. | import psutil
def get_memory_usage_by_pid(pid):
"""
Get the memory usage details of a specified process by PID.
Parameters:
pid (int): Process ID.
Returns:
dict: Memory usage details including rss, vms, shared, text, lib, data, and dirty memory.
"""
try:
process = psutil.P... | from solution import get_memory_usage_by_pid, generate_report
import psutil
def test_get_memory_usage_by_pid_existing_process():
current_pid = psutil.Process().pid
memory_usage = get_memory_usage_by_pid(current_pid)
assert "rss" in memory_usage
assert "vms" in memory_usage
assert "shared" in memory... | [
{
"docstring": "Get the memory usage details of a specified process by PID.\n\nParameters:\npid (int): Process ID.\n\nReturns:\ndict: Memory usage details including rss, vms, shared, text, lib, data, and dirty memory.",
"function_declaration": "def get_memory_usage_by_pid(pid):",
"function_name": "get_m... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import psutil\n\ndef get_memory_usage_details(pid):\n \"\"\"\n Function that retrieves and returns memory usage details of a process given its PID.\n \n Parameters:\n pid (int):... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00068738",
"row_id": 68738,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139313']"
} | 0.634198 | Filter_68738 | I | [
"get_memory_usage_by_pid",
"generate_report"
] | 2 | [
[
"generate_report",
"get_memory_usage_by_pid"
]
] | 1 | [] | false | [] | false | pytest | true | [
"psutil"
] | false | f701d9d0c2288079f70e1117ca0f48b9e9574ec4 | a7e9ae4d92b79a52ed8283646fcbdaaffda9bfb7 | |||
v1.0 | instruct | Filter | Filter_69263_I | Can you help me understand how to use the `scipy.integrate.odeint` function to solve a system of differential equations in Python? | import numpy as np
from scipy.integrate import odeint
def model(z, t):
x, y = z
dxdt = -y
dydt = x
return [dxdt, dydt]
def solve_oscillator(initial_conditions, t):
"""
Solves the system of differential equations for a simple harmonic oscillator.
Parameters:
initial_conditions (lis... | import numpy as np
from solution import solve_oscillator
def test_solve_oscillator_initial_conditions():
initial_conditions = [1, 0]
t = np.linspace(0, 10, 100)
solutions = solve_oscillator(initial_conditions, t)
assert solutions[0, 0] == 1
assert solutions[0, 1] == 0
def test_solve_oscillator_sha... | [
{
"docstring": null,
"function_declaration": "def model(z, t):",
"function_name": "model",
"parameter_list": "(z, t)"
},
{
"docstring": "Solves the system of differential equations for a simple harmonic oscillator.\n\nParameters:\ninitial_conditions (list): [x0, y0], initial conditions for x... | [
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 numpy as np\nfrom scipy.integrate import odeint\n\ndef system(y, t):\n y1, y2 = y\n dydt = [-y1 + y2, -y1 - y2]\n return dydt\n\ndef solve_ode():\n # Initial conditions\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00069263",
"row_id": 69263,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140342']"
} | 0.344468 | Filter_69263 | I | [
"model",
"solve_oscillator"
] | 2 | [
[
"solve_oscillator",
"model"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 303fec72e240c750e875e58704aab161fc7d33da | 5c7f7955e49c46a3aebb779e8ec9dfd492432c68 | |||
v1.0 | instruct | Filter | Filter_69387_I | Given a list of strings and a target string, write a function to find the shortest substring in the list that contains all characters of the target string. If no such substring exists, return an empty string. The function should be efficient and consider all possible substrings only once. | def contains_all_chars(s: str, target: str) -> bool:
from collections import Counter
target_count = Counter(target)
s_count = Counter(s)
for char in target_count:
if target_count[char] > s_count[char]:
return False
return True
def shortest_substring(lst, target):
m... | from solution import shortest_substring
def test_shortest_substring_found():
lst = ["abcdef", "abac", "defabc", "cab"]
target = "abc"
assert shortest_substring(lst, target) == "abc"
def test_shortest_substring_not_found():
lst = ["abcdef", "abac", "defab"]
target = "xyz"
assert shortest_substr... | [
{
"docstring": null,
"function_declaration": "def contains_all_chars(s, target):",
"function_name": "contains_all_chars",
"parameter_list": "(s, target)"
},
{
"docstring": null,
"function_declaration": "def shortest_substring(lst, target):",
"function_name": "shortest_substring",
... | [
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": "from collections import Counter\n\ndef shortest_substring_with_target(strings, target):\n \"\"\"\n Find the shortest substring in the list that contains all characters of the target stri... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00069387",
"row_id": 69387,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140602']"
} | 0.684981 | Filter_69387 | I | [
"contains_all_chars",
"shortest_substring"
] | 2 | [
[
"shortest_substring",
"contains_all_chars"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6f559773421969c39ac74a717bc07e98a1a94b92 | 2337340e3efd849381d41398ca8ea8e3a87446b2 | |||
v1.0 | instruct | Filter | Filter_69531_I | Write a Python script that calculates the Moving Average Convergence Divergence (MACD) and the Relative Strength Index (RSI) for a given set of stock prices. The script should take a list of closing prices as input and output the MACD line, the signal line, and the RSI value for each day. The MACD is calculated using a... | import numpy as np
def ema(values, window):
"""
Calculate the Exponential Moving Average (EMA).
"""
weights = np.exp(np.linspace(-1., 0., window))
weights /= weights.sum()
a = np.convolve(values, weights, mode='full')[:len(values)]
a[:window] = a[window]
return a
def macd(pri... | from solution import calculate_indicators
def test_macd_length():
prices = [10, 12, 11, 12, 14, 13, 11, 10, 12, 13, 15, 17, 19, 22, 20, 18, 17, 16, 14, 13, 14, 16, 18, 20, 21, 23, 24, 26]
macd_line, signal_line, rsi_values = calculate_indicators(prices)
assert len(macd_line) == len(prices)
assert len(s... | [
{
"docstring": "Calculate the Exponential Moving Average (EMA).",
"function_declaration": "def ema(values, window):",
"function_name": "ema",
"parameter_list": "(values, window)"
},
{
"docstring": "Calculate the MACD and Signal line for given stock prices.",
"function_declaration": "def ... | [
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef ema(prices, period):\n \"\"\"\n Calculates the Exponential Moving Average (EMA) for a given period.\n \"\"\"\n ema_values = []\n multiplier = 2 / (peri... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00069531",
"row_id": 69531,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140893']"
} | 0.492015 | Filter_69531 | I | [
"ema",
"macd",
"rsi",
"calculate_indicators"
] | 4 | [
[
"calculate_indicators",
"macd"
],
[
"calculate_indicators",
"rsi"
],
[
"macd",
"ema"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 832c8994119649ce6b1ec57c9f1c6fc20d43fc52 | 6177bc280caa1bca462859fa9a0399928e11c6fd | |||
v1.0 | instruct | Filter | Filter_69557_I | Can you provide a Python code to implement the k-means clustering algorithm from scratch without using any external libraries like NumPy or scikit-learn? | import random
import math
def euclidean_distance(point1, point2):
return math.sqrt(sum((i - j) ** 2 for i, j in zip(point1, point2)))
def initialize_centroids(data, k):
return random.sample(data, k)
def assign_clusters(data, centroids):
clusters = {}
for point in data:
distances = [euclidean_... | from solution import k_means
def test_k_means_single_cluster():
data = [(1, 1), (1, 2), (2, 1), (2, 2)]
k = 1
centroids, clusters = k_means(data, k)
assert len(centroids) == 1
assert len(clusters) == 1
for point in data:
assert point in clusters[0]
def test_k_means_two_clusters():
... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def initialize_centroids(data, k):",
"function_name": "initialize_centr... | [
0,
0,
0,
0,
1,
1,
0,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef initialize_centroids(points, k):\n \"\"\" Randomly initialize centroids. \"\"\"\n centroids = random.sample(points, k)\n return centroids\n\ndef assign_points_to_... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00069557",
"row_id": 69557,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140943']"
} | 0.605219 | Filter_69557 | I | [
"euclidean_distance",
"initialize_centroids",
"assign_clusters",
"compute_centroids",
"k_means"
] | 5 | [
[
"assign_clusters",
"euclidean_distance"
],
[
"k_means",
"assign_clusters"
],
[
"k_means",
"compute_centroids"
],
[
"k_means",
"initialize_centroids"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 76990eb12827e703891b34df461a6329e84bca36 | 36e322826567bb5fb02f399362e98bacd32cfa68 | |||
v1.0 | instruct | Filter | Filter_69561_I | I have a project where I need to create a simple REPL for a programming language in Python. A REPL is a Read-Eval-Print Loop, which reads input from the user, evaluates it, and prints the result. How can I create a basic REPL for a custom simple programming language in Python? | def simple_eval(expression):
"""
Evaluates a simple mathematical expression.
For now, it only supports basic arithmetic operations: +, -, *, /.
"""
try:
# Using eval in a controlled environment for simplicity.
# WARNING: eval is dangerous and should not be used with untrusted input.
... | import builtins
from solution import simple_eval
def test_simple_eval_addition():
assert simple_eval("2 + 3") == 5
def test_simple_eval_subtraction():
assert simple_eval("10 - 4") == 6
def test_simple_eval_multiplication():
assert simple_eval("3 * 4") == 12
def test_simple_eval_division():
assert si... | [
{
"docstring": "Evaluates a simple mathematical expression.\nFor now, it only supports basic arithmetic operations: +, -, *, /.",
"function_declaration": "def simple_eval(expression):",
"function_name": "simple_eval",
"parameter_list": "(expression)"
},
{
"docstring": "A Read-Eval-Print Loop... | [
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": "def simple_eval(expression):\n \"\"\"\n A simple evaluation function for a custom toy language.\n For this example, it can evaluate simple arithmetic expressions.\n \"\"\"\n try... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00069561",
"row_id": 69561,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140953']"
} | 0.38516 | Filter_69561 | I | [
"simple_eval",
"simple_repl"
] | 2 | [
[
"simple_repl",
"simple_eval"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 790a20049a50a7b7b4ff6fb2b23b601ee271c5d6 | 4b11768f0ece26c3dfecef688dc71ab7e5e1241f | |||
v1.0 | instruct | Filter | Filter_69643_I | Can you provide a Python code to implement the minimax algorithm for the game of Tic Tac Toe? | def is_winner(board, player):
"""
Check if the player has won the game.
"""
win_conditions = [
[board[0][0], board[0][1], board[0][2]],
[board[1][0], board[1][1], board[1][2]],
[board[2][0], board[2][1], board[2][2]],
[board[0][0], board[1][0], board[2][0]],
[boar... | import pytest
from solution import is_winner, is_draw, minimax, find_best_move
def test_is_winner():
board1 = [
['X', 'X', 'X'],
['-', 'O', '-'],
['O', '-', 'O']
]
board2 = [
['O', 'X', 'X'],
['-', 'O', '-'],
['O', '-', 'O']
]
board3 = [
['O',... | [
{
"docstring": "Check if the player has won the game.",
"function_declaration": "def is_winner(board, player):",
"function_name": "is_winner",
"parameter_list": "(board, player)"
},
{
"docstring": "Check if the game is a draw.",
"function_declaration": "def is_draw(board):",
"functio... | [
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": "def minimax(board, depth, is_maximizing, player, opponent):\n \"\"\"\n Implement the minimax algorithm for Tic Tac Toe.\n\n :param board: The current state of the board, a list of lis... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00069643",
"row_id": 69643,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141115']"
} | 0.476224 | Filter_69643 | I | [
"is_winner",
"is_draw",
"minimax",
"find_best_move"
] | 4 | [
[
"find_best_move",
"minimax"
],
[
"minimax",
"is_draw"
],
[
"minimax",
"is_winner"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 3a6eead61c7da5fc7f0b4a0f07b6fdff60f508c6 | f49361d626b51596b6031d42dc75cd6e77058285 | |||
v1.0 | instruct | Filter | Filter_69909_I | I want to create a simple web application using Flask, which includes a form where users can upload images and save them on the server. How can I do this? | from flask import Flask, request, redirect, url_for, render_template
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
def allowed_file(filename... | import pytest
import os
from werkzeug.datastructures import FileStorage
from solution import app, UPLOAD_FOLDER, allowed_file
def test_allowed_file():
assert allowed_file('test.jpg') == True
assert allowed_file('test.jpeg') == True
assert allowed_file('test.png') == True
assert allowed_file('test.gif')... | [
{
"docstring": null,
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def upload_file():",
"function_name": "upload_file",
"parameter_list": "()"
},
{
"d... | [
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": "from flask import Flask, request, redirect, url_for, render_template\nimport os\n\napp = Flask(__name__)\nUPLOAD_FOLDER = 'uploads/'\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n# Ensure th... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00069909",
"row_id": 69909,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141650']"
} | 0.44067 | Filter_69909 | I | [
"allowed_file",
"upload_file",
"uploaded_file"
] | 3 | [
[
"upload_file",
"allowed_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask",
"werkzeug"
] | false | 5e130dd7ea53396a1040bc79e84f867e40311dad | 231b85066cc30c3e018da440da9cd7756a3cb4f0 | |||
v1.0 | instruct | Filter | Filter_70020_I | Can you provide a Python code snippet to simulate a simple dice game where a player rolls two dice and wins if the sum is 7 or 11? Otherwise, the player loses. The game should run for 100 trials and print the win rate. | import random
def roll_dice():
return random.randint(1, 6), random.randint(1, 6)
def simulate_game():
dice1, dice2 = roll_dice()
total = dice1 + dice2
return total == 7 or total == 11
def simulate_trials(num_trials=100):
wins = 0
for _ in range(num_trials):
if simulate_game():
... | from solution import roll_dice, simulate_game, simulate_trials
def test_roll_dice():
for _ in range(1000): # Run many trials to ensure distribution
dice1, dice2 = roll_dice()
assert 1 <= dice1 <= 6
assert 1 <= dice2 <= 6
def test_simulate_game():
random.seed(0) # Set seed for reprodu... | [
{
"docstring": null,
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def simulate_game():",
"function_name": "simulate_game",
"parameter_list": "()"
},
{
"docstring": null,
... | [
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 random\n\ndef roll_dice():\n \"\"\"\n Simulate rolling two dice and return their sum.\n \"\"\"\n die1 = random.randint(1, 6)\n die2 = random.randint(1, 6)\n return die... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00070020",
"row_id": 70020,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141891']"
} | 0.510981 | Filter_70020 | I | [
"roll_dice",
"simulate_game",
"simulate_trials"
] | 3 | [
[
"simulate_game",
"roll_dice"
],
[
"simulate_trials",
"simulate_game"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7b7a088e52923ca3ebc85f59d461397d21d45246 | d79994f0060bf2b79d508b3dc22c5ec2bd45cce8 | |||
v1.0 | instruct | Filter | Filter_70074_I | How can I implement an alarm feature in my Python application that triggers every 2 minutes to check the server status? | import time
def check_server_status():
"""
Dummy function to check server status.
Advanced logic for communicating with the server should be implemented here.
For now, it just prints a message.
"""
print("Checking server status...")
def start_alarm(interval_minutes=2):
"""
Starts an al... | from solution import check_server_status, start_alarm
import pytest
import threading
def test_check_server_status(capsys):
check_server_status()
captured = capsys.readouterr()
assert "Checking server status..." in captured.out
def test_start_alarm(monkeypatch):
# Mock time.sleep to avoid actual delay
... | [
{
"docstring": "Dummy function to check server status.\nAdvanced logic for communicating with the server should be implemented here.\nFor now, it just prints a message.",
"function_declaration": "def check_server_status():",
"function_name": "check_server_status",
"parameter_list": "()"
},
{
... | [
0,
0,
0,
0,
1,
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 time\nimport requests\n\ndef check_server_status():\n \"\"\"\n Function to check the server status.\n \"\"\"\n try:\n response = requests.get(\"http://yourserver.com/... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00070074",
"row_id": 70074,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141993']"
} | 0.569755 | Filter_70074 | I | [
"check_server_status",
"start_alarm"
] | 2 | [
[
"start_alarm",
"check_server_status"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bdee5f0d8a194725c8af320eeb72172119d17c4b | d732849b81149deb91bba79211610ee500f10638 | |||
v1.0 | instruct | Filter | Filter_70424_I | Write a Python script that automatically installs and sets up a Django project using virtual environments. The script should include steps to create a new project, install Django, and run the server. Additionally, include error handling to ensure the process runs smoothly. | import os
import subprocess
import sys
def run_command(command):
"""Run a shell command and return the output."""
try:
result = subprocess.run(command, check=True, shell=True, text=True, capture_output=True)
return result.stdout
except subprocess.CalledProcessError as e:
print(f"Err... | import os
import subprocess
from unittest.mock import patch, call
@patch('subprocess.run')
def test_create_virtualenv(mock_run):
from solution import create_virtualenv
mock_run.return_value.stdout = "Virtualenv created"
assert create_virtualenv('venv') == "Virtualenv created"
mock_run.assert_called_wit... | [
{
"docstring": "Run a shell command and return the output.",
"function_declaration": "def run_command(command):",
"function_name": "run_command",
"parameter_list": "(command)"
},
{
"docstring": "Create a virtual environment.",
"function_declaration": "def create_virtualenv(env_name):",
... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport subprocess\nimport sys\n\ndef is_venv():\n return (hasattr(sys, 'real_prefix') or \n (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))\n\ndef cre... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00070424",
"row_id": 70424,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142708']"
} | 0.388894 | Filter_70424 | I | [
"run_command",
"create_virtualenv",
"install_django",
"start_django_project",
"run_django_server",
"setup_django_project"
] | 6 | [
[
"create_virtualenv",
"run_command"
],
[
"install_django",
"run_command"
],
[
"run_django_server",
"run_command"
],
[
"setup_django_project",
"create_virtualenv"
],
[
"setup_django_project",
"install_django"
],
[
"setup_django_project",
"run_djang... | 8 | [] | false | [] | false | pytest | true | [] | true | 3223fa6857ce22305400e59bba3a075dee834c7d | f2154bed3904d3294947b0c20ea1d52ca92ed179 | |||
v1.0 | instruct | Filter | Filter_70477_I | I need a Python script to process a CSV file and calculate the average salary from it. The CSV file has columns: Name, Department, Salary. The salary is stored as a string with a dollar sign and commas (e.g., "$40,000"). How can I handle the salary format and calculate the average? | import csv
def process_salary(salary_str):
"""
Convert a salary string in the format '$XX,XXX' to a float.
"""
return float(salary_str.replace("$", "").replace(",", ""))
def calculate_average_salary(csv_file_path):
"""
Calculate the average salary from a CSV file.
Parameters:
csv_file... | from solution import process_salary, calculate_average_salary
import csv
import os
def test_process_salary():
assert process_salary("$40,000") == 40000.0
assert process_salary("$1,000,000") == 1000000.0
assert process_salary("$500") == 500.0
def test_calculate_average_salary():
# Create a temporary CS... | [
{
"docstring": "Convert a salary string in the format '$XX,XXX' to a float.",
"function_declaration": "def process_salary(salary_str):",
"function_name": "process_salary",
"parameter_list": "(salary_str)"
},
{
"docstring": "Calculate the average salary from a CSV file.\n\nParameters:\ncsv_fi... | [
0,
0,
0,
0,
1,
1,
1,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\n\ndef process_csv(file_path):\n \"\"\"\n Reads a CSV file and calculates the average salary.\n\n Parameters:\n - file_path: str, path to the CSV file\n\n Returns:\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00070477",
"row_id": 70477,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142803']"
} | 0.516224 | Filter_70477 | I | [
"process_salary",
"calculate_average_salary"
] | 2 | [
[
"calculate_average_salary",
"process_salary"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cab0b20f850ad487789a925bb1307c51743df641 | 37dae2abccc3b0bd7de915def1dac0a7036c74cb | |||
v1.0 | instruct | Filter | Filter_70837_I | Please provide a detailed explanation of how to implement a gradient descent algorithm for linear regression in Python. This should include the necessary code snippets for each step, along with a brief explanation of the code. | import numpy as np
def compute_cost(X, y, theta):
"""
Compute the cost for linear regression.
"""
m = len(y) # Number of training examples
predictions = X.dot(theta)
cost = (1 / (2 * m)) * np.sum(np.square(predictions - y))
return cost
def gradient_descent(X, y, theta, alpha, num_iters):
... | from solution import compute_cost, gradient_descent, linear_regression_gradient_descent
import numpy as np
def test_compute_cost():
X = np.array([[1, 1], [1, 2], [1, 3]])
y = np.array([1, 2, 3])
theta = np.array([0, 1])
assert np.isclose(compute_cost(X, y, theta), 0)
def test_gradient_descent():
X... | [
{
"docstring": "Compute the cost for linear regression.",
"function_declaration": "def compute_cost(X, y, theta):",
"function_name": "compute_cost",
"parameter_list": "(X, y, theta)"
},
{
"docstring": "Perform gradient descent to learn theta.",
"function_declaration": "def gradient_desce... | [
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 numpy as np\n\ndef predict(X, theta):\n \"\"\"\n Predict the y values given the input features X and parameters theta.\n \n Parameters:\n X : numpy.ndarray\n The i... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00070837",
"row_id": 70837,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143538']"
} | 0.478235 | Filter_70837 | I | [
"compute_cost",
"gradient_descent",
"linear_regression_gradient_descent"
] | 3 | [
[
"gradient_descent",
"compute_cost"
],
[
"linear_regression_gradient_descent",
"gradient_descent"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 999f7913080518b5cfa116b6bf1fc7e816bbaee3 | 2df9d8a8f83645fc868db64748415b9bf6251c9a | |||
v1.0 | instruct | Filter | Filter_71037_I | I want to develop a Python package that can be installed with pip and can handle multi-threaded data processing. How can I structure my package and use multi-threading effectively in it? | from concurrent.futures import ThreadPoolExecutor
def process_data(data):
"""
Function to simulate data processing.
"""
# Simulate some data processing task
return [element * 2 for element in data]
def parallel_process(data_chunks, num_threads=4):
"""
Function to process data in parallel u... | from solution import process_data, parallel_process
def test_process_data():
assert process_data([1, 2, 3]) == [2, 4, 6]
def test_parallel_process():
data_chunks = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
expected = [[2, 4, 6], [8, 10, 12], [14, 16, 18]]
assert parallel_process(data_chunks, num_threads=2) ==... | [
{
"docstring": "Function to simulate data processing.",
"function_declaration": "def process_data(data):",
"function_name": "process_data",
"parameter_list": "(data)"
},
{
"docstring": "Function to process data in parallel using multithreading.",
"function_declaration": "def parallel_pro... | [
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# mypackage/core.py\ndef process_data(data):\n \"\"\"\n Simulates data processing and returns the processed data.\n \"\"\"\n return data ** 2\n\n# mypackage/processing.py\nfrom thr... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00071037",
"row_id": 71037,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143965']"
} | 0.467217 | Filter_71037 | I | [
"process_data",
"parallel_process"
] | 2 | [
[
"parallel_process",
"process_data"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 777f2037e38edf77698d672bdcfe13ae45824c2d | 4abfa97af0ec529a47eef349351698f8c0b48e24 | |||
v1.0 | instruct | Filter | Filter_71646_I | Can you provide a Python code to generate a web page from a Markdown file using the `markdown` library? | import markdown
def markdown_to_html(markdown_content):
"""
Converts markdown content to HTML.
Args:
markdown_content (str): The markdown content to be converted.
Returns:
str: The converted HTML content.
"""
html_content = markdown.markdown(markdown_content)
return html_c... | from solution import markdown_to_html, save_html_to_file, generate_web_page_from_markdown
import os
def test_markdown_to_html():
markdown_content = "# Title\n\nThis is a **bold** text."
expected_html_content = "<h1>Title</h1>\n<p>This is a <strong>bold</strong> text.</p>"
assert markdown_to_html(markdown_c... | [
{
"docstring": "Converts markdown content to HTML.\n\nArgs:\nmarkdown_content (str): The markdown content to be converted.\n\nReturns:\nstr: The converted HTML content.",
"function_declaration": "def markdown_to_html(markdown_content):",
"function_name": "markdown_to_html",
"parameter_list": "(markd... | [
0,
0,
0,
1,
1,
1,
1,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import markdown\n\ndef generate_web_page(markdown_content, output_file_path):\n \"\"\"\n Converts a Markdown string to an HTML string and writes it to an output file.\n\n Parameters:\... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00071646",
"row_id": 71646,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145238']"
} | 0.490398 | Filter_71646 | I | [
"markdown_to_html",
"save_html_to_file",
"generate_web_page_from_markdown"
] | 3 | [
[
"generate_web_page_from_markdown",
"markdown_to_html"
],
[
"generate_web_page_from_markdown",
"save_html_to_file"
]
] | 2 | [] | false | [] | false | pytest | true | [
"markdown"
] | false | 1fa9d6364210be7b7e082ba9b33b5cd1170248a5 | 4159f3064ccd42f22e1ea2cb8471239e8dde60d5 | |||
v1.0 | instruct | Filter | Filter_71667_I | I need a Python script to download files from a list of URLs. The script should handle exceptions and create a directory for each URL's host domain if it doesn't exist. It should also save the downloaded files in the corresponding directory named after the domain. For example, files from `http://example.com/file1.txt` ... | import os
import requests
from urllib.parse import urlparse
def download_file(url):
"""
Downloads a file from the given URL and saves it into a directory named after the domain of the URL.
"""
try:
# Parse the URL to get the domain
parsed_url = urlparse(url)
domain = parsed_url.... | import os
import pytest
from unittest.mock import patch, mock_open
from solution import download_file, download_files_from_list
URL_LIST = [
"http://example.com/file1.txt",
"http://anotherdomain.com/file2.txt"
]
def test_download_file():
with patch("solution.requests.get") as mock_get:
mock_get.re... | [
{
"docstring": "Downloads a file from the given URL and saves it into a directory named after the domain of the URL.",
"function_declaration": "def download_file(url):",
"function_name": "download_file",
"parameter_list": "(url)"
},
{
"docstring": "Downloads files from a list of URLs.",
... | [
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 os\nimport requests\nfrom urllib.parse import urlparse\n\ndef download_file(url):\n try:\n parsed_url = urlparse(url)\n domain = parsed_url.netloc\n \n # ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00071667",
"row_id": 71667,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145283']"
} | 0.612838 | Filter_71667 | I | [
"download_file",
"download_files_from_list"
] | 2 | [
[
"download_files_from_list",
"download_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 6ffe44139da0c9bb3c4a54bde248ec0f26f29ba6 | 0bb132a52ecd1b70fcdffe987aa15110b2643a7a | |||
v1.0 | instruct | Filter | Filter_71731_I | Can I convert a string to an integer in Python using a GUI application? | import tkinter as tk
from tkinter import messagebox
def convert_string_to_int(input_str):
"""
Converts the given string to an integer. Returns the integer
if conversion is successful, else raises a ValueError.
"""
return int(input_str)
def on_convert_button_click(entry, result_label):
"""Handl... | import pytest
from solution import convert_string_to_int
def test_convert_string_to_int_valid():
assert convert_string_to_int("123") == 123
assert convert_string_to_int("0") == 0
assert convert_string_to_int("-456") == -456
def test_convert_string_to_int_invalid():
with pytest.raises(ValueError):
... | [
{
"docstring": "Converts the given string to an integer. Returns the integer\nif conversion is successful, else raises a ValueError.",
"function_declaration": "def convert_string_to_int(input_str):",
"function_name": "convert_string_to_int",
"parameter_list": "(input_str)"
},
{
"docstring": ... | [
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 tkinter as tk\nfrom tkinter import messagebox\n\ndef convert_string_to_int(input_string):\n \"\"\"\n Converts a string to an integer. Raises ValueError if the string is not a vali... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00071731",
"row_id": 71731,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145416']"
} | 0.486932 | Filter_71731 | I | [
"convert_string_to_int",
"on_convert_button_click",
"main"
] | 3 | [
[
"on_convert_button_click",
"convert_string_to_int"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8bde143d744c8aab740657f62ae524c10bb2d22a | 31e093387ca9e8576fd34348ed61a2e12209391b | |||
v1.0 | instruct | Filter | Filter_71844_I | How can I implement flood prevention in a web application using Python and Flask? | from flask import Flask, request, jsonify
from time import time
app = Flask(__name__)
# Dictionary to store users' request data
users_requests = {}
# Define limits
LIMIT_REQUESTS = 100 # Number of allowed requests
LIMIT_TIME = 3600 # Time window in seconds (1 hour)
def is_request_allowed(user_ip):
current_tim... | import pytest
from flask import Flask, request, jsonify
from time import time, sleep
# Using the same function as in solution
app = Flask(__name__)
users_requests = {}
LIMIT_REQUESTS = 5 # Adjusted for faster testing
LIMIT_TIME = 10 # Adjusted for faster testing
def is_request_allowed(user_ip):
current_time = t... | [
{
"docstring": null,
"function_declaration": "def is_request_allowed(user_ip):",
"function_name": "is_request_allowed",
"parameter_list": "(user_ip)"
},
{
"docstring": null,
"function_declaration": "def endpoint():",
"function_name": "endpoint",
"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": "from flask import Flask, request, jsonify\nfrom flask_limiter import Limiter\nfrom flask_limiter.util import get_remote_address\n\napp = Flask(__name__)\n\n# Configure the limiting by IP addre... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00071844",
"row_id": 71844,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145637']"
} | 0.49911 | Filter_71844 | I | [
"is_request_allowed",
"endpoint"
] | 2 | [
[
"endpoint",
"is_request_allowed"
]
] | 1 | [] | false | [] | false | pytest | false | [
"flask"
] | false | 9620f2073436310af9df82f4dfff1728875fe220 | 1820cb7c08755242504408b219d90de3aca6fd22 | |||
v1.0 | instruct | Filter | Filter_71977_I | I want to create a Python script that can send an email notification whenever a new file is added to a specific directory. How can I do this? | import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import time
def send_email(subject, body, to_email):
from_email = "your_email@example.com"
from_password = "your_password"
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_emai... | import os
import time
import tempfile
import threading
from solution import send_email, monitor_directory
def test_send_email(monkeypatch):
def mock_sendmail(from_email, to_email, msg):
assert from_email == "your_email@example.com"
assert to_email == "recipient_email@example.com"
assert "Ne... | [
{
"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 monitor_directory(directory, to_email):",
"function_name": "monit... | [
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 os\nimport time\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nfrom email import encoders\n... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00071977",
"row_id": 71977,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145928']"
} | 0.461846 | Filter_71977 | I | [
"send_email",
"monitor_directory"
] | 2 | [
[
"monitor_directory",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 825f20a7d8dd68411c39cdd46b072124f75222e2 | f570267c771ce273e304ad999fe3b462e35c0a79 | |||
v1.0 | instruct | Filter | Filter_71998_I | How can I create a custom JSON Schema validator in Python that supports a specific keyword, say "customKeyword", which validates that a string property must start with a specific prefix? | import jsonschema
from jsonschema import Draft7Validator, validators
# Create a custom validator class with the "customKeyword" to ensure strings start with a specific prefix
def customValidator(validator, customKeyword, instance, schema):
if not isinstance(instance, str):
return
if not instance.s... | from solution import validate_json
def test_validate_json_no_errors():
schema = {
"type": "object",
"properties": {
"name": {"type": "string", "customKeyword": "prefix_"}
},
"required": ["name"]
}
instance = {"name": "prefix_John"}
errors = validate_json(ins... | [] | [
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 jsonschema\nfrom jsonschema import Draft7Validator, ValidationError, validators\n\n# Extending the existing Draft7Validator to handle the custom keyword\ndef custom_validator(validator,... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00071998",
"row_id": 71998,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145969']"
} | 0.508586 | Filter_71998 | I | [
"customValidator",
"extend_with_custom_keyword",
"validate_json"
] | 3 | [
[
"extend_with_custom_keyword",
"customValidator"
]
] | 1 | [] | false | [] | false | pytest | true | [
"jsonschema"
] | false | 341fb7ee972e9039a09eac227c0f0e1307885676 | 4538a288395fdb8c4a0cd8355b071398c7fdc98f | |||
v1.0 | instruct | Filter | Filter_72454_I | Can you explain how to implement the k-means clustering algorithm from scratch in Python? | import numpy as np
def initialize_centroids(X, k):
"""
Randomly initialize centroids by choosing k unique data points from X.
Parameters:
X (numpy ndarray): The dataset (n_samples, n_features).
k (int): The number of clusters.
Returns:
numpy ndarray: The initialized centroids (k, ... | import pytest
import numpy as np
from solution import initialize_centroids, assign_clusters, update_centroids, kmeans
def test_initialize_centroids():
np.random.seed(0)
X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
k = 2
centroids = initialize_centroids(X, k)
assert centroids.shape == (k, 2)
... | [
{
"docstring": "Randomly initialize centroids by choosing k unique data points from X.\n\nParameters:\nX (numpy ndarray): The dataset (n_samples, n_features).\nk (int): The number of clusters.\n\nReturns:\nnumpy ndarray: The initialized centroids (k, n_features).",
"function_declaration": "def initialize_ce... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
1
] | 3 | hard | 0.3 | {
"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 \"\"\"Randomly initialize the centroids from the dataset X\"\"\"\n indices = np.random.choice(X.shape[0], k, replace=False)\n r... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00072454",
"row_id": 72454,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146861']"
} | 0.627643 | Filter_72454 | 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 | 05fc3ee090b25fa1c7c7ef084e9e70a8b564a36a | 0c400f06df6c9d76906b0c5e64e82454fe116edf | |||
v1.0 | instruct | Filter | Filter_72471_I | Hello, how can I create a Python script that monitors system temperature and logs it to a file every minute? On a Linux system? | import time
import datetime
import os
def get_cpu_temperature():
"""
Gets the CPU temperature from the system.
"""
# This path is specific to the system. Adjust if necessary.
temp_file = "/sys/class/thermal/thermal_zone0/temp"
try:
with open(temp_file, 'r') as file:
tem... | from solution import get_cpu_temperature, log_temperature_to_file
import os
def test_get_cpu_temperature():
temp = get_cpu_temperature()
assert isinstance(temp, float)
def test_log_temperature_to_file():
test_log_file = "test_temperature_log.txt"
# Ensure the file is empty before logging
if o... | [
{
"docstring": "Gets the CPU temperature from the system.",
"function_declaration": "def get_cpu_temperature():",
"function_name": "get_cpu_temperature",
"parameter_list": "()"
},
{
"docstring": "Logs the current CPU temperature to a specified log file.",
"function_declaration": "def log... | [
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 psutil\nimport time\n\ndef get_system_temperature():\n \"\"\"\n Fetches the current system temperature in Celsius.\n \"\"\"\n try:\n # psutil.sensors_temperatures ret... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00072471",
"row_id": 72471,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146890']"
} | 0.528648 | Filter_72471 | I | [
"get_cpu_temperature",
"log_temperature_to_file"
] | 2 | [
[
"log_temperature_to_file",
"get_cpu_temperature"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 00a9bf4261cdb65a6bcd9c8cda452f67b7ab09e4 | 19a8dd657523c6c18d7264fb36d2120c53c47bf1 | |||
v1.0 | instruct | Filter | Filter_72816_I | How can I implement an automatic update mechanism for my software application in Python? | import os
import sys
import requests
# Example configuration
CURRENT_VERSION = "1.0.0"
VERSION_CHECK_URL = "https://example.com/version"
UPDATE_URL = "https://example.com/download/latest"
UPDATE_FILE_PATH = "update.zip"
def check_for_update():
"""
Checks if an update is available by comparing the current vers... | def test_check_for_update(monkeypatch):
from solution import check_for_update
def mock_requests_get(url):
class MockResponse:
def __init__(self, text):
self.text = text
return MockResponse("1.0.1") # Assume latest version is "1.0.1"
monkeypatch.setattr("so... | [
{
"docstring": "Checks if an update is available by comparing the current version with the latest version.",
"function_declaration": "def check_for_update():",
"function_name": "check_for_update",
"parameter_list": "()"
},
{
"docstring": "Downloads the update file from the update URL.",
... | [
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 os\nimport sys\nimport subprocess\n\ndef update_software(repository_url, branch='main'):\n \"\"\"\n Updates the software by pulling the latest changes from the specified git repos... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00072816",
"row_id": 72816,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147602']"
} | 0.411597 | Filter_72816 | I | [
"check_for_update",
"download_update",
"install_update",
"restart_application",
"update_application"
] | 5 | [
[
"update_application",
"check_for_update"
],
[
"update_application",
"download_update"
],
[
"update_application",
"install_update"
],
[
"update_application",
"restart_application"
]
] | 4 | [] | false | [] | false | pytest | true | [
"requests"
] | false | c3ae8babc00153a54f6355b90a992a0a696d8eba | f5379fab79a74892cd1ac75da5e3ebf15e373f75 | |||
v1.0 | instruct | Filter | Filter_72912_I | Can you write a Python code snippet that demonstrates how to create a simple assembly line simulation using a combination of generators and coroutines? In this simulation, we want to simulate the process of producing widgets, where widgets go through three stages: assembly, quality check, and packaging. Each stage can ... | def assembly_stage(widget_id):
"""
Generator for the assembly stage.
Takes a widget id and passes it to the next stage.
"""
while True:
yield f"Widget {widget_id} assembled"
def quality_check_stage(assembled_widget):
"""
Generator for the quality check stage.
Takes an assembled ... | from solution import assembly_stage, quality_check_stage, packaging_stage, run_assembly_line
def test_assembly_stage():
assembly_gen = assembly_stage(1)
assert next(assembly_gen) == "Widget 1 assembled"
def test_quality_check_stage():
quality_check_gen = quality_check_stage("Widget 1 assembled")
asser... | [
{
"docstring": "Generator for the assembly stage.\nTakes a widget id and passes it to the next stage.",
"function_declaration": "def assembly_stage(widget_id):",
"function_name": "assembly_stage",
"parameter_list": "(widget_id)"
},
{
"docstring": "Generator for the quality check stage.\nTake... | [
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": "def raw_materials(n):\n \"\"\"\n Generator to produce raw materials.\n \"\"\"\n for i in range(n):\n yield f\"raw_material_{i}\"\n\ndef assembly_line():\n \"\"\"\n Cor... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00072912",
"row_id": 72912,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147799']"
} | 0.330919 | Filter_72912 | I | [
"assembly_stage",
"quality_check_stage",
"packaging_stage",
"run_assembly_line"
] | 4 | [
[
"run_assembly_line",
"assembly_stage"
],
[
"run_assembly_line",
"packaging_stage"
],
[
"run_assembly_line",
"quality_check_stage"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | d840148fff69d7b1498b704fdbe881be57604389 | 5ecf4be88fb486a6604cc5878508997059762348 | |||
v1.0 | instruct | Filter | Filter_72935_I | Can you provide a Python code to visualize the optimization path of a simple quadratic function using a gradient descent algorithm? | import numpy as np
import matplotlib.pyplot as plt
def quadratic_function(x):
"""
Simple quadratic function: f(x) = x^2
"""
return x**2
def gradient(x):
"""
Gradient of the simple quadratic function f(x) = x^2
"""
return 2 * x
def gradient_descent(starting_x, learning_rate, num_iterat... | from solution import quadratic_function, gradient, gradient_descent
def test_quadratic_function():
assert quadratic_function(0) == 0
assert quadratic_function(1) == 1
assert quadratic_function(-1) == 1
assert quadratic_function(2) == 4
def test_gradient():
assert gradient(0) == 0
assert gradie... | [
{
"docstring": "Simple quadratic function: f(x) = x^2",
"function_declaration": "def quadratic_function(x):",
"function_name": "quadratic_function",
"parameter_list": "(x)"
},
{
"docstring": "Gradient of the simple quadratic function f(x) = x^2",
"function_declaration": "def gradient(x):... | [
0,
0,
0,
1,
0,
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 numpy as np\nimport matplotlib.pyplot as plt\n\ndef quadratic_function(x):\n \"\"\"\n Simple quadratic function: f(x) = x^2\n \"\"\"\n return x ** 2\n\ndef gradient(x):\n ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00072935",
"row_id": 72935,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147842']"
} | 0.485781 | Filter_72935 | I | [
"quadratic_function",
"gradient",
"gradient_descent",
"plot_optimization_path"
] | 4 | [
[
"gradient_descent",
"gradient"
],
[
"plot_optimization_path",
"quadratic_function"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | b2ab7edce579a3db85658a93681fc8bd8e796906 | 7b3c9334511a9bca67208e5bb7dd70d03041bcd2 | |||
v1.0 | instruct | Filter | Filter_73300_I | How can I split a large CSV file into smaller chunks using Python? | import csv
def split_csv(file_path, chunk_size, output_prefix):
"""
Splits a large CSV file into smaller chunks.
:param file_path: The path to the large CSV file
:param chunk_size: The number of rows per chunk
:param output_prefix: The prefix for the output chunk files
"""
with open(file_p... | import os
import csv
from solution import split_csv
def create_test_csv(file_path, rows):
"""
Creates a test CSV with the specified number of rows.
:param file_path: The path to the test CSV file
:param rows: The rows to be added to the test CSV file
"""
headers = ["Header1", "Header2", "Heade... | [
{
"docstring": "Splits a large CSV file into smaller chunks.\n\n:param file_path: The path to the large CSV file\n:param chunk_size: The number of rows per chunk\n:param output_prefix: The prefix for the output chunk files",
"function_declaration": "def split_csv(file_path, chunk_size, output_prefix):",
... | [
0,
0,
0,
1,
0,
1,
1,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\n\ndef split_csv(input_file, output_prefix, chunk_size):\n \"\"\"\n Split a large CSV file into smaller chunks.\n \n Args:\n input_file (str): Path to the in... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00073300",
"row_id": 73300,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148582']"
} | 0.470115 | Filter_73300 | I | [
"split_csv",
"write_chunk"
] | 2 | [
[
"split_csv",
"write_chunk"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ad69daf9a9b383239e24e50a489e30cdf940bd9f | 521f2b32ac28777889ecdf0364d4a8dac0477a8d | |||
v1.0 | instruct | Filter | Filter_73358_I | I'm trying to create a simple financial dashboard using Python. Can you guide me through the process, including the necessary libraries and tools? | import pandas as pd
import matplotlib.pyplot as plt
def fetch_and_process_data():
"""
Fetches and processes data for the financial dashboard.
Returns a DataFrame.
"""
# For simplicity, we'll use a dummy dataset
data = {
'Date': pd.date_range(start='1/1/2023', periods=100),
'Stoc... | from solution import fetch_and_process_data, plot_financial_data
import pandas as pd
def test_fetch_and_process_data():
df = fetch_and_process_data()
assert not df.empty, "DataFrame should not be empty"
assert 'Date' in df.columns, "Date column should be present in DataFrame"
assert 'Stock_Price' ... | [
{
"docstring": "Fetches and processes data for the financial dashboard.\nReturns a DataFrame.",
"function_declaration": "def fetch_and_process_data():",
"function_name": "fetch_and_process_data",
"parameter_list": "()"
},
{
"docstring": "Plots financial data using matplotlib.",
"function... | [
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 matplotlib.pyplot as plt\nimport pandas as pd\n\ndef create_financial_dashboard(data):\n \"\"\"\n Create a simple financial dashboard which includes a line chart of stock prices.\... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00073358",
"row_id": 73358,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148723']"
} | 0.441557 | Filter_73358 | I | [
"fetch_and_process_data",
"plot_financial_data",
"display_financial_dashboard"
] | 3 | [
[
"display_financial_dashboard",
"fetch_and_process_data"
],
[
"display_financial_dashboard",
"plot_financial_data"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"pandas"
] | false | eda348dc7ce503d975ff4c49c8fc3baa65bb3c25 | 7f76518b1f656d3d79da278b7c413f0f9d3c2e05 | |||
v1.0 | instruct | Filter | Filter_73447_I | I need help transforming a biological algorithm into machine learning code. Specifically, I want to implement a genetic algorithm for a simple optimization problem using Python. Could you provide a step-by-step guide along with the Python code? | import random
def initialize_population(pop_size, chromosome_length):
"""Initialize a population with random individuals."""
return [[random.randint(0, 1) for _ in range(chromosome_length)] for _ in range(pop_size)]
def fitness_function(individual):
"""Define a fitness function to evaluate individuals."""... | from solution import initialize_population, fitness_function, select_parents, crossover, mutate, genetic_algorithm
def test_initialize_population():
pop = initialize_population(10, 5)
assert len(pop) == 10
assert all(len(ind) == 5 for ind in pop)
assert all(gene in [0, 1] for ind in pop for gene in ind... | [
{
"docstring": "Initialize a population with random individuals.",
"function_declaration": "def initialize_population(pop_size, chromosome_length):",
"function_name": "initialize_population",
"parameter_list": "(pop_size, chromosome_length)"
},
{
"docstring": "Define a fitness function to ev... | [
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 random\n\ndef initialize_population(size, chrom_length):\n population = []\n for _ in range(size):\n individual = [random.randint(0, 1) for _ in range(chrom_length)]\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00073447",
"row_id": 73447,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148941']"
} | 0.342294 | Filter_73447 | I | [
"initialize_population",
"fitness_function",
"select_parents",
"crossover",
"mutate",
"genetic_algorithm"
] | 6 | [
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"fitness_function"
],
[
"genetic_algorithm",
"initialize_population"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"select_parents"
],
[
"select_parents",
"fitness_function... | 6 | [] | false | [] | false | pytest | true | [] | true | 7bb210c12f89717edf1afed9c8efbdab171975b9 | 333dabd43ac001c5c68c4206818f0e1b13654e94 | |||
v1.0 | instruct | Filter | Filter_73614_I | How can I create a Python script that periodically checks the status of a website and logs the results for future analysis? | import time
import requests
import logging
# Set up logging
logging.basicConfig(filename='website_status.log', level=logging.INFO, format='%(asctime)s - %(message)s')
def check_website_status(url):
"""
Checks the status of a website.
Parameters:
url (str): The URL of the website to check.
... | import pytest
from unittest.mock import patch, MagicMock
from solution import check_website_status
def test_check_website_status_up():
with patch('requests.get') as mock_get:
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.ok = True
mock_get.return_value = ... | [
{
"docstring": "Checks the status of a website.\n\nParameters:\nurl (str): The URL of the website to check.\n\nReturns:\ndict: A dictionary containing the URL, status code, and status.",
"function_declaration": "def check_website_status(url):",
"function_name": "check_website_status",
"parameter_lis... | [
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 requests\nimport logging\nimport time\n\ndef check_website_status(url, interval):\n \"\"\"\n Periodically checks the status of the website and logs the results.\n\n :param url:... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00073614",
"row_id": 73614,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149274']"
} | 0.554074 | Filter_73614 | I | [
"check_website_status",
"log_website_status"
] | 2 | [
[
"log_website_status",
"check_website_status"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | e450cd29f12e07f2fed8d8d29d4ea7dae93e8c81 | f8ae24a12b396ee31586b696c396fed43d314060 | |||
v1.0 | instruct | Filter | Filter_73649_I | Can you provide a Python code to simulate the forward kinematics of a 6-DoF robotic arm using Denavit-Hartenberg (DH) parameters? | import numpy as np
def dh_transform(a, alpha, d, theta):
"""
Returns the transformation matrix based on DH parameters.
Parameters:
a -- Link length
alpha -- Link twist
d -- Link offset
theta -- Joint angle
Returns:
Transformation matrix (4x4 numpy array)
"""
return... | import numpy as np
from solution import dh_transform, forward_kinematics
def test_dh_transform():
a, alpha, d, theta = 1, 0, 1, np.pi/2
expected = np.array([
[0, -1, 0, 1],
[1, 0, 0, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]
])
result = dh_transform(a, alpha, d, theta)
assert n... | [
{
"docstring": "Returns the transformation matrix based on DH parameters.\n\nParameters:\na -- Link length\nalpha -- Link twist\nd -- Link offset\ntheta -- Joint angle\n\nReturns:\nTransformation matrix (4x4 numpy array)",
"function_declaration": "def dh_transform(a, alpha, d, theta):",
"function_name":... | [
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\n\ndef dh_transformation_matrix(theta, d, a, alpha):\n \"\"\"\n Computes the Denavit-Hartenberg transformation matrix.\n :param theta: Joint angle (theta_i)\n :p... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00073649",
"row_id": 73649,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149344']"
} | 0.322029 | Filter_73649 | I | [
"dh_transform",
"forward_kinematics"
] | 2 | [
[
"forward_kinematics",
"dh_transform"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | a11df17df84a84b9233707f0a7ead514a18381c1 | d298d30c9dc81ecff39c89db8c79fb6180caa082 | |||
v1.0 | instruct | Filter | Filter_73751_I | How can I create a simple web application using Flask in Python that allows users to upload images and convert them to grayscale? | from flask import Flask, request, redirect, url_for, send_file
from werkzeug.utils import secure_filename
import os
from PIL import Image
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads/'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CO... | import os
import pytest
from io import BytesIO
from PIL import Image
from solution import app, allowed_file, UPLOAD_FOLDER
@pytest.fixture
def client():
app.config['TESTING'] = True
client = app.test_client()
yield client
def test_allowed_file():
assert allowed_file("image.png") == True
assert all... | [
{
"docstring": null,
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def upload_form():",
"function_name": "upload_form",
"parameter_list": "()"
},
{
"d... | [
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, request, redirect, url_for\nfrom werkzeug.utils import secure_filename\nimport os\nfrom PIL import Image\n\nUPLOAD_FOLDER = 'uploads/'\nGRAYSCALE_FOLD... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00073751",
"row_id": 73751,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149579']"
} | 0.442406 | Filter_73751 | I | [
"allowed_file",
"upload_form",
"upload_image",
"convert_image"
] | 4 | [
[
"upload_image",
"allowed_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"PIL",
"flask",
"werkzeug"
] | false | df334b0265a720b162263c02012809ebde30b975 | 3e29ffc27c55a5e3317ad5170d061033eeba4a1e | |||
v1.0 | instruct | Filter | Filter_73828_I | Can you explain how the parallel merge sort algorithm works, and provide a simple implementation in Python using the multiprocessing library? | import multiprocessing
def merge(left, right):
"""
Merge two sorted lists into a single sorted list.
"""
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.appen... | from solution import parallel_merge_sort
def test_parallel_merge_sort_empty():
assert parallel_merge_sort([]) == []
def test_parallel_merge_sort_single_element():
assert parallel_merge_sort([1]) == [1]
def test_parallel_merge_sort_sorted():
arr = [1, 2, 3, 4, 5]
assert parallel_merge_sort(arr) == arr... | [
{
"docstring": "Merge two sorted lists into a single sorted list.",
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
},
{
"docstring": "Perform a parallel merge sort on the provided list.",
"function_declaration": "def paralle... | [
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": "from multiprocessing import Process, Manager\n\n\ndef merge_sort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n L = arr[:mid]\n R = arr[mid:]\n\n # Creating pr... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00073828",
"row_id": 73828,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149744']"
} | 0.49039 | Filter_73828 | I | [
"merge",
"parallel_merge_sort"
] | 2 | [
[
"parallel_merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0028460b329b7ccd6d8ea989050899bf1e7d9de4 | 00f02d5762c172a5bee233503c2fefa65e16c2d7 | |||
v1.0 | instruct | Filter | Filter_73844_I | How can I create a Connect Four game application using Python with a graphical user interface (GUI)? | import tkinter as tk
from tkinter import messagebox
ROW_COUNT = 6
COLUMN_COUNT = 7
def create_board():
board = []
for _ in range(ROW_COUNT):
board.append([0] * COLUMN_COUNT)
return board
def drop_piece(board, row, col, piece):
board[row][col] = piece
def is_valid_location(board, col):
re... | import pytest
from solution import create_board, drop_piece, is_valid_location, get_next_open_row, winning_move
def test_create_board():
board = create_board()
assert len(board) == 6
assert len(board[0]) == 7
assert all(all(cell == 0 for cell in row) for row in board)
def test_drop_piece():
board ... | [
{
"docstring": null,
"function_declaration": "def create_board():",
"function_name": "create_board",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def drop_piece(board, row, col, piece):",
"function_name": "drop_piece",
"parameter_list": "(board, row, co... | [
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 tkinter as tk\nfrom tkinter import messagebox\n\nROWS = 6\nCOLS = 7\nEMPTY = 0\nPLAYER_ONE = 1\nPLAYER_TWO = 2\n\nclass ConnectFour:\n def __init__(self, root):\n self.root = ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00073844",
"row_id": 73844,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149773']"
} | 0.357643 | Filter_73844 | I | [
"create_board",
"drop_piece",
"is_valid_location",
"get_next_open_row",
"print_board",
"winning_move",
"create_game_gui"
] | 7 | [
[
"create_game_gui",
"create_board"
],
[
"create_game_gui",
"drop_piece"
],
[
"create_game_gui",
"get_next_open_row"
],
[
"create_game_gui",
"is_valid_location"
],
[
"create_game_gui",
"winning_move"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 384ee5924371d67bc47fa2f0a788084f74b993e5 | 9cf1183aa1e7da112b90a665be53bac6bfce339b | |||
v1.0 | instruct | Filter | Filter_73968_I | Can you provide a Python script that checks for palindromes in a text file? The script should read from the file, identify palindrome words, and print them out. | def is_palindrome(word):
"""
Returns True if the provided word is a palindrome, False otherwise.
"""
word = word.lower()
return word == word[::-1]
def find_palindromes_in_file(file_path):
"""
Reads a file, identifies palindrome words, and returns them in a list.
"""
palindromes = []... | from solution import is_palindrome, find_palindromes_in_file
def test_is_palindrome():
assert is_palindrome("radar") is True
assert is_palindrome("Radar") is True
assert is_palindrome("hello") is False
assert is_palindrome("A man a plan a canal Panama") is False # single word expected
assert is_pa... | [
{
"docstring": "Returns True if the provided word is a palindrome, False otherwise.",
"function_declaration": "def is_palindrome(word):",
"function_name": "is_palindrome",
"parameter_list": "(word)"
},
{
"docstring": "Reads a file, identifies palindrome words, and returns them in a list.",
... | [
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_palindrome(word):\n \"\"\"\n Checks if a given word is a palindrome.\n \"\"\"\n word = word.lower()\n return word == word[::-1]\n\ndef find_palindromes_in_file(file_path)... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00073968",
"row_id": 73968,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150018']"
} | 0.72847 | Filter_73968 | I | [
"is_palindrome",
"find_palindromes_in_file"
] | 2 | [
[
"find_palindromes_in_file",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d3e6ca3c1cb77de9bd0a8986deccd115f635d21d | abe9c1d8ab5ef06cbc50f92e56722c46d35b57dd | |||
v1.0 | instruct | Filter | Filter_74108_I | How can I add a product to a shopping cart in a Python web application using Flask, and ensure that the product details are correctly stored in the session? | from flask import Flask, session, request, jsonify
app = Flask(__name__)
app.secret_key = 'supersecretkey'
def add_product_to_cart(product_id, product_name, quantity, price):
"""
Adds a product to the shopping cart stored in session.
"""
if 'cart' not in session:
session['cart'] = []
cart... | import pytest
from flask import Flask, session
from flask.testing import FlaskClient
from solution import app, add_product_to_cart
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
with app.app_context():
yield client
def test_add_product_to_cart_... | [
{
"docstring": "Adds a product to the shopping cart stored in session.",
"function_declaration": "def add_product_to_cart(product_id, product_name, quantity, price):",
"function_name": "add_product_to_cart",
"parameter_list": "(product_id, product_name, quantity, price)"
},
{
"docstring": nu... | [
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": "from flask import Flask, session, request, jsonify\n\napp = Flask(__name__)\napp.secret_key = 'supersecretkey'\n\n@app.route('/add_to_cart', methods=['POST'])\ndef add_to_cart():\n product_... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00074108",
"row_id": 74108,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150317']"
} | 0.408513 | Filter_74108 | I | [
"add_product_to_cart",
"add_to_cart"
] | 2 | [
[
"add_to_cart",
"add_product_to_cart"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 86a7ea06c040297bfba514828e6d3cfecc9832a3 | 9d8c8692c340a30b46cc9b3093921aeedbaff2a8 | |||
v1.0 | instruct | Filter | Filter_74149_I | I want to implement a simple text-based game in Python where the player guesses a word. The game should give hints based on the number of correct letters guessed. How can I do this? | import random
def get_hint(secret_word, guessed_word):
"""
Returns a hint based on the number of correct letters guessed.
For each correctly guessed letter at the correct position, the letter is shown.
Otherwise, an underscore ('_') is shown in its place.
"""
hint = ''
for i in range(len(se... | from solution import get_hint
def test_get_hint_all_correct():
assert get_hint('python', 'python') == 'python'
def test_get_hint_some_correct():
assert get_hint('python', 'pyro') == 'py____'
assert get_hint('python', 'pyraz') == 'py____'
def test_get_hint_none_correct():
assert get_hint('python', 'ja... | [
{
"docstring": "Returns a hint based on the number of correct letters guessed.\nFor each correctly guessed letter at the correct position, the letter is shown.\nOtherwise, an underscore ('_') is shown in its place.",
"function_declaration": "def get_hint(secret_word, guessed_word):",
"function_name": "g... | [
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 random\n\ndef word_guessing_game(word_list):\n \"\"\"\n A text-based game where the player guesses a word, and the game gives hints based on the number \n of correct letters gu... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00074149",
"row_id": 74149,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150389']"
} | 0.505037 | Filter_74149 | I | [
"get_hint",
"play_game"
] | 2 | [
[
"play_game",
"get_hint"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9fdbdca28bd002f52dc6fa81e5dd185ddd1dc912 | 240f0f3740b0c2404cec189ea59510fa111172de | |||
v1.0 | instruct | Filter | Filter_74196_I | I want to create a simple Python script to download images from a list of URLs. How can I do this? | import os
import requests
def download_image(url, dest_folder):
"""
Download an image from a URL to the specified destination folder.
:param url: URL of the image to download
:param dest_folder: Destination folder to save the image
:return: The path of the downloaded image
"""
if not o... | import os
import requests
from unittest.mock import patch, mock_open
# Define the functions in the solution for accessibility in tests.
def test_download_image():
url = "http://example.com/image.jpg"
dest_folder = "test_images"
with patch("requests.get") as mock_get:
mock_get.return_value.stat... | [
{
"docstring": "Download an image from a URL to the specified destination folder.\n\n:param url: URL of the image to download\n:param dest_folder: Destination folder to save the image\n:return: The path of the downloaded image",
"function_declaration": "def download_image(url, dest_folder):",
"function_... | [
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 requests\nimport os\n\ndef download_image(url, save_path):\n \"\"\"\n Download an image from a specified URL and save it to a given path.\n\n :param url: URL of the image to be... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00074196",
"row_id": 74196,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150479']"
} | 0.573327 | Filter_74196 | I | [
"download_image",
"download_images"
] | 2 | [
[
"download_images",
"download_image"
]
] | 1 | [] | false | [] | false | pytest | false | [
"requests"
] | false | 1cf116e6fbc7d2b97ee22f5936ffe7e018e99c43 | 5dd8cbcf8dc4062b7f27a0c5e582787ed9bc6b9f | |||
v1.0 | instruct | Filter | Filter_74783_I | How can I modify the given Python code to read a list of file paths from a CSV file and process each file to count the occurrences of specific keywords? | import csv
def read_file_paths_from_csv(csv_file_path):
"""
Reads a list of file paths from a CSV file. Assumes the file paths are in the first column.
Args:
csv_file_path (str): The path to the CSV file.
Returns:
list: A list of file paths.
"""
file_paths = []
with open(c... | from solution import read_file_paths_from_csv, count_keywords_in_file, process_files
def test_read_file_paths_from_csv(tmpdir):
csv_file = tmpdir.join("file_paths.csv")
csv_file.write("file1.txt\nfile2.txt\nfile3.txt\n")
expected = ["file1.txt", "file2.txt", "file3.txt"]
result = read_file_paths_f... | [
{
"docstring": "Reads a list of file paths from a CSV file. Assumes the file paths are in the first column.\n\nArgs:\ncsv_file_path (str): The path to the CSV file.\n\nReturns:\nlist: A list of file paths.",
"function_declaration": "def read_file_paths_from_csv(csv_file_path):",
"function_name": "read_f... | [
0,
0,
0,
1,
1,
1,
0,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\n\ndef read_file_paths_from_csv(csv_file_path):\n \"\"\"\n Reads a list of file paths from a CSV file.\n\n Args:\n csv_file_path (str): Path to the CSV file containing t... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00074783",
"row_id": 74783,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_151738']"
} | 0.687909 | Filter_74783 | I | [
"read_file_paths_from_csv",
"count_keywords_in_file",
"process_files"
] | 3 | [
[
"process_files",
"count_keywords_in_file"
],
[
"process_files",
"read_file_paths_from_csv"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e688be19228c51b00aee9df32613cc910c9f16ee | 79e1401cca4a8cb4794f6f68b3a5498be9bbcad9 | |||
v1.0 | instruct | Filter | Filter_75218_I | How can I determine if a given string is a palindrome and also a valid email address in Python? A palindrome is a sequence that reads the same backward as forward, and a valid email address must meet certain criteria such as having '@' and '.' characters in the correct positions. | import re
def is_palindrome(s):
"""
Checks if the given string is a palindrome.
"""
cleaned_s = "".join(char.lower() for char in s if char.isalnum())
return cleaned_s == cleaned_s[::-1]
def is_valid_email(email):
"""
Validates if the given string is a valid email address.
"""
email... | from solution import is_palindrome, is_valid_email, is_palindrome_and_valid_email
def test_is_palindrome():
assert is_palindrome("A man a plan a canal Panama")
assert is_palindrome("racecar")
assert not is_palindrome("hello")
assert is_palindrome("Able , was I ere I saw eLba")
assert not is_palindr... | [
{
"docstring": "Checks if the given string is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Validates if the given string is a valid email address.",
"function_declaration": "def is_valid_emai... | [
0,
0,
1,
0,
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 re\n\ndef is_palindrome(s):\n \"\"\"\n Checks if a given string is a palindrome.\n \n Args:\n s (str): The input string.\n \n Returns:\... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00075218",
"row_id": 75218,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_152603']"
} | 0.730328 | Filter_75218 | I | [
"is_palindrome",
"is_valid_email",
"is_palindrome_and_valid_email"
] | 3 | [
[
"is_palindrome_and_valid_email",
"is_palindrome"
],
[
"is_palindrome_and_valid_email",
"is_valid_email"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 64b8a04576f7d5018f3da9850d1b975dd914f3f4 | df727d9f82d718b1add72868dd0800ff76d0c567 | |||
v1.0 | instruct | Filter | Filter_75297_I | Hey there! I am a student studying machine learning and I have a project where I need to implement a neural network from scratch using Python. I want to understand the basic components of a neural network, like weight initialization, activation functions, loss functions, and the forward and backward propagation process... | import numpy as np
def initialize_weights(input_dim, output_dim):
"""
Initialize weights with small random numbers.
"""
np.random.seed(42) # Seed for reproducibility
return np.random.randn(input_dim, output_dim) * 0.01
def initialize_bias(output_dim):
"""
Initialize bias with zeros.
"... | import numpy as np
from solution import SimpleNN, initialize_weights, initialize_bias, sigmoid, sigmoid_derivative, mse_loss, forward_propagation, backward_propagation
def test_initialization():
weights = initialize_weights(2, 1)
bias = initialize_bias(1)
assert weights.shape == (2, 1)
assert bias.shap... | [] | [
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 numpy as np\n\n# Weight Initialization\ndef initialize_weights(layers):\n \"\"\"\n Randomly initialize weights for each layer of the neural network.\n \"\"\"\n weights = []\... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00075297",
"row_id": 75297,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_152769']"
} | 0.293991 | Filter_75297 | I | [
"initialize_weights",
"initialize_bias",
"sigmoid",
"sigmoid_derivative",
"mse_loss",
"forward_propagation",
"backward_propagation"
] | 7 | [
[
"forward_propagation",
"sigmoid"
]
] | 1 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"numpy"
] | false | 079ec62f6c7b45cd69445987c700597c4214dce5 | af1fe7f1c2429f39b0123a46d68df7374556a9c1 | |||
v1.0 | instruct | Filter | Filter_75334_I | Can you provide a Python script that performs the Knuth-Morris-Pratt (KMP) algorithm for substring search? | def kmp_pattern_search(text, pattern):
"""
Executes the Knuth-Morris-Pratt algorithm for substring search.
:param text: The text to search within.
:param pattern: The pattern to search for.
:return: List of starting positions where pattern is found in text.
"""
positions = []
if not... | from solution import kmp_pattern_search
def test_pattern_found_single_occurrence():
assert kmp_pattern_search("ababcabcabababd", "ababd") == [10]
def test_pattern_found_multiple_occurrences():
assert kmp_pattern_search("ababcabcabababdababd", "ababd") == [10, 15]
def test_pattern_not_found():
assert kmp_... | [
{
"docstring": "Executes the Knuth-Morris-Pratt algorithm for substring search.\n\n:param text: The text to search within.\n:param pattern: The pattern to search for.\n:return: List of starting positions where pattern is found in text.",
"function_declaration": "def kmp_pattern_search(text, pattern):",
... | [
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": "def kmp_search(pattern, text):\n \"\"\"\n Performs KMP search of pattern in text and returns the starting indices of all occurrences of pattern in text.\n \"\"\"\n # Preprocess the... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00075334",
"row_id": 75334,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_152832']"
} | 0.444772 | Filter_75334 | I | [
"kmp_pattern_search",
"compute_lps"
] | 2 | [
[
"kmp_pattern_search",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e54bf54bee4ca2386e27a4a5d81069eba9786efe | 644ed421bde1ee5816e0a01f095a03b2e1d74d93 | |||
v1.0 | instruct | Filter | Filter_75569_I | Can you provide a detailed explanation of how to implement the Huffman Coding algorithm in Python for text compression? Huffman Coding is a popular algorithm used for lossless data compression, where each character in the input data is replaced with a variable-length code. The shorter codes are assigned to more frequen... | import heapq
from collections import defaultdict, Counter
class Node:
def __init__(self, char=None, freq=0):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def build_frequency_table(data):
... | from solution import (
build_frequency_table,
build_huffman_tree,
build_codes,
huffman_encoding,
huffman_decoding
)
def test_huffman_encoding():
data = "this is an example for huffman encoding"
encoded_data, tree = huffman_encoding(data)
assert isinstance(encoded_data, str)
asse... | [] | [
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 heapq\nfrom collections import defaultdict, Counter\n\nclass HuffmanNode:\n def __init__(self, char=None, freq=0):\n self.char = char\n self.freq = freq\n self.l... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00075569",
"row_id": 75569,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_153336']"
} | 0.500046 | Filter_75569 | I | [
"build_frequency_table",
"build_huffman_tree",
"build_codes",
"huffman_encoding",
"huffman_decoding"
] | 5 | [
[
"huffman_encoding",
"build_codes"
],
[
"huffman_encoding",
"build_frequency_table"
],
[
"huffman_encoding",
"build_huffman_tree"
]
] | 3 | [] | false | [
"Node"
] | true | pytest | true | [] | true | ff883a8ac431cb34749305bb5da9f519f57a55b5 | e03f4765bdb7f179e12ed1c2fbe7d6e9e5037205 | |||
v1.0 | instruct | Filter | Filter_75662_I | Can you provide a Python function to perform a simple linear regression using the gradient descent method? | import numpy as np
def compute_cost(X, y, theta):
m = len(y)
predictions = X.dot(theta)
cost = (1/2*m) * np.sum(np.square(predictions - y))
return cost
def gradient_descent(X, y, theta, learning_rate, iterations):
m = len(y)
cost_history = np.zeros(iterations)
for i in range(iteration... | from solution import compute_cost, gradient_descent, simple_linear_regression
import numpy as np
def test_compute_cost():
X = np.array([[1, 1], [1, 2], [1, 3]])
y = np.array([1, 2, 3])
theta = np.array([0, 1])
assert compute_cost(X, y, theta) == 0.0
def test_gradient_descent():
X = np.array([[1, 1... | [
{
"docstring": null,
"function_declaration": "def compute_cost(X, y, theta):",
"function_name": "compute_cost",
"parameter_list": "(X, y, theta)"
},
{
"docstring": null,
"function_declaration": "def gradient_descent(X, y, theta, learning_rate, iterations):",
"function_name": "gradien... | [
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 simple_linear_regression_gradient_descent(X, y, learning_rate=0.01, epochs=1000):\n \"\"\"\n Performs simple linear regression using the gradient descent method.\n \n Parameter... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00075662",
"row_id": 75662,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_153519']"
} | 0.565473 | Filter_75662 | I | [
"compute_cost",
"gradient_descent",
"simple_linear_regression"
] | 3 | [
[
"gradient_descent",
"compute_cost"
],
[
"simple_linear_regression",
"gradient_descent"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | cafe41c12a8b1c35b5d53c5d631bfa4c71cbae41 | 7b982a8e211c8ddcbe383f139bca51559facbad2 | |||
v1.0 | instruct | Filter | Filter_75855_I | Can you provide a Python code to simulate a slot machine with three wheels, each containing numbers from 1 to 10? The simulation should spin each wheel and print the outcome. If all three wheels show the same number, the player wins; otherwise, the player loses. | import random
def spin_wheel():
"""
Simulates spinning of a single wheel which returns a random number from 1 to 10.
"""
return random.randint(1, 10)
def simulate_slot_machine():
"""
Simulates a slot machine with three wheels.
"""
wheel1 = spin_wheel()
wheel2 = spin_wheel()
whe... | from solution import spin_wheel, simulate_slot_machine
import random
def test_spin_wheel():
result = spin_wheel()
assert 1 <= result <= 10
def test_simulate_slot_machine_win(monkeypatch):
def mock_spin_wheel():
return 5
monkeypatch.setattr('solution.spin_wheel', mock_spin_wheel)
simul... | [
{
"docstring": "Simulates spinning of a single wheel which returns a random number from 1 to 10.",
"function_declaration": "def spin_wheel():",
"function_name": "spin_wheel",
"parameter_list": "()"
},
{
"docstring": "Simulates a slot machine with three wheels.",
"function_declaration": "... | [
0,
0,
0,
0,
0,
1,
0,
1,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef spin_wheel():\n \"\"\"\n Simulates a spin of a slot machine wheel.\n Returns a random integer between 1 and 10.\n \"\"\"\n return random.randint(1, 10)\n\nd... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00075855",
"row_id": 75855,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_153925']"
} | 0.515169 | Filter_75855 | I | [
"spin_wheel",
"simulate_slot_machine"
] | 2 | [
[
"simulate_slot_machine",
"spin_wheel"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0981296d9f2dfadb7b1628cd472aa1307151b9ca | d168d32e457e77746c8bf12de01f9e9b23653dfa | |||
v1.0 | instruct | Filter | Filter_75871_I | How can I load a pre-trained transformer model in PyTorch and fine-tune it on a custom dataset for text classification? | import torch
from torch.utils.data import DataLoader, Dataset
from transformers import BertTokenizer, BertForSequenceClassification, AdamW
class CustomDataset(Dataset):
def __init__(self, texts, labels, tokenizer, max_length):
self.texts = texts
self.labels = labels
self.tokenizer = tokeniz... | import pytest
from solution import CustomDataset, load_and_fine_tune_model
def test_custom_dataset_initialization():
texts = ["Hello world", "How are you?"]
labels = [0, 1]
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
max_length = 10
dataset = CustomDataset(texts, labels, tokenize... | [] | [
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "!pip install transformers torch datasets\n\nimport torch\nfrom transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments\nfrom datasets import load_dataset\n... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00075871",
"row_id": 75871,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_153960']"
} | 0.331567 | Filter_75871 | I | [
"train_epoch",
"load_and_fine_tune_model"
] | 2 | [
[
"load_and_fine_tune_model",
"train_epoch"
]
] | 1 | [] | false | [
"CustomDataset"
] | true | pytest | true | [
"torch",
"transformers"
] | false | ce81f47e2ae9da6e7f4c7b73f21afd9f9474ebdc | d7fcb6669d6fd10670d5a43a37ade6b2a3aef9b9 | |||
v1.0 | instruct | Filter | Filter_75937_I | Write a Python program that takes a string as input and calculates the sum of the ASCII values of all the characters in the string. The program should output the sum in a user-friendly format. | def sum_of_ascii_values(input_str):
"""
Returns the sum of the ASCII values of all the characters in the input string.
"""
return sum(ord(char) for char in input_str)
def user_friendly_sum_of_ascii_values(input_str):
"""
Returns a user-friendly statement of the sum of the ASCII values of
a... | from solution import sum_of_ascii_values, user_friendly_sum_of_ascii_values
def test_sum_of_ascii_values_empty_string():
assert sum_of_ascii_values("") == 0
def test_sum_of_ascii_values_single_character():
assert sum_of_ascii_values("A") == 65
assert sum_of_ascii_values("a") == 97
def test_sum_of_ascii_v... | [
{
"docstring": "Returns the sum of the ASCII values of all the characters in the input string.",
"function_declaration": "def sum_of_ascii_values(input_str):",
"function_name": "sum_of_ascii_values",
"parameter_list": "(input_str)"
},
{
"docstring": "Returns a user-friendly statement of the ... | [
0,
0,
0,
0,
1,
1,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sum_of_ascii_values(input_string):\n \"\"\"\n Returns the sum of the ASCII values of all characters in the input string.\n \"\"\"\n return sum(ord(char) for char in input_strin... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00075937",
"row_id": 75937,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_154092']"
} | 0.755191 | Filter_75937 | I | [
"sum_of_ascii_values",
"user_friendly_sum_of_ascii_values"
] | 2 | [
[
"user_friendly_sum_of_ascii_values",
"sum_of_ascii_values"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 895f916fb2d8bbe638cc625bc4d02c97d2ce1b93 | c5a4ce85ef5f8e0a46c96da9c8b8bba1bde1f666 | |||
v1.0 | instruct | Filter | Filter_75948_I | Given a list of strings and a target string, you need to find the closest strings to the target string based on Levenshtein distance. The Levenshtein distance between two strings is the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other. Your ... | import heapq
from typing import List, Tuple
def levenshtein_distance(s1: str, s2: str) -> int:
if len(s1) < len(s2):
return levenshtein_distance(s2, s1)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
... | from solution import levenshtein_distance, k_closest_strings
def test_levenshtein_distance():
assert levenshtein_distance("kitten", "sitting") == 3
assert levenshtein_distance("flaw", "lawn") == 2
assert levenshtein_distance("gumbo", "gambol") == 2
assert levenshtein_distance("book", "back") == 2
a... | [
{
"docstring": null,
"function_declaration": "def levenshtein_distance(s1, s2):",
"function_name": "levenshtein_distance",
"parameter_list": "(s1, s2)"
},
{
"docstring": null,
"function_declaration": "def k_closest_strings(strings, target, k):",
"function_name": "k_closest_strings",
... | [
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nfrom typing import List, Tuple\n\ndef levenshtein_distance(s1: str, s2: str) -> int:\n \"\"\"\n Compute the Levenshtein distance between two strings.\n \"\"\"\n if le... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00075948",
"row_id": 75948,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_154114']"
} | 0.72035 | Filter_75948 | I | [
"levenshtein_distance",
"k_closest_strings"
] | 2 | [
[
"k_closest_strings",
"levenshtein_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 82039c1075c760d48f61e898965f701d6c832307 | dd4efd00d05d75bf3b6fcd6b5852bb560391d862 | |||
v1.0 | instruct | Filter | Filter_75976_I | Can you explain the concept of caching in web applications and provide a simple example in Python using Flask? | from flask import Flask, request, jsonify
from functools import lru_cache
app = Flask(__name__)
# A simple example of caching function results using lru_cache decorator
@lru_cache(maxsize=100)
def expensive_computation(x):
# Simulate expensive computation
result = x * x
return result
@app.route('/comput... | import pytest
from solution import app
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_computation(client):
response = client.get('/compute?x=5')
assert response.status_code == 200
json_data = response.get_json()
assert json_data['result'] == 25
def t... | [
{
"docstring": null,
"function_declaration": "def expensive_computation(x):",
"function_name": "expensive_computation",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def compute():",
"function_name": "compute",
"parameter_list": "()"
}
] | [
0,
0,
1,
1,
0,
0,
0,
0,
1
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask\nfrom flask_caching import Cache\n\napp = Flask(__name__)\n\n# Configure Flask-Caching\napp.config['CACHE_TYPE'] = 'SimpleCache'\napp.config['CACHE_DEFAULT_TIMEOUT'] = ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00075976",
"row_id": 75976,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_154166']"
} | 0.431961 | Filter_75976 | I | [
"expensive_computation",
"compute"
] | 2 | [
[
"compute",
"expensive_computation"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 9c55b37ea9a618f67536efc769395941073f5037 | b07c4c0864d822d323c4d3e9be2e0bf5f6a884df | |||
v1.0 | instruct | Filter | Filter_75986_I | Can you explain how the `termios` module in Python works and provide an example of how to use it? | import sys
import termios
import tty
def set_non_canonical_mode(fd):
"""
Sets the terminal to non-canonical mode.
"""
original_attributes = termios.tcgetattr(fd)
new_attributes = termios.tcgetattr(fd)
new_attributes[3] = new_attributes[3] & ~(termios.ICANON | termios.ECHO) # lflags
termios.... | import termios
from solution import set_non_canonical_mode, set_canonical_mode
def test_set_non_canonical_mode(monkeypatch):
fake_fd = 0
fake_attributes = [0, 0, 0, termios.ICANON | termios.ECHO]
monkeypatch.setattr(termios, 'tcgetattr', lambda fd: fake_attributes)
monkeypatch.setattr(termios, 'tcsetat... | [
{
"docstring": "Sets the terminal to non-canonical mode.",
"function_declaration": "def set_non_canonical_mode(fd):",
"function_name": "set_non_canonical_mode",
"parameter_list": "(fd)"
},
{
"docstring": "Restores the terminal to canonical mode.",
"function_declaration": "def set_canonic... | [
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 termios\nimport sys\nimport tty\n\ndef getch():\n \"\"\"\n Read a single character from the terminal without requiring the Enter key to be pressed.\n \"\"\"\n fd = sys.stdin... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00075986",
"row_id": 75986,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_154186']"
} | 0.391342 | Filter_75986 | I | [
"set_non_canonical_mode",
"set_canonical_mode",
"read_one_character"
] | 3 | [
[
"read_one_character",
"set_canonical_mode"
],
[
"read_one_character",
"set_non_canonical_mode"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8bc6bbaaac02a5d1a5c45940229d5c9f2f346873 | 852813828fd2a50ff75fac761aa71c0c6f1c3d4a | |||
v1.0 | instruct | Filter | Filter_76280_I | Can you explain how to implement a Minimax algorithm in a simple Tic-Tac-Toe game using Python? | def print_board(board):
for row in board:
print("|".join(row))
print("-" * 5)
def check_win(board, player):
win_conditions = [
[board[0][0], board[0][1], board[0][2]],
[board[1][0], board[1][1], board[1][2]],
[board[2][0], board[2][1], board[2][2]],
[board[0][0],... | from solution import print_board, check_win, check_draw, minimax, best_move
def test_print_board(capfd):
board = [['X', 'O', 'X'], ['O', 'O', 'X'], [' ', ' ', ' ']]
print_board(board)
out, err = capfd.readouterr()
expected_output = "X|O|X\n-----\nO|O|X\n-----\n | | \n-----\n"
assert out == expected... | [
{
"docstring": null,
"function_declaration": "def print_board(board):",
"function_name": "print_board",
"parameter_list": "(board)"
},
{
"docstring": null,
"function_declaration": "def check_win(board, player):",
"function_name": "check_win",
"parameter_list": "(board, player)"
... | [
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 is_winner(board, player):\n # Check rows, columns and diagonals for a win\n win_cond = [\n [board[0], board[1], board[2]],\n [board[3], board[4], board[5]],\n [b... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00076280",
"row_id": 76280,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_154768']"
} | 0.497904 | Filter_76280 | I | [
"print_board",
"check_win",
"check_draw",
"minimax",
"best_move"
] | 5 | [
[
"best_move",
"minimax"
],
[
"minimax",
"check_draw"
],
[
"minimax",
"check_win"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | f5d0814b69712cbada27abf34e42db870e57845c | d2b87ccebb1fc6c60a92bd999a15c59a2ba81069 | |||
v1.0 | instruct | Filter | Filter_76406_I | I need to create a simple Python script that animates the evolution of a 1D cellular automaton over time. The rules for the automaton are simple: each cell in the current row determines the state of the cells in the next row based on the following rule: a cell's state is 1 if exactly one of its two neighbors (to the le... | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update_cautomaton(ca, steps):
"""
Updates the 1D cellular automaton state over a specified number of steps.
Parameters:
ca (np.ndarray): Initial state of the cellular automaton.
steps (int):... | from solution import update_cautomaton
import numpy as np
def test_initial_state_persists():
initial_state = np.array([0, 1, 0, 1, 0])
result = update_cautomaton(initial_state, 1)
assert np.array_equal(result[0], initial_state)
def test_single_step_evolution():
initial_state = np.array([0, 1, 0, 1, 0]... | [
{
"docstring": "Updates the 1D cellular automaton state over a specified number of steps.\n\nParameters:\n ca (np.ndarray): Initial state of the cellular automaton.\n steps (int): Number of steps to evolve the CA.\n \nReturns:\n np.ndarray: 2D array where each row represents the state of the CA at e... | [
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 numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\ndef generate_initial_row(n):\n \"\"\"\n Generates the initial row of the cellular automat... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00076406",
"row_id": 76406,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_155017']"
} | 0.490643 | Filter_76406 | I | [
"update_cautomaton",
"animate_ca"
] | 2 | [
[
"animate_ca",
"update_cautomaton"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | b7e2c4c19a24b35fbe445efa1cc5ca18e4b05491 | a9fc075b10de0e3ee1cdac094860d81c03232f8e | |||
v1.0 | instruct | Filter | Filter_76559_I | How can I create a Python function that generates a list of all palindrome numbers within a given range? | def is_palindrome(num):
"""
Checks if a given number is a palindrome.
"""
return str(num) == str(num)[::-1]
def generate_palindromes(start, end):
"""
Generates a list of all palindrome numbers within the given range [start, end].
"""
palindromes = []
for num in range(start, end + 1)... | from solution import is_palindrome, generate_palindromes
def test_is_palindrome():
assert is_palindrome(121) == True
assert is_palindrome(123) == False
assert is_palindrome(0) == True
assert is_palindrome(22) == True
assert is_palindrome(10) == False
def test_generate_palindromes_small_range()... | [
{
"docstring": "Checks if a given number is a palindrome.",
"function_declaration": "def is_palindrome(num):",
"function_name": "is_palindrome",
"parameter_list": "(num)"
},
{
"docstring": "Generates a list of all palindrome numbers within the given range [start, end].",
"function_declar... | [
0,
0,
0,
1,
1,
1,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(number):\n \"\"\"\n Checks if a given number is a palindrome.\n \n A number is a palindrome if it reads the same backward as forward.\n \"\"\"\n str_num = s... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00076559",
"row_id": 76559,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_155352']"
} | 0.631786 | Filter_76559 | I | [
"is_palindrome",
"generate_palindromes"
] | 2 | [
[
"generate_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7ffdfd9dde0e4a9f30e4f2947db67a192db52ac6 | 367ca0bfdea34570a6a4cf5bfb1c38d168fe49ca | |||
v1.0 | instruct | Filter | Filter_76686_I | Write a Python function that takes a list of molecules, where each molecule is represented as a string in the format "C3H6O", and returns a dictionary where the keys are the unique molecules and the values are their respective counts. The function should also handle cases where the molecules are in a different order or... | import re
from collections import defaultdict
def standardize_molecule(molecule):
"""
Standardizes the molecule string by removing spaces,
sorting the elements by their symbols, then returning
the combined string in a standardized format.
"""
# Remove whitespace characters
molecule = molecu... | from solution import count_molecules
def test_standard_molecules():
assert count_molecules(["C3H6O", "C3H6O", "C3H6O"]) == {"C3H6O": 3}
def test_molecules_with_spaces():
assert count_molecules(["C3 H6 O", " H6C3O ", "C3H6O"]) == {"C3H6O": 3}
def test_molecules_with_different_orders():
assert count_molecu... | [
{
"docstring": "Standardizes the molecule string by removing spaces,\nsorting the elements by their symbols, then returning\nthe combined string in a standardized format.",
"function_declaration": "def standardize_molecule(molecule):",
"function_name": "standardize_molecule",
"parameter_list": "(mol... | [
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 re\nfrom collections import defaultdict\n\ndef parse_molecule(molecule):\n \"\"\"\n Parse the input molecule string and return a canonical form.\n \"\"\"\n # Remove spaces a... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00076686",
"row_id": 76686,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_155612']"
} | 0.631515 | Filter_76686 | I | [
"standardize_molecule",
"count_molecules"
] | 2 | [
[
"count_molecules",
"standardize_molecule"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d3c6173bfa6ffdf7d9d17c10a439356f1a14d7b7 | c6315fc0632f4385db81f6e74860d1edf654ef23 | |||
v1.0 | instruct | Filter | Filter_76823_I | Can you provide a Python function to compress and decompress a string using the Huffman Coding algorithm? | import heapq
from collections import defaultdict, Counter
class Node:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def build_huffman_tree(freq_map):
... | from solution import huffman_compress, huffman_decompress
def test_huffman_compress_decompress_simple():
data = "hello"
compressed_data, huffman_tree = huffman_compress(data)
decompressed_data = huffman_decompress(compressed_data, huffman_tree)
assert decompressed_data == data
def test_huffman_compres... | [] | [
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 heapq\nfrom collections import defaultdict, Counter\n\nclass Node:\n def __init__(self, char, freq, left=None, right=None):\n self.char = char\n self.freq = freq\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00076823",
"row_id": 76823,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_155882']"
} | 0.570606 | Filter_76823 | I | [
"build_huffman_tree",
"build_codes",
"huffman_compress",
"huffman_decompress"
] | 4 | [
[
"huffman_compress",
"build_codes"
],
[
"huffman_compress",
"build_huffman_tree"
]
] | 2 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 082a58f4c32075120d4d654e62902a3720c92752 | 0881f67ace3db9808e2caa1ec1652ffbbd7c7608 | |||
v1.0 | instruct | Filter | Filter_76827_I | Can you provide me with a Python code to simulate the SIR model for an epidemic using the given initial conditions and parameters? | from scipy.integrate import odeint
import numpy as np
# Function to compute the derivatives
def sir_model(y, t, beta, gamma):
S, I, R = y
dSdt = -beta * S * I
dIdt = beta * S * I - gamma * I
dRdt = gamma * I
return [dSdt, dIdt, dRdt]
# Function to solve the SIR model
def solve_sir(S0, I0, R0, beta... | from solution import solve_sir
import numpy as np
def test_solve_sir_initial_conditions():
S0, I0, R0 = 990, 10, 0
beta, gamma = 0.3, 0.1
days = 160
S, I, R = solve_sir(S0, I0, R0, beta, gamma, days)
assert round(S[0]) == S0
assert round(I[0]) == I0
assert round(R[0]) == R0
def test_solve_... | [
{
"docstring": null,
"function_declaration": "def sir_model(y, t, beta, gamma):",
"function_name": "sir_model",
"parameter_list": "(y, t, beta, gamma)"
},
{
"docstring": null,
"function_declaration": "def solve_sir(S0, I0, R0, beta, gamma, days):",
"function_name": "solve_sir",
"... | [
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": "def simulate_sir(S0, I0, R0, beta, gamma, days):\n \"\"\"\n Simulates the SIR model for an epidemic over a given number of days.\n\n Parameters:\n S0 (int): Initial number of susce... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00076827",
"row_id": 76827,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_155894']"
} | 0.368941 | Filter_76827 | I | [
"sir_model",
"solve_sir"
] | 2 | [
[
"solve_sir",
"sir_model"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 623c60eb11bc767cd03f21cac4fb2bfb9c4946ed | 57fa04d4aa84ad212e9f0e10a7ae1860ca034cdd | |||
v1.0 | instruct | Filter | Filter_76931_I | Can you provide a Python code snippet that prints out the current datetime and the next occurrence of a specific weekday, say Wednesday? | from datetime import datetime, timedelta
def get_next_weekday(current_date, weekday):
"""
Given a datetime object and a target weekday, returns a new datetime object representing
the next occurrence of the desired weekday.
Weekday is an integer where Monday is 0 and Sunday is 6.
"""
days_ahead ... | from datetime import datetime, timedelta
from solution import get_next_weekday
def test_get_next_weekday_same_day():
today = datetime(2023, 10, 4) # This is a Wednesday
next_wednesday = get_next_weekday(today, 2) # Wednesday is 2 in Python's weekday
assert next_wednesday == today + timedelta(days=7)
def... | [
{
"docstring": "Given a datetime object and a target weekday, returns a new datetime object representing\nthe next occurrence of the desired weekday.\nWeekday is an integer where Monday is 0 and Sunday is 6.",
"function_declaration": "def get_next_weekday(current_date, weekday):",
"function_name": "get_... | [
0,
0,
0,
1,
0,
0,
1,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from datetime import datetime, timedelta\n\ndef get_next_weekday(target_weekday):\n \"\"\"\n Returns the current datetime and the next occurrence of the given target_weekday.\n \n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00076931",
"row_id": 76931,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_156120']"
} | 0.701137 | Filter_76931 | I | [
"get_next_weekday",
"print_current_and_next_wednesday"
] | 2 | [
[
"print_current_and_next_wednesday",
"get_next_weekday"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f8a8b9afd242968c5d8422263f50111866cb374f | ea8b2dc64c6f66a17936626cdd7cd10f554f4f7f | |||
v1.0 | instruct | Filter | Filter_77005_I | Can I create a Python script that dynamically adjusts the screen brightness and volume based on the time of day using a Windows machine? | import ctypes
import time
import datetime
import os
def set_brightness(brightness):
"""
Adjust the screen brightness.
:param brightness: Brightness level from 0 to 100.
"""
if 0 <= brightness <= 100:
os.system(f"powershell (Get-WmiObject -Namespace root/WMI -Class WmiMonitorBrightnessM... | from solution import set_brightness, set_volume, adjust_brightness_and_volume, get_current_time
def test_set_brightness_valid():
try:
set_brightness(50)
set_brightness(0)
set_brightness(100)
except ValueError:
assert False, "set_brightness() raised ValueError unexpectedly!"
def... | [
{
"docstring": "Adjust the screen brightness.\n\n:param brightness: Brightness level from 0 to 100.",
"function_declaration": "def set_brightness(brightness):",
"function_name": "set_brightness",
"parameter_list": "(brightness)"
},
{
"docstring": "Adjust the system volume.\n\n:param volume: ... | [
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 ctypes\nimport datetime\nfrom pycaw.pycaw import AudioUtilities, ISimpleAudioVolume\nfrom comtypes import CLSCTX_ALL\n\ndef set_brightness(brightness):\n \"\"\"\n Sets the screen ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00077005",
"row_id": 77005,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_156272']"
} | 0.389836 | Filter_77005 | I | [
"set_brightness",
"set_volume",
"get_current_time",
"adjust_brightness_and_volume"
] | 4 | [
[
"adjust_brightness_and_volume",
"get_current_time"
],
[
"adjust_brightness_and_volume",
"set_brightness"
],
[
"adjust_brightness_and_volume",
"set_volume"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 6a2cf18b919b94b5e788e7ac2222b8f5c3cefc73 | 2a4542750825ac2b656d08d5060c163e24f3b06e | |||
v1.0 | instruct | Filter | Filter_77157_I | I need to create a simple web application that allows users to upload files and display them. How can I achieve this using Python? | from flask import Flask, request, redirect, url_for, send_from_directory, render_template_string
import os
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs... | import pytest
import os
from werkzeug.datastructures import FileStorage
from solution import app, allowed_file
@pytest.fixture
def client():
app.config['TESTING'] = True
client = app.test_client()
yield client
def test_allowed_file():
assert allowed_file('test.txt') == True
assert allowed_file('te... | [
{
"docstring": null,
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def index():",
"function_name": "index",
"parameter_list": "()"
},
{
"docstring": n... | [
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": "from flask import Flask, request, render_template, redirect, url_for\nimport os\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = 'uploads/'\napp.config['ALLOWED_EXTENSIONS'] = {'txt', '... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00077157",
"row_id": 77157,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_156605']"
} | 0.454983 | Filter_77157 | I | [
"allowed_file",
"index",
"upload_file",
"uploaded_file"
] | 4 | [
[
"upload_file",
"allowed_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask",
"werkzeug"
] | false | 6b7dd94d261b2950cb542cecef140df07eab2f97 | 029697d22b3c934d641f87e3d8e4f5706a3fb2a3 | |||
v1.0 | instruct | Filter | Filter_77202_I | How can I create a custom user management system using Python and Flask? | from flask import Flask, request, jsonify, session, redirect, url_for
from werkzeug.security import generate_password_hash, check_password_hash
import uuid
app = Flask(__name__)
app.secret_key = 'supersecretkey'
# In-memory user store for simplicity
users_db = {}
# Helper function to get user by username
def get_use... | import pytest
from solution import app, users_db
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def test_register(client):
response = client.post('/register', json={
'username': 'testuser',
'password': 'testpassword'
})... | [
{
"docstring": null,
"function_declaration": "def get_user_by_username(username):",
"function_name": "get_user_by_username",
"parameter_list": "(username)"
},
{
"docstring": null,
"function_declaration": "def register():",
"function_name": "register",
"parameter_list": "()"
},
... | [
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.125 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, render_template, request, redirect, url_for, flash, session\nfrom flask_sqlalchemy import SQLAlchemy\nfrom werkzeug.security import generate_password_hash, check_passw... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00077202",
"row_id": 77202,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_156698']"
} | 0.546588 | Filter_77202 | I | [
"get_user_by_username",
"register",
"login",
"logout",
"profile"
] | 5 | [
[
"login",
"get_user_by_username"
],
[
"profile",
"get_user_by_username"
],
[
"register",
"get_user_by_username"
]
] | 3 | [] | false | [] | false | pytest | true | [
"flask",
"werkzeug"
] | false | d835cd73e9189060aa275b014000a493e31f9c3f | c7c0c6e48fc9a28fa79d1f428c7e8ef7bf1af0b5 | |||
v1.0 | instruct | Filter | Filter_77233_I | How can I create a Python script to automatically monitor webpage changes and send an email alert when changes are detected? | import hashlib
import requests
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def fetch_webpage(url):
response = requests.get(url)
if response.status_code == 200:
return response.text
else:
return None
def hash_content(content):
retur... | import pytest
from solution import fetch_webpage, hash_content, monitor_webpage, send_email_alert
def test_fetch_webpage(monkeypatch):
class MockResponse:
def __init__(self, status_code, text):
self.status_code = status_code
self.text = text
def mock_get(url):
retur... | [
{
"docstring": null,
"function_declaration": "def fetch_webpage(url):",
"function_name": "fetch_webpage",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def hash_content(content):",
"function_name": "hash_content",
"parameter_list": "(content)"
},
... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport hashlib\nimport smtplib\nimport time\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef get_website_hash(url):\n \"\"\"\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00077233",
"row_id": 77233,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_156761']"
} | 0.412 | Filter_77233 | I | [
"fetch_webpage",
"hash_content",
"send_email_alert",
"monitor_webpage"
] | 4 | [
[
"monitor_webpage",
"fetch_webpage"
],
[
"monitor_webpage",
"hash_content"
],
[
"monitor_webpage",
"send_email_alert"
]
] | 3 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 8c1aefcdeb5113c5080f0d95428f10b322ea6fde | 92f6c915129b6cfde36141397009395fde23ae9f | |||
v1.0 | instruct | Filter | Filter_77685_I | I want to create a CSV file that includes a column with real-time weather data. How can I automate this process using Python? | import requests
import csv
from datetime import datetime
def get_weather_data(city, api_key):
"""
Fetch real-time weather data for a given city using OpenWeatherMap API.
Args:
city (str): The name of the city.
api_key (str): The API key for the OpenWeatherMap service.
Returns:
dic... | import pytest
from unittest.mock import patch
from solution import get_weather_data, create_weather_csv
@patch('solution.requests.get')
def test_get_weather_data(mock_get):
# Mock successful response
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {
"main": {"temp... | [
{
"docstring": "Fetch real-time weather data for a given city using OpenWeatherMap API.\n\nArgs:\ncity (str): The name of the city.\napi_key (str): The API key for the OpenWeatherMap service.\n\nReturns:\ndict: A dictionary with temperature data.",
"function_declaration": "def get_weather_data(city, api_key... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport pandas as pd\nfrom datetime import datetime\n\ndef fetch_weather(city, api_key):\n \"\"\"\n Fetch the current weather data for a given city using the OpenWeatherM... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00077685",
"row_id": 77685,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_157756']"
} | 0.71673 | Filter_77685 | I | [
"get_weather_data",
"create_weather_csv"
] | 2 | [
[
"create_weather_csv",
"get_weather_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 99c86b4521a5fb84a385af32f80a5c80c0d38500 | 0c98c14b3f7bb19756c646d72d290af802952ce1 | |||
v1.0 | instruct | Filter | Filter_77743_I | Can you provide a Python code example that demonstrates how to implement a simple marine navigation system using GPS data? This system should be able to calculate the distance to a destination and provide directions based on the current position. | from math import radians, cos, sin, asin, sqrt, atan2, degrees
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great-circle distance in kilometers between two points on the Earth
specified by their longitude and latitude.
:param lon1: Longitude of the first point
:param lat1: Latitude of... | from solution import navigate_to_coordinate, haversine, calculate_initial_compass_bearing
def test_haversine_simple():
assert round(haversine(0, 0, 0, 1), 2) == 111.19
assert round(haversine(0, 0, 1, 0), 2) == 111.19
def test_calculate_initial_compass_bearing():
assert round(calculate_initial_compass_bear... | [
{
"docstring": "Calculate the great-circle distance in kilometers between two points on the Earth \nspecified by their longitude and latitude.\n\n:param lon1: Longitude of the first point\n:param lat1: Latitude of the first point\n:param lon2: Longitude of the second point\n:param lat2: Latitude of the second p... | [
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 math\n\ndef haversine_distance(lat1, lon1, lat2, lon2):\n \"\"\"\n Calculate the great circle distance between two points \n on the earth (specified in decimal degrees)\n \"... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00077743",
"row_id": 77743,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_157879']"
} | 0.382926 | Filter_77743 | I | [
"haversine",
"calculate_initial_compass_bearing",
"navigate_to_coordinate"
] | 3 | [
[
"navigate_to_coordinate",
"calculate_initial_compass_bearing"
],
[
"navigate_to_coordinate",
"haversine"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 63d4f7471d1f790c2264c51b9967f23760847e91 | 2cfd7e734f3d30d27360faa7b60ba7af0d381584 | |||
v1.0 | instruct | Filter | Filter_77783_I | Can you provide a Python script that reads a CSV file containing latitude and longitude pairs and calculates the distance between the first point and all other points using the haversine formula? Also, include error handling for file operations and data parsing. | import csv
from math import radians, sin, cos, sqrt, atan2
def haversine(lat1, lon1, lat2, lon2):
"""
Returns the distance between two points on the Earth's surface in kilometers, given their latitude and longitude in degrees.
"""
R = 6371 # Radius of the Earth in km
lat1, lon1, lat2, lon2 = map(... | import pytest
from solution import haversine, calculate_distances_from_csv
import os
def test_haversine():
assert haversine(0, 0, 0, 0) == 0
assert round(haversine(0, 0, 1, 1), 2) == 157.25
def test_calculate_distances_from_csv(tmpdir):
# Creating a temporary CSV file
csvfile = tmpdir.join("test.csv")... | [
{
"docstring": "Returns the distance between two points on the Earth's surface in kilometers, given their latitude and longitude in degrees.",
"function_declaration": "def haversine(lat1, lon1, lat2, lon2):",
"function_name": "haversine",
"parameter_list": "(lat1, lon1, lat2, lon2)"
},
{
"do... | [
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 csv\nimport math\n\ndef read_csv(filepath):\n \"\"\"\n Reads the CSV file and returns a list of (latitude, longitude) tuples.\n \"\"\"\n coordinates = []\n try:\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00077783",
"row_id": 77783,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_157955']"
} | 0.595797 | Filter_77783 | I | [
"haversine",
"calculate_distances_from_csv"
] | 2 | [
[
"calculate_distances_from_csv",
"haversine"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a1ddad064af3c14b8d4ab65a6574691b0b6abfdf | b0f9e8825b346a37ff508370cfe0c2c5713f60eb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.