task_id
string
prompt
string
canonical_solution
string
corrupted_solution
string
test_code
string
mutation_types
list
num_corruptions
int64
BigCodeBench/0
Calculates the average of the sums of absolute differences between each pair of consecutive numbers for all permutations of a given list. Each permutation is shuffled before calculating the differences. Args: - numbers (list): A list of numbers. Default is numbers from 1 to 10. The function should output with: floa...
import itertools from random import shuffle def task_func(numbers=list(range(1, 3))): """ Calculates the average of the sums of absolute differences between each pair of consecutive numbers for all permutations of a given list. Each permutation is shuffled before calculating the differences. Args: ...
import itertools from random import shuffle def task_func(numbers=list(range(1, 3))): """ Calculates the average of the sums of absolute differences between each pair of consecutive numbers for all permutations of a given list. Each permutation is shuffled before calculating the differences. Args: ...
import unittest from unittest.mock import patch from random import seed, shuffle import itertools class TestCases(unittest.TestCase): def test_default_numbers(self): # Test with default number range (1 to 10) to check that the result is a positive float. result = task_func() self.assertIsIns...
[ "mutate_list_indexing" ]
1
BigCodeBench/1
Generate a random string of the specified length composed of uppercase and lowercase letters, and then count the occurrence of each character in this string. The function should raise the exception for: ValueError if the length is a negative number The function should output with: dict: A dictionary where each key ...
import collections import random import string def task_func(length=100): """ Generate a random string of the specified length composed of uppercase and lowercase letters, and then count the occurrence of each character in this string. Parameters: length (int, optional): The number of characters ...
import collections import random import string def task_func(length=100): """ Generate a random string of the specified length composed of uppercase and lowercase letters, and then count the occurrence of each character in this string. Parameters: length (int, optional): The number of characters ...
import unittest import string class TestCases(unittest.TestCase): def setUp(self): # Prepare valid characters and set a random seed for reproducibility self.valid_chars = string.ascii_uppercase + string.ascii_lowercase random.seed(42) # Ensuring reproducibility for tests def test_genera...
[ "mutate_comparison_operators" ]
1
BigCodeBench/5
Create a dictionary where keys are letters from a predefined list LETTERS and values are lists of random integers. Then, calculates the population standard deviation for each list of integers and returns a dictionary of these values. The random integers for each key are generated within the range 0 to 100, and each lis...
import random import math def task_func(LETTERS=[chr(i) for i in range(97, 123)]): """ Create a dictionary where keys are letters from a predefined list LETTERS and values are lists of random integers. Then, calculates the population standard deviation for each list of integers and returns a dictionary of ...
import random import math def task_func(LETTERS=[chr(i) for i in range(97, 123)]): """ Create a dictionary where keys are letters from a predefined list LETTERS and values are lists of random integers. Then, calculates the population standard deviation for each list of integers and returns a dictionary of ...
import unittest from unittest.mock import patch import math import random class TestCases(unittest.TestCase): def setUp(self): self.LETTERS = [chr(i) for i in range(97, 123)] random.seed(42) def test_default_letters(self): # Test the function with the default set of letters sd_di...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/6
Find the latest log file in a specified directory that matches a given regex pattern. This function searches through all files in the specified directory, filters them based on the provided regex pattern, and returns the path to the most recent log file based on modification time. If no files match the pattern or the d...
import os import re def task_func(pattern, log_dir='/var/log/'): """ Find the latest log file in a specified directory that matches a given regex pattern. This function searches through all files in the specified directory, filters them based on the provided regex pattern, and returns the path to the...
import os import re def task_func(pattern, log_dir='/var/log/'): """ Find the latest log file in a specified directory that matches a given regex pattern. This function searches through all files in the specified directory, filters them based on the provided regex pattern, and returns the path to the...
import unittest from unittest.mock import patch import os import re class TestCases(unittest.TestCase): @patch("os.listdir") @patch("os.path.getmtime") def test_case_1(self, mock_getmtime, mock_listdir): # Test that no log files are returned when none match the regex pattern mock_listdi...
[ "mutate_list_indexing" ]
1
BigCodeBench/7
Find the best-selling product from a given CSV file with sales data. This function parses a CSV file assumed to have a header followed by rows containing two columns: 'product' and 'quantity'. It computes the total sales per product and determines the product with the highest cumulative sales. The CSV file must include...
import csv import collections import operator def task_func(csv_file_path): """ Find the best-selling product from a given CSV file with sales data. This function parses a CSV file assumed to have a header followed by rows containing two columns: 'product' and 'quantity'. It computes the total sales p...
import csv import collections import operator def task_func(csv_file_path): """ Find the best-selling product from a given CSV file with sales data. This function parses a CSV file assumed to have a header followed by rows containing two columns: 'product' and 'quantity'. It computes the total sales p...
import os import unittest import csv class TestCases(unittest.TestCase): def setUp(self): # Create a directory for test files if it does not exist self.test_dir = os.path.join(os.getcwd(), 'test_data') os.makedirs(self.test_dir, exist_ok=True) def tearDown(self): # Remove all fil...
[ "mutate_list_indexing" ]
1
BigCodeBench/8
Convert elements in 'T1' to integers and create a list of random integers where the number of integers is determined by the sum of the integers in `T1`. Random integers are generated between 0 and `RANGE` (default is 100). Count the occurrences of each number in the generated list using a Counter. The function should o...
from collections import Counter import itertools from random import randint def task_func(T1, RANGE=100): """ Convert elements in 'T1' to integers and create a list of random integers where the number of integers is determined by the sum of the integers in `T1`. Random integers are generated between 0 and...
from collections import Counter import itertools from random import randint def task_func(T1, RANGE=100): """ Convert elements in 'T1' to integers and create a list of random integers where the number of integers is determined by the sum of the integers in `T1`. Random integers are generated between 0 and...
import unittest from collections import Counter class TestCases(unittest.TestCase): def test_case_1(self): """Single tuple with small integers as strings""" T1 = (('1', '2', '3'),) result = task_func(T1) self.assertIsInstance(result, Counter) self.assertEqual(sum(result.value...
[ "mutate_range_bounds" ]
1
BigCodeBench/12
Runs the provided backup shell script and logs the start time, end time, and exit status in a specified JSON log file. The function should raise the exception for: FileNotFoundError: If the script file does not exist. RuntimeError: If there is an error executing the script. The function should output with: dict: A ...
import subprocess import os import json from datetime import datetime def task_func(script_name='backup.sh', log_file='/home/user/backup_log.json'): """ Runs the provided backup shell script and logs the start time, end time, and exit status in a specified JSON log file. Parameters: - script...
import subprocess import os import json from datetime import datetime def task_func(script_name='backup.sh', log_file='/home/user/backup_log.json'): """ Runs the provided backup shell script and logs the start time, end time, and exit status in a specified JSON log file. Parameters: - script_...
import unittest from unittest.mock import patch, mock_open class TestCases(unittest.TestCase): @patch("os.path.isfile", return_value=True) @patch("subprocess.call", return_value=0) @patch("builtins.open", new_callable=mock_open, read_data="{}") def test_default_values_successful_script(self, mock_f...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/13
Download all files from a specific directory on an FTP server using wget in a subprocess. Args: ftp_server (str): The FTP server address. Default is 'ftp.dlptest.com'. ftp_user (str): The FTP server username. Default is 'dlpuser'. ftp_password (str): The FTP server password. Default is 'rNrKYTX9g7z3RgJRmxWuGHbeu'. ftp_...
import subprocess import ftplib import os def task_func(ftp_server='ftp.dlptest.com', ftp_user='dlpuser', ftp_password='rNrKYTX9g7z3RgJRmxWuGHbeu', ftp_dir='/ftp/test'): """ Download all files from a specific directory on an FTP server using wget in a subprocess. Args: ftp_server (str): The FTP se...
import subprocess import ftplib import os def task_func(ftp_server='ftp.dlptest.com', ftp_user='dlpuser', ftp_password='rNrKYTX9g7z3RgJRmxWuGHbeu', ftp_dir='/ftp/test'): """ Download all files from a specific directory on an FTP server using wget in a subprocess. Args: ftp_server (str): The FTP se...
import unittest from unittest.mock import patch import os class TestCases(unittest.TestCase): def setUp(self): """Setup a clean test environment before each test.""" if not os.path.exists("downloaded_files"): os.makedirs("downloaded_files") def tearDown(self): """Cleanup...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/16
Backup all '.log' files in a specified directory to a tar.gz file and delete the original files after backup. The backup file is named 'logs_backup.tar.gz' and placed in the specified backup directory. The function should raise the exception for: FileNotFoundError: If the specified directory does not exist. The functio...
import os import glob import subprocess def task_func(directory, backup_dir='/path/to/backup'): """ Backup all '.log' files in a specified directory to a tar.gz file and delete the original files after backup. The backup file is named 'logs_backup.tar.gz' and placed in the specified backup directory. ...
import os import glob import subprocess def task_func(directory, backup_dir='/path/to/backup'): """ Backup all '.log' files in a specified directory to a tar.gz file and delete the original files after backup. The backup file is named 'logs_backup.tar.gz' and placed in the specified backup directory. ...
import unittest import tempfile import os import subprocess import glob import shutil class TestCases(unittest.TestCase): def setUp(self): self.temp_dir = tempfile.mkdtemp() self.temp_backup_dir = tempfile.mkdtemp() # Create some log files and some non-log files for i in ran...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/18
Divide a CSV file into several smaller files and shuffle the lines in each file. This function takes a CSV file path as input, divides it into smaller files using the shell 'split' command, and shuffles the rows in each of the resulting files. The output files are named with a 'split_' prefix. The function should outpu...
import subprocess import csv import glob import random import os def task_func(file): """ Divide a CSV file into several smaller files and shuffle the lines in each file. This function takes a CSV file path as input, divides it into smaller files using the shell 'split' command, and shuffles the ...
import subprocess import csv import glob import random import os def task_func(file): """ Divide a CSV file into several smaller files and shuffle the lines in each file. This function takes a CSV file path as input, divides it into smaller files using the shell 'split' command, and shuffles the ...
import unittest import csv import os import tempfile class TestCases(unittest.TestCase): def setUp(self): # Create a temporary directory to hold the files self.test_dir = tempfile.mkdtemp() self.small_csv_path = os.path.join(self.test_dir, "small.csv") self.medium_csv_path = os.path....
[ "mutate_edge_case_guards" ]
1
BigCodeBench/19
Zips all files (not including subdirectories) located in the specified directory and returns the path to the created zip file. Note that: Notes: The zip name is always 'files.zip' The function should raise the exception for: FileNotFoundError: if the specified directory does not exist The function should output with: ...
import os import glob import zipfile def task_func(directory): """ Zips all files (not including subdirectories) located in the specified directory and returns the path to the created zip file. Parameters: directory (str): The directory path containing the files to be zipped. Returns: ...
import os import glob import zipfile def task_func(directory): """ Zips all files (not including subdirectories) located in the specified directory and returns the path to the created zip file. Parameters: directory (str): The directory path containing the files to be zipped. Returns: ...
import unittest import os import tempfile import zipfile class TestCases(unittest.TestCase): def setUp(self): """Setup a temporary directory before each test.""" self.test_dir = tempfile.mkdtemp() def tearDown(self): """Clean up the temporary directory after each test.""" ...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/23
Alternates elements from two numeric lists, calculates the absolute difference of each element from a predefined threshold, and returns the element closest to this threshold. Note that: Notes: If l1 and l2 are of different lengths, elements from the longer list without a corresponding pair in the shorter list will not ...
import numpy as np from itertools import zip_longest def task_func(l1, l2,THRESHOLD = 0.5): """ Alternates elements from two numeric lists, calculates the absolute difference of each element from a predefined threshold, and returns the element closest to this threshold. Parameters: l1 (list):...
import numpy as np from itertools import zip_longest def task_func(l1, l2, THRESHOLD=0.5): """ Alternates elements from two numeric lists, calculates the absolute difference of each element from a predefined threshold, and returns the element closest to this threshold. Parameters: l1 (list): ...
import unittest class TestCases(unittest.TestCase): def test_case_1(self): # Test with two lists of equal length where one element exactly matches the threshold. l1 = [0, 0.5, 2, 3, 4] l2 = [10, 11, 12, 13, 14] self.assertEqual(task_func(l1, l2), 0.5) def test_case_2(self): ...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/24
Hashes a password using the PBKDF2 HMAC algorithm with SHA-256 as the hashing algorithm, combined with a randomly generated salt, and returns both the salt and the hashed password, each base64-encoded. The function should raise the exception for: ValueError if the password is None or empty The function should output wi...
import base64 import hashlib import os def task_func(password, SALT_LENGTH = 32): """ Hashes a password using the PBKDF2 HMAC algorithm with SHA-256 as the hashing algorithm, combined with a randomly generated salt, and returns both the salt and the hashed password, each base64-encoded. Paramete...
import base64 import hashlib import os def task_func(password, SALT_LENGTH=32): """ Hashes a password using the PBKDF2 HMAC algorithm with SHA-256 as the hashing algorithm, combined with a randomly generated salt, and returns both the salt and the hashed password, each base64-encoded. Parameters...
import unittest import base64 import hashlib import os class TestCases(unittest.TestCase): def decode_and_regenerate_password(self, encoded_salt, encoded_hashed_password, original_password): """ Helper function to decode base64 encoded salt and password, and regenerate the hashed password. """ decod...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/30
Validate the structure and contents of a JSON file against predefined schema rules and retrieve a specified attribute from the JSON object. Ensures that all required fields exist, match their defined types, and checks the validity of the email format using a regular expression. Errors: - Raises ValueError if the file d...
import json import os import re def task_func( file_path, attribute, INPUT_JSON={ "type": "object", "properties": { "name": {"type": str}, "age": {"type": int}, "email": {"type": str} }, "required": ["name", "age", "email"] }, ...
import json import os import re def task_func(file_path, attribute, INPUT_JSON={'type': 'object', 'properties': {'name': {'type': str}, 'age': {'type': int}, 'email': {'type': str}}, 'required': ['name', 'age', 'email']}, EMAIL_REGEX='^[a-z0-9]+[\\._]?[a-z0-9]+[@]\\w+[.]\\w{2,3}$'): """ Validate the structure ...
import unittest import json import os import re EMAIL_REGEX = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" class TestCases(unittest.TestCase): def setUp(self): # Creating a dummy JSON file self.filepath = '/tmp/test_data.json' self.valid_data = { "name": "John Doe", ...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/33
Calculate the product of the second values in each tuple in a list of tuples and return the product as a single-element numeric array. The function should output with: numpy.ndarray: A 1D numpy array containing a single element that is the product of the second values in the list of tuples. You should write self-co...
import numpy as np from functools import reduce def task_func(list_of_pairs): """ Calculate the product of the second values in each tuple in a list of tuples and return the product as a single-element numeric array. Parameters: list_of_pairs (list): A list of tuples, where the first element is t...
import numpy as np from functools import reduce def task_func(list_of_pairs): """ Calculate the product of the second values in each tuple in a list of tuples and return the product as a single-element numeric array. Parameters: list_of_pairs (list): A list of tuples, where the first element is t...
import unittest import numpy as np from functools import reduce class TestCases(unittest.TestCase): def test_case_1(self): # Basic test case with positive and negative numbers list_of_pairs = [('Fruits', 5), ('Vegetables', 9), ('Dairy', -1), ('Bakery', -2), ('Meat', 4)] expected_output ...
[ "mutate_list_indexing" ]
1
BigCodeBench/34
Create a word cloud from text after removing URLs and plot it. The function should raise the exception for: ValueError("No words available to generate a word cloud after removing URLs."): If there are no words available to generate a word cloud after removing URLs. The function should output with: WordCloud object:...
import re from wordcloud import WordCloud import matplotlib.pyplot as plt def task_func(text): """ Create a word cloud from text after removing URLs and plot it. Parameters: - text (str): The text to analyze. Returns: WordCloud object: The generated word cloud. Raises: ValueError("No...
import re from wordcloud import WordCloud import matplotlib.pyplot as plt def task_func(text): """ Create a word cloud from text after removing URLs and plot it. Parameters: - text (str): The text to analyze. Returns: WordCloud object: The generated word cloud. Raises: ValueError("No ...
import unittest class TestCases(unittest.TestCase): """Test cases for the task_func function.""" def test_case_1(self): text = ( f"Visit https://www.example1.com for more info. This is the first sentence." ) result = task_func(text) self.assertIsInstance(result, WordC...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/36
Replace all elements in DataFrame columns that do not exist in the TARGET_VALUES array with zeros, then perform a Box-Cox transformation on each column (if data is not constant, add 1 to account for zeros) and display the resulting KDE plots. The function should output with: pandas.DataFrame: The transformed DataFr...
import numpy as np from scipy import stats import matplotlib.pyplot as plt TARGET_VALUES = np.array([1, 3, 4]) def task_func(df): """ Replace all elements in DataFrame columns that do not exist in the TARGET_VALUES array with zeros, then perform a Box-Cox transformation on each column (if data is not constant...
import numpy as np from scipy import stats import matplotlib.pyplot as plt TARGET_VALUES = np.array([1, 3, 4]) def task_func(df): """ Replace all elements in DataFrame columns that do not exist in the TARGET_VALUES array with zeros, then perform a Box-Cox transformation on each column (if data is not constant,...
import unittest import pandas as pd class TestCases(unittest.TestCase): """Test cases for the task_func function.""" def test_case_1(self): df = pd.DataFrame( { "A": [1, 2, 3, 4, 3, 2, 2, 1], "B": [7, 8, 9, 1, 2, 3, 5, 6], "C": [9, 7, 3, 1, 8, ...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/40
Calculate the Z-values of a 2D data matrix, calculate the mean value of each row and then visualize the correlation matrix of the Z-values with a heatmap. The function should output with: tuple: A tuple containing: pandas.DataFrame: A DataFrame with columns 'Feature 1', 'Feature 2', ..., 'Feature n' containing ...
import pandas as pd import seaborn as sns from scipy.stats import zscore def task_func(data_matrix): """ Calculate the Z-values of a 2D data matrix, calculate the mean value of each row and then visualize the correlation matrix of the Z-values with a heatmap. Parameters: data_matrix (numpy.array): Th...
import pandas as pd import seaborn as sns from scipy.stats import zscore def task_func(data_matrix): """ Calculate the Z-values of a 2D data matrix, calculate the mean value of each row and then visualize the correlation matrix of the Z-values with a heatmap. Parameters: data_matrix (numpy.array): The...
import unittest import numpy as np import matplotlib class TestCases(unittest.TestCase): """Test cases for the task_func function.""" def test_case_1(self): data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) df, ax = task_func(data) self.assertTrue(isinstance(df, pd.DataFrame)) s...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/42
Apply PCA with n_components components to a 2D data matrix, calculate the mean value of each component, and then return the cumulative explained variance of the components in a plot. - The function returns a dataframe with columns 'Component 1', 'Component 2', ... etc. - Each row of the dataframe correspond to a row of...
import pandas as pd import matplotlib.pyplot as plt from sklearn.decomposition import PCA def task_func(data_matrix, n_components=2): """ Apply PCA with n_components components to a 2D data matrix, calculate the mean value of each component, and then return the cumulative explained variance of the components ...
import pandas as pd import matplotlib.pyplot as plt from sklearn.decomposition import PCA def task_func(data_matrix, n_components=2): """ Apply PCA with n_components components to a 2D data matrix, calculate the mean value of each component, and then return the cumulative explained variance of the components i...
import unittest import numpy as np class TestCases(unittest.TestCase): """Test cases for the task_func function.""" def test_case_1(self): data = np.array([[6, 8, 1, 3, 4], [-1, 0, 3, 5, 1]]) df, ax = task_func(data) self.assertEqual(df.shape, (2, 3)) self.assertTrue("Mean" in df...
[ "mutate_range_bounds" ]
1
BigCodeBench/46
Calculate Z-scores for numeric columns in a DataFrame and draw a histogram for each column. - Missing values are replaced by the column's average. - The histograms are plotted with 10 bins. The function should output with: tuple: 1. pandas.DataFrame: A DataFrame with computed z-scores. 2. list: A list of Ax...
from scipy.stats import zscore import matplotlib.pyplot as plt def task_func(df): """ Calculate Z-scores for numeric columns in a DataFrame and draw a histogram for each column. - Missing values are replaced by the column's average. - The histograms are plotted with 10 bins. Parameters: - df ...
from scipy.stats import zscore import matplotlib.pyplot as plt def task_func(df): """ Calculate Z-scores for numeric columns in a DataFrame and draw a histogram for each column. - Missing values are replaced by the column's average. - The histograms are plotted with 10 bins. Parameters: - df (...
import unittest import pandas as pd import numpy as np class TestCases(unittest.TestCase): """Test cases for the task_func function.""" def test_case_1(self): df = pd.DataFrame( { "col1": [1, 7, 3], "col2": [4, 5, 7], "col3": [None, None, None]...
[ "mutate_list_indexing" ]
1
BigCodeBench/48
Generate n random Unix timestamps and convert them to strings formatted as UTC DATE_FORMAT. Plot a histogram of the distribution of the generated timestamps. If an output path is provided, save the histogram to the specified path. Otherwise, display the plot. The function should output with: list: The list of n for...
import time from datetime import datetime import random import matplotlib.pyplot as plt # Constants DATE_FORMAT = "%Y-%m-%d %H:%M:%S" def task_func(n, output_path=None): """ Generate n random Unix timestamps and convert them to strings formatted as UTC DATE_FORMAT. Plot a histogram of the distribution of...
import time from datetime import datetime import random import matplotlib.pyplot as plt DATE_FORMAT = '%Y-%m-%d %H:%M:%S' def task_func(n, output_path=None): """ Generate n random Unix timestamps and convert them to strings formatted as UTC DATE_FORMAT. Plot a histogram of the distribution of the generated...
import unittest import os class TestCases(unittest.TestCase): """Test cases for the task_func function.""" def setUp(self): self.test_dir = "data/task_func" os.makedirs(self.test_dir, exist_ok=True) self.o_1 = os.path.join(self.test_dir, "histogram_1.png") def tearDown(self) -> None:...
[ "mutate_range_bounds" ]
1
BigCodeBench/49
Convert a list of Unix timestamps to date objects, create a Pandas DataFrame, and draw a histogram. - The date format should be as DATE_FORMAT. - The DataFrame should have 'Timestamp' and 'Datetime' as column names. - If the list of timestamps is empty, raise a ValueError with the message "Input list of timestamps is e...
from datetime import datetime import pandas as pd import matplotlib.pyplot as plt # Constants DATE_FORMAT = "%Y-%m-%d %H:%M:%S" def task_func(timestamps): """ Convert a list of Unix timestamps to date objects, create a Pandas DataFrame, and draw a histogram. - The date format should be as DATE_FORMAT. ...
from datetime import datetime import pandas as pd import matplotlib.pyplot as plt DATE_FORMAT = '%Y-%m-%d %H:%M:%S' def task_func(timestamps): """ Convert a list of Unix timestamps to date objects, create a Pandas DataFrame, and draw a histogram. - The date format should be as DATE_FORMAT. - The DataFr...
import unittest class TestCases(unittest.TestCase): """Test cases for the task_func function.""" def setUp(self): self.test_data = [ [1318935276, 1342905276, 23074268], [4235087541, 1234653346, 19862358], [], [1156829289], [1000000000, 20000000...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/54
Analyze a text by creating a document term matrix with CountVectorizer. The text contains several sentences, each separated by a period. Ignore empty sentences. The function should output with: DataFrame: A pandas DataFrame with the document-term matrix. Its column names should be adapted from the vectorizer featur...
import pandas as pd import regex as re from sklearn.feature_extraction.text import CountVectorizer def task_func(text): """ Analyze a text by creating a document term matrix with CountVectorizer. The text contains several sentences, each separated by a period. Ignore empty sentences. Parameters: ...
import pandas as pd import regex as re from sklearn.feature_extraction.text import CountVectorizer def task_func(text): """ Analyze a text by creating a document term matrix with CountVectorizer. The text contains several sentences, each separated by a period. Ignore empty sentences. Parameters: t...
import unittest class TestCases(unittest.TestCase): """Test cases for the task_func function.""" def test_case_1(self): # Test with a basic input text = "This is a sample sentence. This sentence contains sample words." dtm = task_func(text) # Assertions self.assertEqual( ...
[ "mutate_comparison_operators" ]
1
BigCodeBench/55
Given a text as input, the function should split it into multiple sentences and build a dictionary where each key is associated with a sentence and the corresponding value is the number of words in the sentence. The function returns a pandas Series built from the dictionary. - The keys of the dictionary (which correspo...
import re import pandas as pd STOPWORDS = ["Those", "are", "the", "words", "to", "ignore"] def task_func(text): """ Given a text as input, the function should split it into multiple sentences and build a dictionary where each key is associated with a sentence and the corresponding value is the number of word...
import re import pandas as pd STOPWORDS = ['Those', 'are', 'the', 'words', 'to', 'ignore'] def task_func(text): """ Given a text as input, the function should split it into multiple sentences and build a dictionary where each key is associated with a sentence and the corresponding value is the number of words ...
import unittest class TestCases(unittest.TestCase): """Test cases for the task_func function.""" def test_case_1(self): text = "This is a sample sentence. This sentence contains sample words." expected_output = pd.Series({"Sentence 1": 5, "Sentence 2": 4}) result = task_func(text) ...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/64
You are given a list of elements. Each element is a list with the same length as COLUMNS, representing one row a dataframe df to create. Visualize the distribution of different values in a column "col3" of a pandas DataFrame df, grouped by "col1" and "col2," using a heatmap. The function should output with: tuple: ...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Constants COLUMNS = ['col1', 'col2', 'col3'] def task_func(data): """ You are given a list of elements. Each element is a list with the same length as COLUMNS, representing one row a dataframe df to create. Visualize the distribution ...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt COLUMNS = ['col1', 'col2', 'col3'] def task_func(data): """ You are given a list of elements. Each element is a list with the same length as COLUMNS, representing one row a dataframe df to create. Visualize the distribution of different ...
import unittest class TestCases(unittest.TestCase): """Test cases for the task_func function.""" def test_case_1(self): data = [[1, 1, 1], [1, 1, 1], [1, 1, 2], [1, 2, 3], [1, 2, 3], [1, 2, 3], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2, 3], [2, 2, 3], [2, 2, 3]] df = pd.DataFrame(data, columns=COLU...
[ "mutate_list_indexing" ]
1
BigCodeBench/70
Load e-mail data from a JSON file, convert it into a Pandas DataFrame, calculate the sum and mean of the list associated with each e-mail, and then record those values. Additionally, it plots the sum and mean values for each email. If there is no e-mail data, return an empty dataframe with the right columns (['email', ...
import pandas as pd import json import numpy as np # Constants COLUMNS = ['email', 'list'] def task_func(json_file): """ Load e-mail data from a JSON file, convert it into a Pandas DataFrame, calculate the sum and mean of the list associated with each e-mail, and then record those values. Additionally, it...
import pandas as pd import json import numpy as np COLUMNS = ['email', 'list'] def task_func(json_file): """ Load e-mail data from a JSON file, convert it into a Pandas DataFrame, calculate the sum and mean of the list associated with each e-mail, and then record those values. Additionally, it plots the su...
import os import shutil import unittest class TestCases(unittest.TestCase): """Test cases for the task_func function.""" def setUp(self): self.test_dir = 'data/task_func' os.makedirs(self.test_dir, exist_ok=True) self.f_1 = os.path.join(self.test_dir, "json_1.json") self.f_2 = os...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/72
Traverse a directory for CSV files a get the file with the longest filename. From that CSV file, load e-mail data, convert it into a Pandas DataFrame, calculate the sum, mean and median of the list associated with each e-mail, and then draw a histogram of the median. - The column names of each CSV files are 'email' and...
import pandas as pd import os import numpy as np import ast def task_func(directory): """ Traverse a directory for CSV files a get the file with the longest filename. From that CSV file, load e-mail data, convert it into a Pandas DataFrame, calculate the sum, mean and median of the list associated with each e-...
import pandas as pd import os import numpy as np import ast def task_func(directory): """ Traverse a directory for CSV files a get the file with the longest filename. From that CSV file, load e-mail data, convert it into a Pandas DataFrame, calculate the sum, mean and median of the list associated with each e-...
import unittest import shutil import pandas as pd import matplotlib.pyplot as plt class TestCases(unittest.TestCase): """Test cases for the task_func function.""" def setUp(self): self.test_dir = "data/task_func" os.makedirs(self.test_dir, exist_ok=True) self.dir_1 = os.path.join(self.te...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/74
This function resolves the IP address of the given host and then uses the IP address to fetch geolocation information from the ipinfo.io API. The function is robust against various common errors, such as invalid hostnames, network issues, or problems with the geolocation service. The function should raise the exception...
import socket import requests def task_func(host): """ This function resolves the IP address of the given host and then uses the IP address to fetch geolocation information from the ipinfo.io API. The function is robust against various common errors, such as invalid hostnames, network issues, or probl...
import socket import requests def task_func(host): """ This function resolves the IP address of the given host and then uses the IP address to fetch geolocation information from the ipinfo.io API. The function is robust against various common errors, such as invalid hostnames, network issues, or probl...
import unittest import unittest.mock as mock import socket import requests class TestCases(unittest.TestCase): @mock.patch('socket.gethostbyname') @mock.patch('requests.get') def test_valid_host(self, mock_get, mock_gethostbyname): # Simulates a valid response scenario. mock_gethostbyname.re...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/75
Appends randomly generated sales data for specified fruits over a given range of days to a DataFrame, and returns a seaborn boxplot of the sales. The function should raise the exception for: TypeError: If 'df' is not a pandas DataFrame. ValueError: If 'df' is not empty or If 'sales_lower_bound' is not less than 'sales...
import pandas as pd import numpy as np import itertools from datetime import datetime, timedelta import seaborn as sns def task_func(df, fruits=None, days=None, seed=None, sales_lower_bound=1, sales_upper_bound=50): """ Appends randomly generated sales data for specified fruits over a given range of days to a ...
import pandas as pd import numpy as np import itertools from datetime import datetime, timedelta import seaborn as sns def task_func(df, fruits=None, days=None, seed=None, sales_lower_bound=1, sales_upper_bound=50): """ Appends randomly generated sales data for specified fruits over a given range of days to a ...
import unittest import pandas as pd import numpy as np from datetime import datetime class TestCases(unittest.TestCase): def setUp(self): # Define the default date range for comparison in tests self.default_days = [datetime(2024, 1, 1) + timedelta(days=x) for x in range(7)] def test_default_days...
[ "mutate_range_bounds" ]
1
BigCodeBench/82
Creates a Flask application with configured user authentication using Flask-Login. It defines routes for login, logout, and a protected page. The user authentication is managed with a simple User class and a login form using Flask-WTF. The application uses dynamic configuration for security and template rendering. The ...
from flask import Flask, render_template, redirect, url_for from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired, Length from werkzeug...
from flask import Flask, render_template, redirect, url_for from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired, Length from werkzeug...
import unittest from unittest.mock import patch, MagicMock import os import shutil from flask_login import login_user class TestCases(unittest.TestCase): def setUp(self): current_file_path = os.path.abspath("__file__") current_directory = os.path.dirname(current_file_path) self.secret_key = ...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/84
Generate a sales report with randomly simulated sales and profit data for a given list of products. The data is aggregated by product and sorted by total profit in descending order. The function should raise the exception for: ValueError: If n_samples is not a positive integer, or if sales_lower is greater than sales_u...
import numpy as np import pandas as pd def task_func(products, n_samples=100, sales_lower=50, sales_upper=200, profit_margin_min=0.1, profit_margin_max=0.5, random_seed=42): """ Generate a sales report with randomly simulated sales and profit data for a given list of products. The data is aggregated by pro...
import numpy as np import pandas as pd def task_func(products, n_samples=100, sales_lower=50, sales_upper=200, profit_margin_min=0.1, profit_margin_max=0.5, random_seed=42): """ Generate a sales report with randomly simulated sales and profit data for a given list of products. The data is aggregated by pro...
import pandas as pd import unittest class TestCases(unittest.TestCase): def test_random_reproducibility(self): report1 = task_func(["iPhone", "iPad"], n_samples=50, sales_lower=50, sales_upper=200, profit_margin_min=0.1, profit_margin_max=0.5, random_seed=42) report2 = task_func(["iPhone", "iPad"], ...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/85
Generate and plot weather data for a specified date range. This function creates a DataFrame containing simulated daily weather data within the specified date range. It generates random values for temperature, humidity, and wind speed for each day. The function also plots these parameters over the date range and return...
import numpy as np import pandas as pd from datetime import timedelta def task_func(start_date, end_date, random_seed=42): """ Generate and plot weather data for a specified date range. This function creates a DataFrame containing simulated daily weather data within the specified date range. It g...
import numpy as np import pandas as pd from datetime import timedelta def task_func(start_date, end_date, random_seed=42): """ Generate and plot weather data for a specified date range. This function creates a DataFrame containing simulated daily weather data within the specified date range. It g...
import unittest from datetime import datetime class TestCases(unittest.TestCase): def test_random_reproducibility(self): start_date = datetime(2021, 1, 1) end_date = datetime(2021, 1, 10) df1, _ = task_func(start_date, end_date, random_seed=42) df2, _ = task_func(start_date, end_date...
[ "mutate_comparison_operators" ]
1
BigCodeBench/87
Generates a DataFrame containing ratings for a given list of products. Ratings are generated randomly based on the provided weights. The DataFrame is sorted by ratings in descending order. The function should output with: pandas.DataFrame: A DataFrame with two columns: 'Product' and 'Rating', sorted by 'Rating' in ...
import pandas as pd from random import choices, seed def task_func(products, ratings, weights, random_seed=42): """ Generates a DataFrame containing ratings for a given list of products. Ratings are generated randomly based on the provided weights. The DataFrame is sorted by ratings in descending order. ...
import pandas as pd from random import choices, seed def task_func(products, ratings, weights, random_seed=42): """ Generates a DataFrame containing ratings for a given list of products. Ratings are generated randomly based on the provided weights. The DataFrame is sorted by ratings in descending order. ...
import unittest import pandas as pd class TestCases(unittest.TestCase): def setUp(self): self.products = ["iPhone", "iPad", "Macbook", "Airpods", "Apple Watch"] self.ratings = [1, 2, 3, 4, 5] self.weights = [0.05, 0.1, 0.2, 0.3, 0.35] def test_random_reproducibility(self): df1 = ...
[ "mutate_list_indexing" ]
1
BigCodeBench/88
Generate random sales data for each day between a start and end date, inclusive. Returns the data and a plot of sales over time. sales ranges 0 to 500 and it is an integer The function should output with: DataFrame: A pandas DataFrame with columns 'Date' and 'Sales'. Axes: A matplotlib Axes object of the plot s...
import numpy as np import pandas as pd from datetime import datetime, timedelta def task_func(start_date, end_date, seed=42): """ Generate random sales data for each day between a start and end date, inclusive. Returns the data and a plot of sales over time. Parameters: start_date (datetime): The ...
import numpy as np import pandas as pd from datetime import datetime, timedelta def task_func(start_date, end_date, seed=42): """ Generate random sales data for each day between a start and end date, inclusive. Returns the data and a plot of sales over time. Parameters: start_date (datetime): The ...
import unittest class TestCases(unittest.TestCase): def setUp(self): self.start_date = datetime(2021, 1, 1) self.end_date = datetime(2021, 1, 10) def test_random_reproducibility(self): df1, _ = task_func(self.start_date, self.end_date, 42) df2, _ = task_func(self.start_date, self...
[ "mutate_comparison_operators" ]
1
BigCodeBench/90
Calculate the 'k' nearest neighbors by geographic coordinates using a dataset and a target data point. The function returns a list of the 'k' nearest neighbors, sorted in ascending order of their distances from the target. Constants: radius of earth is 6371 km The function should raise the exception for: ValueError: If...
import numpy as np import math def task_func(data, target, k): """ Calculate the 'k' nearest neighbors by geographic coordinates using a dataset and a target data point. The function returns a list of the 'k' nearest neighbors, sorted in ascending order of their distances from the target. Parame...
import numpy as np import math def task_func(data, target, k): """ Calculate the 'k' nearest neighbors by geographic coordinates using a dataset and a target data point. The function returns a list of the 'k' nearest neighbors, sorted in ascending order of their distances from the target. Parame...
import unittest import pandas as pd class TestCases(unittest.TestCase): def setUp(self): self.data = pd.DataFrame([[14, 25], [1, 22], [7, 8], [10, 15]], columns=['Latitude', 'Longitude']) self.target = [10, 15] def test_correct_number_of_neighbors(self): k = 2 result = task_func(...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/92
Perform K-means clustering on a dataset and generate a scatter plot visualizing the clusters and their centroids. The function should raise the exception for: ValueError: If 'data' is not a pd.DataFrame. ValueError: If 'n_clusters' is not an integer greater than 1. The function should output with: tuple: np.nda...
import pandas as pd import matplotlib.pyplot as plt from sklearn.cluster import KMeans from matplotlib.collections import PathCollection def task_func(data, n_clusters=3): """ Perform K-means clustering on a dataset and generate a scatter plot visualizing the clusters and their centroids. Parameters: ...
import pandas as pd import matplotlib.pyplot as plt from sklearn.cluster import KMeans from matplotlib.collections import PathCollection def task_func(data, n_clusters=3): """ Perform K-means clustering on a dataset and generate a scatter plot visualizing the clusters and their centroids. Parameters: ...
import unittest from matplotlib.collections import PathCollection # Correct import import numpy as np class TestCases(unittest.TestCase): def setUp(self): np.random.seed(42) self.data = pd.DataFrame(np.random.rand(100, 2), columns=['Feature1', 'Feature2']) def test_cluster_centers(self): ...
[ "mutate_comparison_operators" ]
1
BigCodeBench/95
Generates a DataFrame with simulated monthly sales data for various product categories, ensuring reproducibility through the use of a random seed. Note that: Notes: The function sets the random seed at the beginning of execution to ensure that the generated sales data is the same for any given seed value. The sales dat...
import pandas as pd from random import randint, uniform, seed def task_func(categories=None, months=None, random_seed=42): """ Generates a DataFrame with simulated monthly sales data for various product categories, ensuring reproducibility through the use of a random seed. Parameters: categories (...
import pandas as pd from random import randint, uniform, seed def task_func(categories=None, months=None, random_seed=42): """ Generates a DataFrame with simulated monthly sales data for various product categories, ensuring reproducibility through the use of a random seed. Parameters: categories (...
import unittest import pandas as pd class TestCases(unittest.TestCase): def test_reproducibility(self): df1 = task_func(random_seed=42) df2 = task_func(random_seed=42) pd.testing.assert_frame_equal(df1, df2) def test_dataframe_structure(self): df = task_func() self.assert...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/97
Generates all possible combinations of the provided numbers in a given list for each possible length. For each combination, it computes the product of the numbers in the combination. It then computes the logarithm of each product and sums these logarithms to produce the final result. The function should output with: ...
import math import itertools from functools import reduce def task_func(numbers): """ Generates all possible combinations of the provided numbers in a given list for each possible length. For each combination, it computes the product of the numbers in the combination. It then computes the logarithm of ...
import math import itertools from functools import reduce def task_func(numbers): """ Generates all possible combinations of the provided numbers in a given list for each possible length. For each combination, it computes the product of the numbers in the combination. It then computes the logarithm of ...
import unittest import math class TestCases(unittest.TestCase): def test_return_type(self): """Test that the function returns a float with a non-empty list.""" result = task_func([2, 3, 5]) self.assertIsInstance(result, float) def test_specific_case(self): """Test the function wi...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/98
Creates a list of random strings, each of a specified length, and counts the frequency of each character across all strings. The function then returns the characters and their frequencies sorted by frequency in descending order. The random strings are composed of ASCII lowercase characters. The function should output w...
import random import string from collections import Counter def task_func(num_strings, string_length): """ Creates a list of random strings, each of a specified length, and counts the frequency of each character across all strings. The function then returns the characters and their frequencies sorted b...
import random import string from collections import Counter def task_func(num_strings, string_length): """ Creates a list of random strings, each of a specified length, and counts the frequency of each character across all strings. The function then returns the characters and their frequencies sorted b...
import unittest import random class TestCases(unittest.TestCase): def setUp(self): # This method will be run before each test. random.seed(0) # Set a seed for reproducibility in all tests def test_return_type(self): """ Test that the function returns a list. """ result = task_fu...
[ "mutate_range_bounds" ]
1
BigCodeBench/100
Generates a plot of random time series data for the past 30 days with reproducibility controlled by an optional seed parameter. The plot is styled with Arial font for better readability. The function should raise the exception for: ValueError: If there is an issue generating the data or plot. The function should output...
import matplotlib.pyplot as plt import pandas as pd import random from datetime import datetime def task_func(seed=42): """ Generates a plot of random time series data for the past 30 days with reproducibility controlled by an optional seed parameter. The plot is styled with Arial font for better rea...
import matplotlib.pyplot as plt import pandas as pd import random from datetime import datetime def task_func(seed=42): """ Generates a plot of random time series data for the past 30 days with reproducibility controlled by an optional seed parameter. The plot is styled with Arial font for better rea...
import unittest import pandas as pd class TestCases(unittest.TestCase): def test_plot_attributes(self): ax = task_func() self.assertEqual(ax.get_title(), 'Random Time Series Data', "The plot title does not match.") self.assertEqual(ax.get_xlabel(), 'Date', "The x-axis label does not match."...
[ "mutate_range_bounds" ]
1
BigCodeBench/105
Perform exploratory data analysis on a dataframe. This function converts the 'date' column to an ordinal format, creates a correlation matrix, and generates a pair plot of the dataframe. The title of the plot is 'Correlation Matrix'. The function should raise the exception for: ValueError: If the dataframe is empty, if...
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def task_func(df): """ Perform exploratory data analysis on a dataframe. This function converts the 'date' column to an ordinal format, creates a correlation matrix, and generates a pair plot of the dataframe. Parameters: ...
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def task_func(df): """ Perform exploratory data analysis on a dataframe. This function converts the 'date' column to an ordinal format, creates a correlation matrix, and generates a pair plot of the dataframe. Parameters: ...
import unittest import numpy as np class TestCases(unittest.TestCase): def setUp(self): self.valid_df = pd.DataFrame({ "group": ["A", "A", "A", "B", "B"], "date": pd.to_datetime(["2022-01-02", "2022-01-13", "2022-02-01", "2022-02-23", "2022-03-05"]), "value": [10, 20, 16...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/107
Convert the 'date' column of a DataFrame to ordinal, perform KMeans clustering on 'date' and 'value' columns, and plot the clusters. Required names: x: 'Date (ordinal)' ylabel: 'Value' title: 'KMeans Clustering of Value vs Date' The function should raise the exception for: ValueError: If the DataFrame is empty or lacks...
import pandas as pd from sklearn.cluster import KMeans import matplotlib.pyplot as plt def task_func(df, n_clusters=3, random_state=0): """ Convert the 'date' column of a DataFrame to ordinal, perform KMeans clustering on 'date' and 'value' columns, and plot the clusters. Parameters: df (pandas.Da...
import pandas as pd from sklearn.cluster import KMeans import matplotlib.pyplot as plt def task_func(df, n_clusters=3, random_state=0): """ Convert the 'date' column of a DataFrame to ordinal, perform KMeans clustering on 'date' and 'value' columns, and plot the clusters. Parameters: df (pandas.Da...
import unittest import pandas as pd class TestCases(unittest.TestCase): def setUp(self): self.df = pd.DataFrame({ "group": ["A", "A", "A", "B", "B"], "date": pd.to_datetime(["2022-01-02", "2022-01-13", "2022-02-01", "2022-02-23", "2022-03-05"]), "value": [10, 20, 16, 31, ...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/108
Decomposes a time series in the 'value' column of a DataFrame into trend, seasonality, and residuals. The function should raise the exception for: ValueError: If 'df' is not a DataFrame, lacks required columns, or contains invalid data types. ValueError: If 'freq' is not a valid frequency string. ValueError: If 'decomp...
import pandas as pd import matplotlib.pyplot as plt from statsmodels.tsa.seasonal import seasonal_decompose def task_func(df, freq='D', decomposition_model='multiplicative'): """ Decomposes a time series in the 'value' column of a DataFrame into trend, seasonality, and residuals. Parameters: df (DataF...
import pandas as pd import matplotlib.pyplot as plt from statsmodels.tsa.seasonal import seasonal_decompose def task_func(df, freq='D', decomposition_model='multiplicative'): """ Decomposes a time series in the 'value' column of a DataFrame into trend, seasonality, and residuals. Parameters: df (DataF...
import unittest import pandas as pd from statsmodels.tsa.seasonal import DecomposeResult class TestCases(unittest.TestCase): def setUp(self): # Data setup with sufficient data points date_range = pd.date_range(start='2022-01-01', periods=30, freq='D') self.df = pd.DataFrame({ "gr...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/110
Draw and return the daily turnover line chart from a pandas DataFrame. The function should raise the exception for: ValueError: If 'df' is not a DataFrame or lacks 'Date' or 'Sales' columns, or has no data to plot. The function should output with: Axes: Matplotlib Axes object with the line chart. You should write s...
import pandas as pd import matplotlib.pyplot as plt def task_func(df): """ Draw and return the daily turnover line chart from a pandas DataFrame. Parameters: df (DataFrame): A pandas DataFrame with 'Date' and 'Sales' columns. Returns: Axes: Matplotlib Axes object with the line chart. Rai...
import pandas as pd import matplotlib.pyplot as plt def task_func(df): """ Draw and return the daily turnover line chart from a pandas DataFrame. Parameters: df (DataFrame): A pandas DataFrame with 'Date' and 'Sales' columns. Returns: Axes: Matplotlib Axes object with the line chart. Rai...
import unittest import pandas as pd import numpy as np import matplotlib.pyplot as plt class TestCases(unittest.TestCase): def setUp(self): np.random.seed(42) self.df = pd.DataFrame({ 'Date': pd.date_range(start='1/1/2021', periods=10), 'Sales': np.random.randint(100, 2000, s...
[ "mutate_comparison_operators" ]
1
BigCodeBench/113
Updates a given dictionary by adding 10 random elements based on the 'keys' parameter, with values as random integers from 1 to 100. It saves the JSON representation of the updated dictionary to a file and the counts of each key to a separate text file. Note that: This function modifies the input dictionary in place. T...
import json from collections import Counter import random def task_func(my_dict, keys): """ Updates a given dictionary by adding 10 random elements based on the 'keys' parameter, with values as random integers from 1 to 100. It saves the JSON representation of the updated dictionary to a file and the c...
import json from collections import Counter import random def task_func(my_dict, keys): """ Updates a given dictionary by adding 10 random elements based on the 'keys' parameter, with values as random integers from 1 to 100. It saves the JSON representation of the updated dictionary to a file and the c...
import unittest from unittest.mock import patch import os class TestCases(unittest.TestCase): def setUp(self): self.keys = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] def tearDown(self): json_filename = "updated_dictionary.json" txt_filename = "key_frequencies.txt" if os.p...
[ "mutate_comparison_operators" ]
1
BigCodeBench/114
Updates a dictionary by adding a normalized version of a numpy array found under the 'array' key. The normalization is performed using MinMaxScaler, scaling each value to fall between 0 and 1. Note that: Notes: The function modifies the dictionary in-place and does not create a new dictionary. The function assumes that...
import numpy as np from sklearn.preprocessing import MinMaxScaler def task_func(my_dict): """ Updates a dictionary by adding a normalized version of a numpy array found under the 'array' key. The normalization is performed using MinMaxScaler, scaling each value to fall between 0 and 1. Parameters: ...
import numpy as np from sklearn.preprocessing import MinMaxScaler def task_func(my_dict): """ Updates a dictionary by adding a normalized version of a numpy array found under the 'array' key. The normalization is performed using MinMaxScaler, scaling each value to fall between 0 and 1. Parameters: ...
import unittest import numpy as np from unittest.mock import patch class TestCases(unittest.TestCase): def test_return_type(self): """Test that the function returns a dictionary.""" result = task_func({'array': np.array([1, 2, 3])}) self.assertIsInstance(result, dict) def test_normalized...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/117
Generate a Pandas DataFrame with randomized student data. This function allows for specifying the total number of students and the randomness seed for reproducible outcomes. Data attributes include student names, ages, genders, and scores, each derived from provided parameters or defaults. Note that: Notes: The 'Name' ...
import pandas as pd import numpy as np from random import choice, seed as set_seed def task_func(num_of_students, seed=42, name_list=None, gender_list=None, age_range=(15, 20), score_range=(50, 100)): """ Generate a Pandas DataFrame with randomized student data. This function allows for specifying the tot...
import pandas as pd import numpy as np from random import choice, seed as set_seed def task_func(num_of_students, seed=42, name_list=None, gender_list=None, age_range=(15, 20), score_range=(50, 100)): """ Generate a Pandas DataFrame with randomized student data. This function allows for specifying the tot...
import unittest import pandas as pd import numpy as np class TestCases(unittest.TestCase): def test_with_seed(self): df1 = task_func(5, seed=42) df_list = df1.apply(lambda row: ','.join(row.values.astype(str)), axis=1).tolist() expect = ['John,18,Male,78', 'Sara,17,Male,57', 'Mike,19...
[ "mutate_list_indexing" ]
1
BigCodeBench/118
Scans a specified directory for JSON files and copies them to a backup directory. If the backup directory does not exist, it is created. The function returns a list of paths to the copied files in the backup directory. Note that: The function assumes that the source directory exists and contains JSON files. The functio...
import os import shutil def task_func(directory, backup_directory): """ Scans a specified directory for JSON files and copies them to a backup directory. If the backup directory does not exist, it is created. The function returns a list of paths to the copied files in the backup directory. Paramet...
import os import shutil def task_func(directory, backup_directory): """ Scans a specified directory for JSON files and copies them to a backup directory. If the backup directory does not exist, it is created. The function returns a list of paths to the copied files in the backup directory. Paramet...
import unittest import tempfile import os import shutil class TestCases(unittest.TestCase): def setUp(self): # Setup temporary directories for the test self.directory = tempfile.mkdtemp() self.backup_directory = tempfile.mkdtemp() def tearDown(self): # Only attempt to remove the ...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/121
Adds an item "12" to a list 'my_list', simulates sales data for different categories with an optional seed for reproducibility, and returns the data along with a bar plot. The sales data is a DataFrame with random sales figures for predefined categories. The categories are 'Electronics', 'Fashion', 'Home & Kitchen', 'A...
import pandas as pd import numpy as np def task_func(my_list, seed=42): """ Adds an item "12" to a list 'my_list', simulates sales data for different categories with an optional seed for reproducibility, and returns the data along with a bar plot. The sales data is a DataFrame with random sales figure...
import pandas as pd import numpy as np def task_func(my_list, seed=42): """ Adds an item "12" to a list 'my_list', simulates sales data for different categories with an optional seed for reproducibility, and returns the data along with a bar plot. The sales data is a DataFrame with random sales figure...
import unittest import pandas as pd import matplotlib.pyplot as plt class TestCases(unittest.TestCase): def test_reproducibility_with_seed(self): seed_value = 42 data1, _ = task_func([1, 2, 3], seed=seed_value) data2, _ = task_func([1, 2, 3], seed=seed_value) pd.testing.assert_frame_...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/123
Modify a list by adding the element '12', then concatenate a number of CSV files from a directory into a single DataFrame. The number of files concatenated is determined by the sum of the numbers in the list. The function should raise the exception for: TypeError: If 'my_list' is not a list. FileNotFoundError: If no fi...
import pandas as pd import os import glob def task_func(my_list, file_dir='./data_files/', file_ext='.csv'): """ Modify a list by adding the element '12', then concatenate a number of CSV files from a directory into a single DataFrame. The number of files concatenated is determined by the sum of the ...
import pandas as pd import os import glob def task_func(my_list, file_dir='./data_files/', file_ext='.csv'): """ Modify a list by adding the element '12', then concatenate a number of CSV files from a directory into a single DataFrame. The number of files concatenated is determined by the sum of the ...
import unittest import pandas as pd import os def create_dummy_csv(): test_dir = './data_files/' os.makedirs(test_dir, exist_ok=True) for i in range(3): df = pd.DataFrame({'A': range(3), 'B': range(3, 6)}) df.to_csv(f'{test_dir}file_{i}.csv', index=False) def tearDown_dummy(): # Clean up...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/124
Enhances 'my_list' by appending the number 12, then generates a list of random integers based on the sum of elements in 'my_list', limited by 'size'. It measures the time taken for this process and plots a histogram of the generated random numbers. The size of the random numbers list is determined by the sum of the num...
from random import randint,seed as random_seed import time import matplotlib.pyplot as plt def task_func(my_list, size=100, seed=100): """ Enhances 'my_list' by appending the number 12, then generates a list of random integers based on the sum of elements in 'my_list', limited by 'size'. It measures the t...
from random import randint, seed as random_seed import time import matplotlib.pyplot as plt def task_func(my_list, size=100, seed=100): """ Enhances 'my_list' by appending the number 12, then generates a list of random integers based on the sum of elements in 'my_list', limited by 'size'. It measures the ...
import unittest class TestCases(unittest.TestCase): def test_output_types(self): my_list = [1, 2, 3] time_taken, ax = task_func(my_list) self.assertIsInstance(time_taken, float) self.assertIsInstance(ax, plt.Axes) bar_heights = [rect.get_height() for rect in ax.containers[0]]...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/126
Create a report on the number of animals in a zoo. For each animal, generate a random count within a specified range, calculate the mean, median, and standard deviation of these counts, and return a DataFrame with these statistics. Additionally, generate a bar chart of the counts. Note that: The mode is not included in...
import pandas as pd from random import randint, seed as random_seed import statistics import numpy as np def task_func(animals=None, seed=42): """ Create a report on the number of animals in a zoo. For each animal, generate a random count within a specified range, calculate the mean, median, and standard ...
import pandas as pd from random import randint, seed as random_seed import statistics import numpy as np def task_func(animals=None, seed=42): """ Create a report on the number of animals in a zoo. For each animal, generate a random count within a specified range, calculate the mean, median, and standard ...
import unittest import pandas as pd class TestCases(unittest.TestCase): def test_default_animals(self): report = task_func() self.assertEqual(len(report), 5) # Default number of animals self.assertListEqual(list(report['Animal']), ['Lion', 'Elephant', 'Tiger', 'Giraffe', 'Panda']) ...
[ "mutate_range_bounds" ]
1
BigCodeBench/127
Moves all files from a specified root directory (ROOT_DIR) to a target directory (DEST_DIR) if they match a specific hash value (SPECIFIC_HASH). The function calculates the MD5 hash of each file in ROOT_DIR and moves it if the hash matches SPECIFIC_HASH. Note that: The function assumes the existence of the root directo...
import os import shutil import glob import hashlib def task_func(ROOT_DIR, DEST_DIR, SPECIFIC_HASH): """ Moves all files from a specified root directory (ROOT_DIR) to a target directory (DEST_DIR) if they match a specific hash value (SPECIFIC_HASH). The function calculates the MD5 hash of each file in ROOT...
import os import shutil import glob import hashlib def task_func(ROOT_DIR, DEST_DIR, SPECIFIC_HASH): """ Moves all files from a specified root directory (ROOT_DIR) to a target directory (DEST_DIR) if they match a specific hash value (SPECIFIC_HASH). The function calculates the MD5 hash of each file in ROOT...
import unittest import tempfile import shutil import os import hashlib from pathlib import Path from unittest.mock import patch class TestCases(unittest.TestCase): def setUp(self): # Create a temporary directory for ROOT_DIR and DEST_DIR self.temp_dir = tempfile.TemporaryDirectory() self.roo...
[ "mutate_comparison_operators" ]
1
BigCodeBench/128
Simulates a random walk in a two-dimensional space and draws the path using matplotlib. The walk is determined by randomly choosing directions at each step. The function generates two numpy arrays representing the x and y coordinates of each step and plots these points to visualize the path of the walk. The function sh...
import numpy as np import matplotlib.pyplot as plt from random import randint import math def task_func(POINTS=100): """ Simulates a random walk in a two-dimensional space and draws the path using matplotlib. The walk is determined by randomly choosing directions at each step. The function generates tw...
import numpy as np import matplotlib.pyplot as plt from random import randint import math def task_func(POINTS=100): """ Simulates a random walk in a two-dimensional space and draws the path using matplotlib. The walk is determined by randomly choosing directions at each step. The function generates tw...
import unittest from unittest.mock import patch, MagicMock import numpy as np class TestCases(unittest.TestCase): @patch('matplotlib.pyplot.show') def test_no_error(self, mock_show): """Test that the function runs without error.""" try: task_func(100) # Adjust POINTS value if necess...
[ "mutate_list_indexing" ]
1
BigCodeBench/129
Scrape the first table from a web page and extract data into a Pandas DataFrame. This function scrapes the first table found on the specified web page URL and extracts the data into a DataFrame, where each row in the DataFrame corresponds to a table row (<tr>) from the web page, and each column represents the data cont...
import requests from bs4 import BeautifulSoup import pandas as pd def task_func(url='http://example.com'): """ Scrape the first table from a web page and extract data into a Pandas DataFrame. This function scrapes the first table found on the specified web page URL and extracts the data into a DataFrame, ...
import requests from bs4 import BeautifulSoup import pandas as pd def task_func(url='http://example.com'): """ Scrape the first table from a web page and extract data into a Pandas DataFrame. This function scrapes the first table found on the specified web page URL and extracts the data into a DataFrame, ...
import unittest from unittest.mock import patch, Mock import pandas as pd import requests class TestCases(unittest.TestCase): @patch('requests.get') def test_return_type(self, mock_get): # Simulate HTML content for a successful response mock_get.return_value.ok = True mock_get.return_val...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/130
Converts a hex string to bytes, salts it with a random value of specified size, and computes its SHA256 hash. The function generates a random salt of the specified size, appends it to the byte representation of the hex string, and then computes the SHA256 hash of the salted data. The salt and hash are returned as a tup...
import base64 import binascii import os import hashlib def task_func(hex_str, salt_size): """ Converts a hex string to bytes, salts it with a random value of specified size, and computes its SHA256 hash. The function generates a random salt of the specified size, appends it to the byte representation of th...
import base64 import binascii import os import hashlib def task_func(hex_str, salt_size): """ Converts a hex string to bytes, salts it with a random value of specified size, and computes its SHA256 hash. The function generates a random salt of the specified size, appends it to the byte representation of th...
import unittest from unittest.mock import patch import os class TestCases(unittest.TestCase): def test_return_type(self): """ Test that the function returns a tuple. """ result = task_func("F3BE8080", 16) self.assertIsInstance(result, tuple) def test_salt_and_hash_length(self): "...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/131
Converts a hex string to bytes, salts it with a random value of specified size, and computes its SHA256 hash. The function generates a random salt of the given size, appends it to the byte representation of the hex string, and then computes the SHA256 hash of the salted data. The salt and hash are returned as a tuple. ...
import base64 import binascii import os import hashlib def task_func(hex_str, salt_size): """ Converts a hex string to bytes, salts it with a random value of specified size, and computes its SHA256 hash. The function generates a random salt of the given size, appends it to the byte representation of the ...
import base64 import binascii import os import hashlib def task_func(hex_str, salt_size): """ Converts a hex string to bytes, salts it with a random value of specified size, and computes its SHA256 hash. The function generates a random salt of the given size, appends it to the byte representation of the ...
import unittest from unittest.mock import patch class TestCases(unittest.TestCase): def setUp(self): self.salt_size = 16 # Define salt_size here to use in all tests def test_return_type(self): """Test that the function returns a tuple.""" result = task_func("F3BE8080", self.salt_size) ...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/136
Perform Principal Component Analysis (PCA) on the dataframe and visualize the two main components. The function should raise the exception for: ValueError: If the input is not a DataFrame, or if the DataFrame is empty. The function should output with: DataFrame: A pandas DataFrame with the principal components name...
import pandas as pd from sklearn.decomposition import PCA import matplotlib.pyplot as plt def task_func(df): """ Perform Principal Component Analysis (PCA) on the dataframe and visualize the two main components. Parameters: df (DataFrame): The input dataframe containing numerical data. Return...
import pandas as pd from sklearn.decomposition import PCA import matplotlib.pyplot as plt def task_func(df): """ Perform Principal Component Analysis (PCA) on the dataframe and visualize the two main components. Parameters: df (DataFrame): The input dataframe containing numerical data. Return...
import unittest import pandas as pd import numpy as np import matplotlib.pyplot as plt class TestCases(unittest.TestCase): def setUp(self): np.random.seed(42) def test_return_types(self): df = pd.DataFrame(np.random.randint(0, 100, size=(100, 4)), columns=list('ABCD')) pca_df, a...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/139
Draw histograms of numeric columns in a DataFrame and return the plots. Each histogram represents the distribution of values in one numeric column, with the column name as the plot title, 'Value' as the x-axis label, and 'Frequency' as the y-axis label. The function should raise the exception for: ValueError: If the in...
import pandas as pd import numpy as np import matplotlib.pyplot as plt def task_func(df): """ Draw histograms of numeric columns in a DataFrame and return the plots. Each histogram represents the distribution of values in one numeric column, with the column name as the plot title, 'Value' as the x-axi...
import pandas as pd import numpy as np import matplotlib.pyplot as plt def task_func(df): """ Draw histograms of numeric columns in a DataFrame and return the plots. Each histogram represents the distribution of values in one numeric column, with the column name as the plot title, 'Value' as the x-axi...
import unittest import pandas as pd import numpy as np import matplotlib.pyplot as plt class TestCases(unittest.TestCase): def setUp(self): np.random.seed(42) # Set seed for reproducibility self.df = pd.DataFrame({ 'A': np.random.normal(0, 1, 1000), 'B': np.random.exponentia...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/140
Standardize specified numeric columns in a dataframe. The function should raise the exception for: ValueError: If 'df' is not a DataFrame, 'cols' is not a list, or columns in 'cols' don't exist in 'df'. The function should output with: DataFrame: The dataframe with standardized columns. You should write self-contai...
import pandas as pd from sklearn.preprocessing import StandardScaler def task_func(df, cols): """ Standardize specified numeric columns in a dataframe. Parameters: df (DataFrame): The dataframe. cols (list): The columns to standardize. Returns: DataFrame: The dataframe with standardized c...
import pandas as pd from sklearn.preprocessing import StandardScaler def task_func(df, cols): """ Standardize specified numeric columns in a dataframe. Parameters: df (DataFrame): The dataframe. cols (list): The columns to standardize. Returns: DataFrame: The dataframe with standardized c...
import unittest import numpy as np import pandas as pd class TestCases(unittest.TestCase): def setUp(self): np.random.seed(0) self.df = pd.DataFrame({ 'A': np.random.normal(0, 1, 1000), 'B': np.random.exponential(1, 1000), 'C': np.random.randint(0, 100, 1000) ...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/142
Generate diagrams for the sine and cosine functions over the interval [0, 2π]. This function plots the sine and cosine functions, setting appropriate titles and axis labels. The sine function plot is labeled 'Sine function', with x-axis labeled 'x' and y-axis labeled 'sin(x)'. The cosine function plot is labeled 'Cosin...
import numpy as np import matplotlib.pyplot as plt def task_func(): """ Generate diagrams for the sine and cosine functions over the interval [0, 2π]. This function plots the sine and cosine functions, setting appropriate titles and axis labels. Returns: Figure: A Matplotlib Figure object con...
import numpy as np import matplotlib.pyplot as plt def task_func(): """ Generate diagrams for the sine and cosine functions over the interval [0, 2π]. This function plots the sine and cosine functions, setting appropriate titles and axis labels. Returns: Figure: A Matplotlib Figure object con...
import unittest import numpy as np import matplotlib.pyplot as plt class TestCases(unittest.TestCase): def setUp(self): self.fig, self.axs = task_func() def test_return_types(self): self.assertIsInstance(self.fig, plt.Figure) self.assertEqual(len(self.axs), 2) for ax in self.axs:...
[ "mutate_list_indexing" ]
1
BigCodeBench/144
Scans a specified IP address range and sends an HTTP GET request to each IP to verify if it is an active web server. The function requires an IP range in CIDR format (e.g., '192.168.0.0/16') and a timeout value in seconds. It returns a list of IPs where the request returned a status code of 200. If the request is not s...
import ipaddress import requests def task_func(ip_range, timeout): """ Scans a specified IP address range and sends an HTTP GET request to each IP to verify if it is an active web server. The function requires an IP range in CIDR format (e.g., '192.168.0.0/16') and a timeout value in seconds. It return...
import ipaddress import requests def task_func(ip_range, timeout): """ Scans a specified IP address range and sends an HTTP GET request to each IP to verify if it is an active web server. The function requires an IP range in CIDR format (e.g., '192.168.0.0/16') and a timeout value in seconds. It return...
import unittest from unittest.mock import patch, MagicMock import requests # Ensure requests is imported for exception handling class TestCases(unittest.TestCase): @patch('requests.get') def test_return_type(self, mock_get): """Test that the function returns a list.""" mock_get.side_effect = re...
[ "mutate_comparison_operators" ]
1
BigCodeBench/150
Create a profit report for a list of products based on a specific product dictionary that includes the quantity, price, and profit of each product. Additionally, calculate the average price and profit for all considered products, and plot a bar chart of the profit for each product. The function should output with: ...
import pandas as pd import numpy as np def task_func(product_dict, product_keys): """ Create a profit report for a list of products based on a specific product dictionary that includes the quantity, price, and profit of each product. Additionally, calculate the average price and profit for all considered ...
import pandas as pd import numpy as np def task_func(product_dict, product_keys): """ Create a profit report for a list of products based on a specific product dictionary that includes the quantity, price, and profit of each product. Additionally, calculate the average price and profit for all considered p...
import unittest import pandas as pd class TestCases(unittest.TestCase): def setUp(self): # Setup common to all tests: A product dictionary self.product_dict = { 'Apple': [100, 2.5], 'Orange': [80, 3.5], 'Banana': [120, 1.5] } def test_case_1(self): ...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/152
Generates a DataFrame containing random grades for a predefined list of students across a set of courses. Each student will have one grade per course and an average grade calculated across all courses. Note that: The grades are randomly generated for each course using a uniform distribution between 0 and 100. The funct...
import pandas as pd import numpy as np from random import randint # Constants STUDENTS = ['Joe', 'Amy', 'Mark', 'Sara', 'John', 'Emily', 'Zoe', 'Matt'] COURSES = ['Math', 'Physics', 'Chemistry', 'Biology', 'English', 'History', 'Geography', 'Computer Science'] def task_func(): """ Generates a DataFrame conta...
import pandas as pd import numpy as np from random import randint STUDENTS = ['Joe', 'Amy', 'Mark', 'Sara', 'John', 'Emily', 'Zoe', 'Matt'] COURSES = ['Math', 'Physics', 'Chemistry', 'Biology', 'English', 'History', 'Geography', 'Computer Science'] def task_func(): """ Generates a DataFrame containing random g...
import unittest from unittest.mock import patch import random class TestCases(unittest.TestCase): def setUp(self): random.seed(0) # Correctly set up the mock within the test execution context self.patcher = patch('random.randint', side_effect=[i % 100 for i in range(800)]) # Assuming 8 stud...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/154
Scans a specified directory for files matching a given pattern and with a certain suffix, then determines their file types. The function returns a dictionary with file names as keys and their corresponding MIME types as values. The function should output with: dict: A dictionary mapping file names to their MIME typ...
import re import os import glob import mimetypes def task_func(directory, file_pattern, suffix): """ Scans a specified directory for files matching a given pattern and with a certain suffix, then determines their file types. The function returns a dictionary with file names as keys and their corresponding ...
import re import os import glob import mimetypes def task_func(directory, file_pattern, suffix): """ Scans a specified directory for files matching a given pattern and with a certain suffix, then determines their file types. The function returns a dictionary with file names as keys and their corresponding ...
import unittest from unittest.mock import patch, mock_open import mimetypes class TestCases(unittest.TestCase): def test_return_type(self): """Test that the function returns a dictionary.""" with patch('os.chdir'), patch('glob.glob', return_value=[]), patch('re.search'): result = task_fu...
[ "mutate_list_indexing" ]
1
BigCodeBench/159
Compresses a given NumPy array using gzip compression and returns the compressed data. This method takes a NumPy array as input, compresses it using gzip, and returns the compressed data as bytes. It is useful for efficiently handling large datasets, especially when saving space is a concern. The function utilizes the ...
import struct import io import gzip def task_func(newArray): """ Compresses a given NumPy array using gzip compression and returns the compressed data. This method takes a NumPy array as input, compresses it using gzip, and returns the compressed data as bytes. It is useful for efficiently handling la...
import struct import io import gzip def task_func(newArray): """ Compresses a given NumPy array using gzip compression and returns the compressed data. This method takes a NumPy array as input, compresses it using gzip, and returns the compressed data as bytes. It is useful for efficiently handling la...
import unittest import numpy as np class TestCases(unittest.TestCase): def test_return_type(self): """Test that the function returns bytes.""" result = task_func(np.array([1, 2, 3])) self.assertIsInstance(result, bytes) def test_gzipped_data_size(self): """Test the size of the gz...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/160
Processes a given dataset to compute the average of each row, plots the distribution of these averages, and evaluates their normality. The function returns these averages as an additional column in a DataFrame, the plot of the distribution, and the p-value from the normality test if applicable. Note that: The function ...
import pandas as pd import seaborn as sns from scipy import stats # Constants COLUMN_NAMES = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] def task_func(data): """ Processes a given dataset to compute the average of each row, plots the distribution of these averages, and evaluates their normality. The functio...
import pandas as pd import seaborn as sns from scipy import stats COLUMN_NAMES = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] def task_func(data): """ Processes a given dataset to compute the average of each row, plots the distribution of these averages, and evaluates their normality. The function returns thes...
import numpy as np import pandas as pd import unittest import matplotlib.pyplot as plt class TestCases(unittest.TestCase): def setUp(self): # Mock plt.show to prevent it from displaying plots during tests self.addCleanup(plt.close, 'all') def test_basic_functionality(self): data = np.arr...
[ "mutate_list_indexing" ]
1
BigCodeBench/161
Extracts logging information such as message type, timestamp, and the message itself from a log file and stores the data in a CSV format. This utility is ideal for converting plain text logs into a more s tructured format that can be easily analyzed. The log is the format of 'TYPE: [TIMESTAMP (YYYY-MM-DD HH:MM:SS)] - M...
import re import pandas as pd from datetime import datetime def task_func(log_file): """ Extracts logging information such as message type, timestamp, and the message itself from a log file and stores the data in a CSV format. This utility is ideal for converting plain text logs into a more s tructure...
import re import pandas as pd from datetime import datetime def task_func(log_file): """ Extracts logging information such as message type, timestamp, and the message itself from a log file and stores the data in a CSV format. This utility is ideal for converting plain text logs into a more s tructured...
import unittest import os import pandas as pd from unittest.mock import mock_open, patch class TestCases(unittest.TestCase): def setUp(self): self.sample_log_file = 'test_server.log' with open(self.sample_log_file, 'w') as log_file: log_file.write("ERROR: [2023-03-23 15:00:00] - Sample e...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/163
Generates a DataFrame with random numerical data and visualizes this data in a stacked bar chart for specified categories. The function should raise the exception for: ValueError: If the number of columns exceeds the number of available categories. The function should output with: matplotlib.axes._axes.Axes: The Ax...
import numpy as np import pandas as pd def task_func(rows=5, cols=5): """ Generates a DataFrame with random numerical data and visualizes this data in a stacked bar chart for specified categories. Parameters: rows (int, optional): Number of rows for the DataFrame. Defaults to 5. cols (int, op...
import numpy as np import pandas as pd def task_func(rows=5, cols=5): """ Generates a DataFrame with random numerical data and visualizes this data in a stacked bar chart for specified categories. Parameters: rows (int, optional): Number of rows for the DataFrame. Defaults to 5. cols (int, opt...
import unittest import matplotlib.pyplot as plt import matplotlib matplotlib.use('Agg') class TestCases(unittest.TestCase): def tearDown(self): # Cleanup any opened figures in matplotlib plt.close('all') def test_case_1(self): ax = task_func(5, 5) self.assertEqual(len(ax.patches)...
[ "mutate_comparison_operators" ]
1
BigCodeBench/164
Generate random numeric data across a specified range for a given number of categories and visualize it with a stacked bar chart. >>> fig = task_func(num_labels=3, data_range=(1, 10)) >>> fig.show() # This will display the figure with three labels and data range from 1 to 10 The function should output with: matplo...
import pandas as pd import matplotlib.pyplot as plt import numpy as np def task_func(num_labels=5, data_range=(0, 1)): """ Generate random numeric data across a specified range for a given number of categories and visualize it with a stacked bar chart. Parameters: num_labels (int): Specifies the...
import pandas as pd import matplotlib.pyplot as plt import numpy as np def task_func(num_labels=5, data_range=(0, 1)): """ Generate random numeric data across a specified range for a given number of categories and visualize it with a stacked bar chart. Parameters: num_labels (int): Specifies the ...
import unittest from unittest.mock import patch, MagicMock import matplotlib.pyplot as plt import numpy as np import pandas as pd class TestCases(unittest.TestCase): def setUp(self): np.random.seed(0) # Fixing the seed for the sake of determinism in tests @patch('matplotlib.pyplot.subplots') @patch...
[ "mutate_range_bounds" ]
1
BigCodeBench/167
Generate a DataFrame containing random integer values across a specified number of categories, and visualize these data as a horizontal stacked bar chart. Note that: The plot displays categories on the y-axis and their corresponding values on the x-axis, with data segmented by category. The function should output with:...
import pandas as pd import matplotlib.pyplot as plt from random import randint def task_func(num_types=5, integer_range=(0, 100)): """ Generate a DataFrame containing random integer values across a specified number of categories, and visualize these data as a horizontal stacked bar chart. Parameters:...
import pandas as pd import matplotlib.pyplot as plt from random import randint def task_func(num_types=5, integer_range=(0, 100)): """ Generate a DataFrame containing random integer values across a specified number of categories, and visualize these data as a horizontal stacked bar chart. Parameters: ...
import unittest import matplotlib matplotlib.use('Agg') class TestCases(unittest.TestCase): def test_case_1(self): fig, ax = task_func() self.assertEqual(len(ax.patches), 25) def test_case_2(self): fig, ax = task_func(3, (0, 50)) self.assertEqual(len(ax.patches), 9) def test_...
[ "mutate_range_bounds" ]
1
BigCodeBench/168
Generate random data and visualize it with a stacked bar chart, saving the chart to a file. This function facilitates the exploration and sharing of data distribution across multiple categories. The function should output with: tuple: A tuple containing: matplotlib.figure.Figure: The Figure object containing th...
import pandas as pd import matplotlib.pyplot as plt import numpy as np def task_func(num_groups=5, data_size=5, labels=None): """ Generate random data and visualize it with a stacked bar chart, saving the chart to a file. This function facilitates the exploration and sharing of data distribution across mu...
import pandas as pd import matplotlib.pyplot as plt import numpy as np def task_func(num_groups=5, data_size=5, labels=None): """ Generate random data and visualize it with a stacked bar chart, saving the chart to a file. This function facilitates the exploration and sharing of data distribution across mul...
import unittest import pandas as pd import matplotlib.pyplot as plt import os import matplotlib matplotlib.use('Agg') class TestCases(unittest.TestCase): def tearDown(self): """Ensure no files are left after tests.""" try: os.remove('test_plot.png') except FileNotFoundError: ...
[ "mutate_range_bounds" ]
1
BigCodeBench/172
Determine if the given datetime is a weekend. Note that: The datetime to be extracted is located in the 'utc_datetime' key in the JSON data. The function should output with: bool: True if the date is a weekend (Saturday or Sunday), False otherwise. You should write self-contained code starting with: ``` import json...
import json from datetime import datetime def task_func(json_data): """ Determine if the given datetime is a weekend. Parameters: - json_data (str): JSON string containing the datetime in UTC format. Returns: bool: True if the date is a weekend (Saturday or Sunday), False otherwise. Note...
import json from datetime import datetime def task_func(json_data): """ Determine if the given datetime is a weekend. Parameters: - json_data (str): JSON string containing the datetime in UTC format. Returns: bool: True if the date is a weekend (Saturday or Sunday), False otherwise. Note...
import unittest from datetime import datetime import json class TestCases(unittest.TestCase): def test_case_1(self): # Create a datetime object for a weekday (Monday) utc_datetime = datetime(2024, 4, 15, 12, 0, 0) # Monday, April 15, 2024 json_data = json.dumps({'utc_datetime': utc_datetime...
[ "mutate_comparison_operators" ]
1
BigCodeBench/176
Given a list of IP addresses, this function returns a dictionary mapping each valid IP address to its respective hostname. If the hostname cannot be determined, the value will be None. The function should output with: dict: A dictionary with IP addresses as keys and their hostnames as values. If the hostname cannot...
import re import socket def task_func(ip_addresses: list) -> dict: """ Given a list of IP addresses, this function returns a dictionary mapping each valid IP address to its respective hostname. If the hostname cannot be determined, the value will be None. Parameters: ip_addresses (list): A li...
import re import socket def task_func(ip_addresses: list) -> dict: """ Given a list of IP addresses, this function returns a dictionary mapping each valid IP address to its respective hostname. If the hostname cannot be determined, the value will be None. Parameters: ip_addresses (list): A li...
import unittest class TestCases(unittest.TestCase): def test_case_1(self): result = task_func(['8.8.8.8', '8.8.4.4']) expected = {'8.8.8.8': 'dns.google', '8.8.4.4': 'dns.google'} self.assertDictEqual(result, expected) def test_case_2(self): result = task_func(['8.8.4.4']) ...
[ "mutate_list_indexing" ]
1
BigCodeBench/179
Analyzes a given DataFrame containing article titles and content to identify articles with titles that include the words "how" or "what". It calculates the TF-IDF scores for the words in the content of these articles and visualizes these scores in a bar plot. Note that: If the DataFrame does not contain 'Title' and 'Co...
import re import matplotlib.pyplot as plt from sklearn.feature_extraction.text import TfidfVectorizer import numpy as np def task_func(df): """ Analyzes a given DataFrame containing article titles and content to identify articles with titles that include the words "how" or "what". It calculates the TF-IDF...
import re import matplotlib.pyplot as plt from sklearn.feature_extraction.text import TfidfVectorizer import numpy as np def task_func(df): """ Analyzes a given DataFrame containing article titles and content to identify articles with titles that include the words "how" or "what". It calculates the TF-IDF ...
import unittest import pandas as pd import matplotlib matplotlib.use('Agg') class TestCases(unittest.TestCase): def setUp(self): # Sample data for testing self.DATA = { 'Title': ['How to code?', 'What is Python?', 'The art of programming', 'How to cook?', 'What is life?'], 'C...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/191
Simulates sales in a pet shop based on a randomly determined number of customers. Each customer randomly buys one type of animal from the specified list of animals. The function displays and returns a summary of the sales, where the number of customers follows a Poisson distribution with the specified mean (mu). The fu...
import random from scipy import stats def task_func(animals, mean): """ Simulates sales in a pet shop based on a randomly determined number of customers. Each customer randomly buys one type of animal from the specified list of animals. The function displays and returns a summary of the sales, where th...
import random from scipy import stats def task_func(animals, mean): """ Simulates sales in a pet shop based on a randomly determined number of customers. Each customer randomly buys one type of animal from the specified list of animals. The function displays and returns a summary of the sales, where th...
import unittest from unittest.mock import patch class TestCases(unittest.TestCase): def setUp(self): self.animals = ['Dog', 'Cat', 'Bird', 'Fish', 'Hamster'] @patch('random.choice') @patch('scipy.stats.poisson') def test_typical_case(self, mock_poisson, mock_choice): """Test typical case...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/192
Extract all names from a string that is not enclosed by square brackets and send the names in an email. Note that: The message in the email is formatted in "Subject: Extracted Names\n\n" with the extracted name "\nJosie Smith\nMugsy Dog Smith". The function should output with: list: A list of extracted names. You s...
import re import smtplib # Constants TEXT = "Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]" RECEPIENT_ADDRESS = "names@gmail.com" SMTP_SERVER = "smtp.gmail.com" SMTP_PORT = 587 EMAIL_ADDRESS = "your.email@gmail.com" EMAIL_PASSWORD = "your.password" def task_fu...
import re import smtplib TEXT = 'Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]' RECEPIENT_ADDRESS = 'names@gmail.com' SMTP_SERVER = 'smtp.gmail.com' SMTP_PORT = 587 EMAIL_ADDRESS = 'your.email@gmail.com' EMAIL_PASSWORD = 'your.password' def task_func(text=TEXT,...
import unittest from unittest.mock import patch, MagicMock import smtplib class TestCases(unittest.TestCase): @patch('smtplib.SMTP') def test_f225(self, mock_smtp): mock_smtp_instance = MagicMock() mock_smtp.return_value = mock_smtp_instance # Call the function result = ...
[ "mutate_comparison_operators" ]
1
BigCodeBench/195
Open a web page in the default web browser in a background process. The function should output with: int: The return code of the subprocess. You should write self-contained code starting with: ``` import subprocess import platform import time def task_func(url): ```
import subprocess import platform import time def task_func(url): """ Open a web page in the default web browser in a background process. Parameters: url (str): The URL of the webpage to be opened. Returns: int: The return code of the subprocess. Requirements: - subprocess - plat...
import subprocess import platform import time def task_func(url): """ Open a web page in the default web browser in a background process. Parameters: url (str): The URL of the webpage to be opened. Returns: int: The return code of the subprocess. Requirements: - subprocess - plat...
import unittest from unittest.mock import patch, MagicMock class TestCases(unittest.TestCase): @patch('subprocess.Popen') @patch('platform.system') def test_case_1(self, mock_system, mock_popen): mock_system.return_value = 'Darwin' process_mock = MagicMock() process_mock.poll.side_ef...
[ "mutate_comparison_operators" ]
1
BigCodeBench/198
Analyzes a list of numerical data, identifies values greater than the average, and counts how many values are greater than a specified value. Additionally, plots the histogram of the sorted numbers. Note that: If the data list is empty, the function returns an empty numpy.ndarray and a count of 0. This ensures the func...
import numpy as np import bisect import statistics import matplotlib.pyplot as plt def task_func(data, value): """ Analyzes a list of numerical data, identifies values greater than the average, and counts how many values are greater than a specified value. Additionally, plots the histogram of the sort...
import numpy as np import bisect import statistics import matplotlib.pyplot as plt def task_func(data, value): """ Analyzes a list of numerical data, identifies values greater than the average, and counts how many values are greater than a specified value. Additionally, plots the histogram of the sorte...
import unittest from unittest.mock import patch import numpy as np import statistics class TestCases(unittest.TestCase): def test_return_types(self): """Ensure the function returns a numpy.ndarray and an integer.""" data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = task_func(data, 5) s...
[ "mutate_sort_order" ]
1
BigCodeBench/199
Generate a weather report for specified cities at a given UTC datetime. The function should raise the exception for: ValueError: If utc_datetime is not a datetime object or if any of the other parameters are not in the expected format. The function should output with: pandas.DataFrame: A DataFrame containing the we...
import pandas as pd import pytz from datetime import datetime from random import randint, seed as set_seed def task_func( utc_datetime, cities=['New York', 'London', 'Beijing', 'Tokyo', 'Sydney'], weather_conditions=['Sunny', 'Cloudy', 'Rainy', 'Snowy', 'Stormy'], timezones={ 'New York': 'Ameri...
import pandas as pd import pytz from datetime import datetime from random import randint, seed as set_seed def task_func(utc_datetime, cities=['New York', 'London', 'Beijing', 'Tokyo', 'Sydney'], weather_conditions=['Sunny', 'Cloudy', 'Rainy', 'Snowy', 'Stormy'], timezones={'New York': 'America/New_York', 'London': 'E...
import unittest from datetime import datetime import pytz import pandas as pd class TestCases(unittest.TestCase): def setUp(self): self.seed = 42 self.utc_time = datetime(2023, 6, 15, 12, tzinfo=pytz.UTC) def test_valid_input(self): """Test with default parameters and check DataFrame str...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/200
Generates 'n' random numbers between 0 and 1, finds those greater than their average, and counts how many are greater than or equal to a specified value, then plots the sorted numbers. The function should output with: list: Numbers greater than the average of all generated numbers. int: The count of numbers gre...
import random import bisect import statistics import matplotlib.pyplot as plt def task_func(n, value): """ Generates 'n' random numbers between 0 and 1, finds those greater than their average, and counts how many are greater than or equal to a specified value, then plots the sorted numbers. Para...
import random import bisect import statistics import matplotlib.pyplot as plt def task_func(n, value): """ Generates 'n' random numbers between 0 and 1, finds those greater than their average, and counts how many are greater than or equal to a specified value, then plots the sorted numbers. Param...
import unittest from unittest.mock import MagicMock, patch class TestCases(unittest.TestCase): def setUp(self): # Mock random.random to return a fixed sequence of numbers self.random_sequence = [0.6, 0.4, 0.8, 0.2, 0.5] self.random_mock = MagicMock(side_effect=self.random_sequence) @patc...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/201
Analyze a column of a pandas DataFrame, find the values that are larger than the average, and count the number of values that are larger than a given value. The function should raise the exception for: ValueError: If the column does not exist in the DataFrame or value is not a number. The function should output with: ...
import bisect import statistics def task_func(df, column, value): """ Analyze a column of a pandas DataFrame, find the values that are larger than the average, and count the number of values that are larger than a given value. Parameters: df (DataFrame): The pandas DataFrame. column (str): The col...
import bisect import statistics def task_func(df, column, value): """ Analyze a column of a pandas DataFrame, find the values that are larger than the average, and count the number of values that are larger than a given value. Parameters: df (DataFrame): The pandas DataFrame. column (str): The col...
import unittest import pandas as pd class TestCases(unittest.TestCase): def setUp(self): self.df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}) def test_valid_input(self): greater_avg, num_greater, ax = task_func(self.df, 'A', 5) self.assertTrue(len(greater_avg) > 0) self...
[ "mutate_comparison_operators" ]
1
BigCodeBench/203
Extract recepient email address and names from JSON-formatted string and send the names in an email. The sent message should be in the format 'Subject: Extracted Names\n\nName1\nName2\n...'. The function should output with: list: A list of extracted names. You should write self-contained code starting with: ``` imp...
import json import smtplib # Constants SMTP_SERVER = "smtp.gmail.com" SMTP_PORT = 587 EMAIL_ADDRESS = "your.email@gmail.com" EMAIL_PASSWORD = "your.password" def task_func(input_data=None, smtp_server=SMTP_SERVER, smtp_port=SMTP_PORT, email_address=EMAIL_ADDRESS, email_password=EMAIL_PASSWORD, smtp=None): """ ...
import json import smtplib SMTP_SERVER = 'smtp.gmail.com' SMTP_PORT = 587 EMAIL_ADDRESS = 'your.email@gmail.com' EMAIL_PASSWORD = 'your.password' def task_func(input_data=None, smtp_server=SMTP_SERVER, smtp_port=SMTP_PORT, email_address=EMAIL_ADDRESS, email_password=EMAIL_PASSWORD, smtp=None): """ Extract rece...
import unittest from unittest.mock import patch, MagicMock import smtplib class TestCases(unittest.TestCase): @patch('smtplib.SMTP') def test_f225(self, mock_smtp): mock_smtp_instance = MagicMock() mock_smtp.return_value = mock_smtp_instance # Call the function result = ...
[ "mutate_arithmetic_operators" ]
1
BigCodeBench/204
Analyze an "L" list by calculating the mean, median, mode, and standard deviation. Visualize the data by returning a histogram plot. The function should output with: dict: A dictionary with the 'mean', 'median', 'mode', 'std_dev' of 'L, and the 'plot' Axes object. You should write self-contained code starting with:...
import numpy as np from collections import Counter import matplotlib.pyplot as plt def task_func(L): """ Analyze an "L" list by calculating the mean, median, mode, and standard deviation. Visualize the data by returning a histogram plot. Parameters: L (list): Input list. Returns: ...
import numpy as np from collections import Counter import matplotlib.pyplot as plt def task_func(L): """ Analyze an "L" list by calculating the mean, median, mode, and standard deviation. Visualize the data by returning a histogram plot. Parameters: L (list): Input list. Returns: ...
import unittest import doctest class TestCases(unittest.TestCase): def test_case_1(self): L = [1, 2, 3, 4, 5, 6, 7, 8, 9] stats = task_func(L) self.assertAlmostEqual(stats['mean'], np.mean(L)) self.assertAlmostEqual(stats['median'], np.median(L)) self.assertEqual(stats['mode'...
[ "mutate_list_indexing" ]
1
BigCodeBench/513
Analyze a list of fitness data, calculate the sum, the mean, the minimum, the maximum of a certain column and draw a line chart. Additionally, validate that the numeric values for steps, calories burned, and distance walked are non-negative. The function should raise the exception for: KeyError: If the specified column...
import pandas as pd import numpy as np import matplotlib.pyplot as plt def task_func(column, data): """ Analyze a list of fitness data, calculate the sum, the mean, the minimum, the maximum of a certain column and draw a line chart. Additionally, validate that the numeric values for steps, calories bu...
import pandas as pd import numpy as np import matplotlib.pyplot as plt def task_func(column, data): """ Analyze a list of fitness data, calculate the sum, the mean, the minimum, the maximum of a certain column and draw a line chart. Additionally, validate that the numeric values for steps, calories bur...
import unittest from datetime import datetime import matplotlib.pyplot as plt class TestCases(unittest.TestCase): def test_case_1(self): data = [ [datetime(2022, 1, 1), 5000, 200, 3.5], [datetime(2022, 1, 2), 5500, 220, 4.0], [datetime(2022, 1, 3), 6000, 240, 4.5], ...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/515
Generates a DataFrame and heatmap from a 2D list. This function takes a 2D list and returns a pandas DataFrame and a seaborn heatmap representing the correlation matrix of the DataFrame. Assumes sublists of length 5. Also assumes DataFrame columns: 'A', 'B', 'C', 'D', 'E'. The function should raise the exception for: V...
import pandas as pd import seaborn as sns def task_func(array): """Generates a DataFrame and heatmap from a 2D list. This function takes a 2D list and returns a pandas DataFrame and a seaborn heatmap representing the correlation matrix of the DataFrame. Assumes sublists of length 5. Also assumes Data...
import pandas as pd import seaborn as sns def task_func(array): """Generates a DataFrame and heatmap from a 2D list. This function takes a 2D list and returns a pandas DataFrame and a seaborn heatmap representing the correlation matrix of the DataFrame. Assumes sublists of length 5. Also assumes DataF...
import unittest import pandas as pd import numpy as np import matplotlib.pyplot as plt import random class TestCases(unittest.TestCase): def setUp(self): random.seed(42) self.mock_data = [[random.randint(1, 100) for _ in range(5)] for _ in range(5)] def test_case_1(self): # Test datafram...
[ "mutate_comparison_operators" ]
1
BigCodeBench/516
Generate a Pandas DataFrame from a 2D list and perform a multiple linear regression. The function first validates the input list, creates a DataFrame, separates independent and dependent variables, adds a constant to the model, and fits a linear regression using statsmodels. - random_seed (int): A seed for reproducibil...
import pandas as pd import numpy as np import statsmodels.api as sm def task_func( array: list, random_seed: int = 0 ) -> (pd.DataFrame, sm.regression.linear_model.RegressionResultsWrapper): """ Generate a Pandas DataFrame from a 2D list and perform a multiple linear regression. The function first va...
import pandas as pd import numpy as np import statsmodels.api as sm def task_func(array: list, random_seed: int=0) -> (pd.DataFrame, sm.regression.linear_model.RegressionResultsWrapper): """ Generate a Pandas DataFrame from a 2D list and perform a multiple linear regression. The function first validates t...
import unittest import pandas as pd class TestCases(unittest.TestCase): def test_case_1(self): # Testing dataframe creation, model accuracy, and parameters with various numeric data types test_data = [ ([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], 42, 1.0), # Positive values ([[-1, ...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/518
Generate a Pandas DataFrame from a 2D list and calculate a distance matrix. This function converts a 2D list into a DataFrame, with columns named alphabetically starting from 'A'. It uses the `chr()` function, which converts an integer to its corresponding Unicode character, to dynamically assign alphabetical labels to...
import pandas as pd from scipy.spatial.distance import pdist, squareform def task_func(array): """ Generate a Pandas DataFrame from a 2D list and calculate a distance matrix. This function converts a 2D list into a DataFrame, with columns named alphabetically starting from 'A'. It uses the `chr()` fu...
import pandas as pd from scipy.spatial.distance import pdist, squareform def task_func(array): """ Generate a Pandas DataFrame from a 2D list and calculate a distance matrix. This function converts a 2D list into a DataFrame, with columns named alphabetically starting from 'A'. It uses the `chr()` fun...
import unittest class TestCases(unittest.TestCase): def test_case_1(self): # Teset basic case input_data = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] df, distance_matrix = task_func(input_data) self.assertEqual(df.shape, (2, 5)) self.assertTrue((df.columns == ["A", "B", "C", "D", "E...
[ "mutate_range_bounds" ]
1
BigCodeBench/520
Combine a list of dictionaries with the same keys (fruit names) into a single dictionary, calculate the total turnover for each fruit, and return a bar chart's axes with colors representing different fruits. The colors are selected from: 'red', 'yellow', 'green', 'blue', 'purple'. The function ensures that sales quanti...
import collections import matplotlib.pyplot as plt def task_func(data): """ Combine a list of dictionaries with the same keys (fruit names) into a single dictionary, calculate the total turnover for each fruit, and return a bar chart's axes with colors representing different fruits. The colors are sel...
import collections import matplotlib.pyplot as plt def task_func(data): """ Combine a list of dictionaries with the same keys (fruit names) into a single dictionary, calculate the total turnover for each fruit, and return a bar chart's axes with colors representing different fruits. The colors are sele...
import unittest import collections import matplotlib.pyplot as plt class TestCases(unittest.TestCase): def test_case_1(self): # Test basic case with one fruit data = [{"apple": 5}, {"apple": 7}, {"apple": 3}] sales, _ = task_func(data) expected_sales = {"apple": 15} self.asse...
[ "mutate_comparison_operators" ]
1
BigCodeBench/523
Combine a list of dictionaries with the same keys into a single dictionary, turn it into a Pandas DataFrame and create a line plot of the data. The function should output with: matplotlib.axes._axes.Axes or None: Axes object of the plot showing 'Data over Time', with 'Time' on the x-axis and 'Data Points' on th...
import pandas as pd import matplotlib.pyplot as plt def task_func(data): """ Combine a list of dictionaries with the same keys into a single dictionary, turn it into a Pandas DataFrame and create a line plot of the data. Parameters: data (list): A list of dictionaries. The keys are labels and the ...
import pandas as pd import matplotlib.pyplot as plt def task_func(data): """ Combine a list of dictionaries with the same keys into a single dictionary, turn it into a Pandas DataFrame and create a line plot of the data. Parameters: data (list): A list of dictionaries. The keys are labels and the ...
import unittest import matplotlib import matplotlib.pyplot as plt import pandas as pd import numpy as np class TestCases(unittest.TestCase): def setUp(self): self.data1 = [ {"A": 10, "B": 15, "C": 12}, {"A": 12, "B": 20, "C": 14}, {"A": 15, "B": 18, "C": 15}, ...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/524
Calculate statistical measurements (mean and standard deviation) of the values associated with each key in a list of dictionaries, and visualize mean and standard deviation with bar charts. The function should raise the exception for: ValueError: If the input data is empty. TypeError: If the input is not a list of dict...
from collections import defaultdict import numpy as np import matplotlib.pyplot as plt def task_func(data): """ Calculate statistical measurements (mean and standard deviation) of the values associated with each key in a list of dictionaries, and visualize mean and standard deviation with bar charts. ...
from collections import defaultdict import numpy as np import matplotlib.pyplot as plt def task_func(data): """ Calculate statistical measurements (mean and standard deviation) of the values associated with each key in a list of dictionaries, and visualize mean and standard deviation with bar charts. ...
import unittest class TestCases(unittest.TestCase): def test_case_1(self): # Test basic case data = [{"cat": 1, "dog": 3}, {"cat": 2, "dog": 5}, {"cat": 3, "dog": 7}] stats, axes = task_func(data) self.assertAlmostEqual(stats["cat"]["mean"], 2.0) self.assertAlmostEqual(stats[...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/528
Identifies duplicate rows from a CSV file using the csv library, convert duplicated rows into a pandas DataFrame, then plot using matplotlib. Note that: Ensure the CSV file is in proper format and has a .csv extension. Other file formats will raise a ValueError. The function should output with: dict: A dictionary w...
import csv from collections import Counter import pandas as pd import matplotlib.pyplot as plt def task_func(file_path): """ Identifies duplicate rows from a CSV file using the csv library, convert duplicated rows into a pandas DataFrame, then plot using matplotlib. Parameters: - file_path (str):...
import csv from collections import Counter import pandas as pd import matplotlib.pyplot as plt def task_func(file_path): """ Identifies duplicate rows from a CSV file using the csv library, convert duplicated rows into a pandas DataFrame, then plot using matplotlib. Parameters: - file_path (str): ...
import unittest import tempfile import os import matplotlib from collections import Counter class TestCases(unittest.TestCase): def setUp(self): self.temp_dir = tempfile.TemporaryDirectory() self.addCleanup(self.temp_dir.cleanup) def tearDown(self): plt.close("all") def create_temp_c...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/529
Simulate rolling a certain number of a standard six-sided dice several times, then identify and display the distribution of the sums of the dice rolls in a bar plot. The function should output with: tuple: A tuple containing the following elements: Counter: A Counter object with the count of each possible sum. ...
from collections import Counter import random import matplotlib.pyplot as plt def task_func(num_rolls, num_dice, plot_path=None, random_seed=0): """Simulate rolling a certain number of a standard six-sided dice several times, then identify and display the distribution of the sums of the dice rolls in a bar pl...
from collections import Counter import random import matplotlib.pyplot as plt def task_func(num_rolls, num_dice, plot_path=None, random_seed=0): """Simulate rolling a certain number of a standard six-sided dice several times, then identify and display the distribution of the sums of the dice rolls in a bar plo...
import unittest import os from collections import Counter import tempfile import shutil import matplotlib.pyplot as plt class TestCases(unittest.TestCase): def setUp(self): # Create a temporary directory to store plots self.test_dir = tempfile.mkdtemp() def tearDown(self): # Close matplo...
[ "mutate_range_bounds" ]
1
BigCodeBench/532
Identify and count duplicate values in a DataFrame's 'value' column. This function also plots a histogram for all values in the 'value' column and overlays a normal distribution curve on the histogram. The function should output with: tuple: A tuple containing: Counter: A Counter object with the count of each d...
import numpy as np from collections import Counter from scipy.stats import norm import matplotlib.pyplot as plt def task_func(df, bins=4): """ Identify and count duplicate values in a DataFrame's 'value' column. This function also plots a histogram for all values in the 'value' column and overlays a n...
import numpy as np from collections import Counter from scipy.stats import norm import matplotlib.pyplot as plt def task_func(df, bins=4): """ Identify and count duplicate values in a DataFrame's 'value' column. This function also plots a histogram for all values in the 'value' column and overlays a no...
import unittest import pandas as pd from collections import Counter import matplotlib class TestCases(unittest.TestCase): def _check_plot(self, ax): self.assertIsInstance(ax, plt.Axes) self.assertEqual(ax.get_title(), "Distribution") self.assertEqual(ax.get_xlabel(), "Value") self.as...
[ "mutate_comparison_operators" ]
1
BigCodeBench/535
Insert random data into an SQLite3 table that contains random names, ages, and heights. If the table does not exist, it will be created. This function uses the following constants: - NAMES: List of possible names ['John', 'Jane', 'Steve', 'Emma', 'Liam', 'Olivia']. - AGES: Range of possible ages from 18 to 64. - HEIGHT...
import sqlite3 import numpy as np from random import choice, seed def task_func(db_path, table_name, num_entries, random_seed=None): """ Insert random data into an SQLite3 table that contains random names, ages, and heights. If the table does not exist, it will be created. This function uses the follo...
import sqlite3 import numpy as np from random import choice, seed def task_func(db_path, table_name, num_entries, random_seed=None): """ Insert random data into an SQLite3 table that contains random names, ages, and heights. If the table does not exist, it will be created. This function uses the follow...
import unittest import os import sqlite3 import tempfile class TestCases(unittest.TestCase): NAMES = ["John", "Jane", "Steve", "Emma", "Liam", "Olivia"] AGES = range(18, 65) HEIGHTS = range(150, 200) def setUp(self): # Setup a temporary directory before each test self.temp_dir = tempfile...
[ "mutate_edge_case_guards" ]
1
BigCodeBench/538
Plot the relationship between the first and second numerical columns of an SQLite3 table, after excluding 'id' column. The function should raise the exception for: ValueError: If the table has less than two numerical columns. The function should output with: matplotlib.axes._axes.Axes: Scatterplot with column name ...
import sqlite3 import pandas as pd def task_func(db_name, table_name): """ Plot the relationship between the first and second numerical columns of an SQLite3 table, after excluding 'id' column. Parameters: - db_name (str): The absolute path to the SQLite3 database. - table_name (str): The name of...
import sqlite3 import pandas as pd def task_func(db_name, table_name): """ Plot the relationship between the first and second numerical columns of an SQLite3 table, after excluding 'id' column. Parameters: - db_name (str): The absolute path to the SQLite3 database. - table_name (str): The name of ...
import unittest import sqlite3 import os import matplotlib.pyplot as plt import tempfile class TestCases(unittest.TestCase): def setUp(self): self.temp_dir = tempfile.TemporaryDirectory() self.test_db_path = os.path.join(self.temp_dir.name, "test.db") self.another_test_db_path = os.path.join...
[ "mutate_list_indexing" ]
1
BigCodeBench/541
Adds all modules of a specified package to the system path. This function is useful for dynamically importing modules from a package that might not be on the standard path. >>> len(task_func('pandas')) >= 2 True Verify that 'numpy' (a common package) modules are added to the path, >>> 'random' in task_func('numpy') Tru...
import os import sys import importlib from pkgutil import iter_modules def task_func(package_name): """ Adds all modules of a specified package to the system path. This function is useful for dynamically importing modules from a package that might not be on the standard path. Parameters: package_...
import os import sys import importlib from pkgutil import iter_modules def task_func(package_name): """ Adds all modules of a specified package to the system path. This function is useful for dynamically importing modules from a package that might not be on the standard path. Parameters: package_n...
import unittest from unittest.mock import patch, MagicMock import sys class TestCases(unittest.TestCase): @patch('importlib.import_module') @patch('pkgutil.iter_modules') def test_package_module_addition(self, mock_iter_modules, mock_import_module): # Create a mock for the package with a __path__ at...
[ "mutate_list_indexing" ]
1
BigCodeBench/542
Given a list of hexadecimal string keys, this function selects one at random, converts it into a floating-point number, and then computes its MD5 hash. An optional seed parameter allows for deterministic random choices for testing purposes. The function should raise the exception for: ValueError: If contains invalid he...
import hashlib import random import struct KEYS = ['470FC614', '4A0FC614', '4B9FC614', '4C8FC614', '4D7FC614'] def task_func(hex_keys=KEYS, seed=42): """ Given a list of hexadecimal string keys, this function selects one at random, converts it into a floating-point number, and then computes its MD5 hash....
import hashlib import random import struct KEYS = ['470FC614', '4A0FC614', '4B9FC614', '4C8FC614', '4D7FC614'] def task_func(hex_keys=KEYS, seed=42): """ Given a list of hexadecimal string keys, this function selects one at random, converts it into a floating-point number, and then computes its MD5 hash. A...
import unittest class TestCases(unittest.TestCase): def test_normal_functionality(self): """Test the function with default parameters.""" result = task_func() self.assertIsInstance(result, str) def test_custom_keys_list(self): """Test the function with a custom list of hexadecima...
[ "mutate_list_indexing" ]
1
BigCodeBench/545
Generate a random float number from a list of hex strings and then encode the float number in utf-8. The function should output with: bytes: The utf-8 encoded float number. You should write self-contained code starting with: ``` import codecs import random import struct KEYS = ['470FC614', '4A0FC614', '4B9FC614', '...
import codecs import random import struct KEYS = ['470FC614', '4A0FC614', '4B9FC614', '4C8FC614', '4D7FC614'] def task_func(hex_keys=KEYS): """ Generate a random float number from a list of hex strings and then encode the float number in utf-8. Parameters: hex_keys (list of str): A list of hexadecima...
import codecs import random import struct KEYS = ['470FC614', '4A0FC614', '4B9FC614', '4C8FC614', '4D7FC614'] def task_func(hex_keys=KEYS): """ Generate a random float number from a list of hex strings and then encode the float number in utf-8. Parameters: hex_keys (list of str): A list of hexadecimal...
import unittest class TestCases(unittest.TestCase): def test_default_functionality(self): """Test the function with default parameters.""" result = task_func() self.assertIsInstance(result, bytes) # Check if output is correctly encoded in UTF-8 def test_custom_hex_keys(self): ""...
[ "mutate_list_indexing" ]
1
BigCodeBench/547
Encrypt a password using Salt and SHA-256, then encode the result in base64. The function should output with: str: The encrypted password in base64 format. You should write self-contained code starting with: ``` import hashlib import os import base64 def task_func(password: str, salt_length: int = 8) -> str: ```
import hashlib import os import base64 def task_func(password: str, salt_length: int = 8) -> str: """ Encrypt a password using Salt and SHA-256, then encode the result in base64. Parameters: password (str): The password to be encrypted. salt_length (int, optional): The length of the generated sal...
import hashlib import os import base64 def task_func(password: str, salt_length: int=8) -> str: """ Encrypt a password using Salt and SHA-256, then encode the result in base64. Parameters: password (str): The password to be encrypted. salt_length (int, optional): The length of the generated salt. ...
import unittest import binascii class TestCases(unittest.TestCase): def test_valid_encryption_format(self): encrypted = task_func("test_password") try: base64.b64decode(encrypted) valid = True except binascii.Error: valid = False self.assertTr...
[ "mutate_arithmetic_operators" ]
1