Dataset Viewer
Auto-converted to Parquet Duplicate
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
End of preview. Expand in Data Studio

Over-Editing Benchmark (BigCodeBench, 400 tasks)

This is the evaluation set from our EMNLP 2026 paper When Models Edit Too Much: On the Fidelity of Minimal Code Edits. The code for generation, evaluation and training is at nreHieW/over-editing.

We study over-editing, a functionally correct repair that changes more code than the minimal fix requires. To know the minimal repair by construction, we start from 400 BigCodeBench problems and inject localized AST-level corruptions into each reference solution. We keep an example only if the corrupted program fails the original tests, so the minimal repair is exactly the reversal of the injected corruption.

  • 400 tasks: 232 carry one injected corruption and 168 carry two (568 applications in total).
  • 12 corruption families: edge-case guards (129), arithmetic operators (104), comparison operators (75), numeric constants (64), range bounds (60), list indexing (43), boolean constants (40), function call names (36), sort order (10), slice bounds (3), accumulator initialization (2) and removed copy calls (2).

Loading

from datasets import load_dataset

ds = load_dataset("tyzhu/over-editing-bench", split="test")

Fields

Field Type Description
task_id string BigCodeBench task id (e.g., BigCodeBench/0)
prompt string Natural-language task description from BigCodeBench
canonical_solution string Original BigCodeBench reference solution
corrupted_solution string Reference solution after the injected corruption(s); fails test_code
test_code string Original BigCodeBench unit tests
mutation_types list[string] Corruption families applied to this task
num_corruptions int Number of injected corruptions (1 or 2)

Evaluation

A model receives the corrupted function and is asked to repair it. Each repair is scored on Pass@1 (the original tests, executed in a sandbox), excess Levenshtein distance (normalized edit distance beyond the minimal patch) and added cognitive complexity (control-flow overhead the fix does not need). The full pipeline is in the GitHub repository.

data/test.jsonl is a normalized copy with a single mutation_types list field. The original file used in the paper is kept byte-for-byte at raw/corrupted_solutions_manual_easy_400.jsonl (in which the labels appear under mutation_type in 172 records and mutation_types in 228). Use the raw file with the GitHub pipeline:

from huggingface_hub import hf_hub_download

path = hf_hub_download("tyzhu/over-editing-bench", "raw/corrupted_solutions_manual_easy_400.jsonl", repo_type="dataset")

Models

The Qwen3-4B-Instruct-2507 checkpoints from Table 3 of the paper are also on the Hub:

Method Setting Checkpoint
SFT In-domain nreHieW/qwen3-4b-instruct-2507-3epochs-non-ood
SFT Out-of-domain nreHieW/qwen3-4b-instruct-2507-3epochs-ood
Minimal-edit RL Out-of-domain nreHieW/partial-edits-rl-50-steps

License

Released under Apache-2.0, following BigCodeBench (Apache-2.0), from which the problems, reference solutions and tests are derived.

Citation

@misc{zhu2026modelseditmuchfidelity,
      title={When Models Edit Too Much: On the Fidelity of Minimal Code Edits},
      author={Tongyao Zhu and Wei Hern Lim and Min-Yen Kan},
      year={2026},
      eprint={2609.04061},
      archivePrefix={arXiv},
      primaryClass={cs.SE},
      url={https://arxiv.org/abs/2609.04061},
}
Downloads last month
55

Paper for tyzhu/over-editing-bench