{"id":"base_java_01","dataset_type":"base","language":"Java","task_category":"scaffolding", "prompt_en":"write a static method createScaffold(String rootDir) in java that creates a basic project structure for maven. Return ONLY the method", "prompt_nl":"Schrijf een statische methode createScaffold(String rootDir) in Java die een basisprojectstructuur voor Maven creëert. Retourneer ALLEEN de methode.", "code_snippet_input":"", "canonical_solution":"public static void createScaffold(String rootDir) throws IOException {\n Path root = Paths.get(rootDir);\n Files.createDirectories(root.resolve(\"src/main/java\"));\n Files.createDirectories(root.resolve(\"src/test/java\"));\n}", "unit_test_setup": "import org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.io.TempDir;\nimport java.io.IOException;\nimport java.nio.file.*;\nimport static org.junit.jupiter.api.Assertions.*;\n\npublic class ScaffoldTest {\n", "unit_test_assertion":" @Test\n public void testDirectoryCreation(@TempDir Path tempDir) throws IOException {\n createScaffold(tempDir.toString());\n\n assertTrue(Files.exists(tempDir.resolve(\"src/main/java\")), \"src/main/java should exist\");\n assertTrue(Files.exists(tempDir.resolve(\"src/test/java\")), \"src/test/java should exist\");\n assertTrue(Files.isDirectory(tempDir.resolve(\"src/main/java\")), \"Should be a directory\");\n }\n}", "comment":"the folder structure should contain AT LEAST src/main/java/ and src/test/java/ directories since they're required for every maven project" } {"id":"base_java_02","dataset_type":"base","language":"Java","task_category":"elem_func", "prompt_en":"make a staff class with constructor, setters and getters with at least name, birthdate, gender, position, salary, hire date, and department. Don't include imports", "prompt_nl":"maak een staff class met constructor, setters en getters met ten minste name, birthdate, gender, position, salary, hire date en department. Voeg geen imports toe.", "code_snippet_input":"", "canonical_solution":"public class Staff {\n private String name;\n private java.time.LocalDate birthDate;\n private String gender;\n private String position;\n private double salary;\n private java.time.LocalDate hireDate;\n private String department;\n\n public Staff(String name, java.time.LocalDate birthDate, String gender, String position, double salary, java.time.LocalDate hireDate, String department) {\n this.name = name;\n this.birthDate = birthDate;\n this.gender = gender;\n this.position = position;\n this.salary = salary;\n this.hireDate = hireDate;\n this.department = department;\n }\n // ... Getters and Setters omitted for brevity in this view, but include them in real JSON ...\n}", "unit_test_setup":"import org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport java.time.LocalDate;\nimport java.time.Period;\nimport static org.junit.jupiter.api.Assertions.*;", "unit_test_assertion":"\nclass StaffTest {\n private Staff staff;\n private final LocalDate birthDate = LocalDate.of(1990, 5, 20);\n private final LocalDate hireDate = LocalDate.of(2015, 1, 10);\n\n @BeforeEach\n void setUp() {\n staff = new Staff(\"Alice Johnson\", birthDate, \"Female\", \"Data Scientist\", 75000.00, hireDate, \"R&D\");\n }\n\n @Test\n void testConstructorAndGetters() {\n assertEquals(\"Alice Johnson\", staff.getName());\n }\n // ... other tests ...\n}", "comment":"include a constructor, getters and setters for AT LEAST all the fields in the Staff class that are specified in the prompt (name, birthdate, gender, position, salary, hire date, and department)." } {"id":"base_java_03","dataset_type":"base","language":"Java","task_category":"fix_bug", "prompt_en":"why am I getting a compilation error in this code? fix it and don't include imports", "prompt_nl":"waarom krijg ik een compilatie error in deze code? Los het op en voeg geen imports toe.", "code_snippet_input":"/*Local variable counter defined in an enclosing scope must be final or effectively final*/ \nList results = new ArrayList<>();\nint counter = 0;\nList names = List.of(\"Alice\", \"Bob\", \"Charlie\");\n\nnames.forEach(name -> {\n counter++;\n results.add(counter + \": \" + name);\n});", "canonical_solution":"List results = new ArrayList<>();\nAtomicInteger counter = new AtomicInteger(0);\nList names = List.of(\"Alice\", \"Bob\", \"Charlie\");\n\nnames.forEach(name -> {\n results.add(counter.incrementAndGet() + \": \" + name);\n});", "unit_test_setup":"import org.junit.jupiter.api.Test;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport static org.junit.jupiter.api.Assertions.*;\n\nclass LambdaTest {\n private List generateResults() {", "unit_test_assertion":"return results;\n }\n\n @Test\n public void testCounterIncrements() {\n List results = generateResults();\n\n assertEquals(3, results.size(), \"List should contain 3 elements\");\n assertTrue(results.get(0).startsWith(\"1:\"), \"First element must start with 1:\");\n assertTrue(results.get(1).startsWith(\"2:\"), \"Second element must start with 2:\");\n assertTrue(results.get(2).startsWith(\"3:\"), \"Third element must start with 3:\");\n }\n}", "comment":"counter variable is not final, and cant be changed within the lambda. MUST use an AtomicInteger instead to hold the counter, which allows us to modify its value within the lambda." } {"id":"base_java_04","dataset_type":"base","language":"Java","task_category":"fix_bug", "prompt_en":"why am I getting a compilation error in this code? fix it and don't include imports", "prompt_nl":"waarom krijg ik een compilatie error in deze code? Los het op en voeg geen imports toe.", "code_snippet_input":"/*name clash: method(List) has the same erasure as method(List)*/\npublic String sort(List data) {\nreturn \"Sorting strings\";\n}\npublic String sort(List data) { \nreturn \"Sorting integers\";", "canonical_solution":"public String sortStrings(List data) {\nreturn \"Sorting strings\";\n}\npublic String sortIntegers(List data) { \nreturn \"Sorting integers\";\n}\n}", "unit_test_setup":"import org.junit.jupiter.api.Test;\nimport java.util.List;\nimport java.util.ArrayList;\nimport static org.junit.jupiter.api.Assertions.*;\n\npublic class Solution {\n", "unit_test_assertion":"@Test\n public void testMethodsAreDistinct() {\n String result1 = sortStrings(new ArrayList());\n String result2 = sortIntegers(new ArrayList());\n \n assertEquals(\"Sorting strings\", result1);\n assertEquals(\"Sorting integers\", result2);\n }\n}", "comment":"java compiles List and List to the same type List, so can't overload the method. SOlution MUST rename the methods to have distinct names." } {"id":"base_java_05","dataset_type":"base","language":"Java","task_category":"fix_bug", "prompt_en":"why am I getting a compilation error in this code? I want to use the process from printer. Output only the fixed class.", "prompt_nl":"Waarom krijg ik een compilatiefout in deze code? Ik wil het proces van printer gebruiken. Geef alleen de vaste klasse weer.", "code_snippet_input":"/*class OfficeMachine inherits unrelated defaults for process() from types Printer and Scanner*/\npublic class OfficeMachine implements Printer, Scanner {\n \n}", "canonical_solution":"public class OfficeMachine implements Printer, Scanner {\n @Override\n public String process() {\n return Printer.super.process();\n }\n}", "unit_test_setup":"import org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.*;\ninterface Printer {\n default String process() { return \"Printing document...\"; }\n}\n\ninterface Scanner {\n default String process() { return \"Scanning document...\"; }\n}\n", "unit_test_assertion":"\nclass DiamondProblemTest {\n @Test\n public void testConflictResolution() {\n OfficeMachine machine = new OfficeMachine();\nassertEquals(\"Printing document...\", machine.process(), \"Should return Printer's output\");\n }\n}", "comment":"the error happens because officemachine implements two methods with the same name from different interfaces. the soluction MUST override the process() method to explicitly call the Printer's default method." } {"id":"base_java_06","dataset_type":"base","language":"Java","task_category":"id_bug", "prompt_en":"why am i getting wrong results in this code? The method doesn't return a list of the transaction in the target currency. Fix the method and don't include imports", "prompt_nl":"Waarom krijg ik verkeerde resultaten in deze code? De methode retourneert geen lijst met transacties in de doelvaluta. Corrigeer de methode en neem geen imports op.", "code_snippet_input":"public class DataFilter {\npublic List filterByCurrency(List data, String targetCurrency) {\nList result = new ArrayList<>();\nfor (Transaction t : data) {\nif (t.getCurrency() == targetCurrency) {\nresult.add(t);\n}\n}\nreturn result;\n}", "canonical_solution":"public class DataFilter {\npublic List filterByCurrency(List data, String targetCurrency) {\nList result = new ArrayList<>();\nfor (Transaction t : data) {\nif (targetCurrency.equals(t.getCurrency())) {\nresult.add(t);\n}\n}\nreturn result;\n}\n}", "unit_test_setup":"import org.junit.jupiter.api.Test;\nimport java.util.List;\nimport java.util.ArrayList;\nimport static org.junit.jupiter.api.Assertions.*;\n\nclass Transaction {\n private String id;\n private String currency;\n public Transaction(String id, String currency) { this.id = id; this.currency = currency; }\n public String getCurrency() { return currency; }\n}\n", "unit_test_assertion":"\nclass DataFilterTest {\n @Test\n public void testCurrencyFiltering() {\n DataFilter filter = new DataFilter();\n List dataset = new ArrayList<>();\n\n String dynamicUSD = new String(\"USD\");\n String dynamicEUR = new String(\"EUR\");\n \n dataset.add(new Transaction(\"tx1\", dynamicUSD));\n dataset.add(new Transaction(\"tx2\", dynamicEUR));\n dataset.add(new Transaction(\"tx3\", dynamicUSD));\n \n List result = filter.filterByCurrency(dataset, \"USD\");\n \n assertEquals(2, result.size(), \"Should find 2 USD transactions even if memory addresses differ\");\n }\n}", "comment":"== checks for the same reference in memory, not value equality. MUST use .equals() to compare the string values of the currencies." } {"id":"base_java_07","dataset_type":"base","language":"Java","task_category":"id_bug", "prompt_en":"why doesn't this method read the csv data properly? Fix the method and don't include imports", "prompt_nl":"Waarom leest deze methode de csv-gegevens niet correct? Repareer de methode en neem geen imports op.", "code_snippet_input":"/* \nCSV DATA CONTEXT:\npatient_id,full_name,birth_date,is_active,last_bill_amount,department\n101,Laura Smith,2002-05-20,true,150.00,Cardiology\n...\n110,Sam I Am,1960-09-09,false,NA,Psychiatry\n*/\n\npublic static double getBillAmount(String csvLine) {\n String[] columns = csvLine.split(\",\");\n String rawAmount = columns[4];\n return Double.parseDouble(rawAmount);\n}", "canonical_solution":"public static double getBillAmount(String csvLine) {\n String[] columns = csvLine.split(\",\");\n if (columns.length <= 4) return Double.NaN;\n \n String rawAmount = columns[4].trim();\n \n if (rawAmount.equalsIgnoreCase(\"NA\") || rawAmount.isEmpty()) {\n return Double.NaN;\n }\n \n try {\n return Double.parseDouble(rawAmount);\n } catch (NumberFormatException e) {\n return Double.NaN;\n }\n}", "unit_test_setup":"import org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.*;\n\npublic class Solution {\n", "unit_test_assertion":"@Test\n public void testValidAmount() {\n String line = \"101,Laura Smith,2002-05-20,true,150.00,Cardiology\";\n assertEquals(150.00, getBillAmount(line), 0.001);\n }\n\n @Test\n public void testNAValue() {\n String line = \"110,Sam I Am,1960-09-09,false,NA,Psychiatry\";\n assertTrue(Double.isNaN(getBillAmount(line)), \"NA should return NaN, not throw exception\");\n }\n\n @Test\n public void testGarbageValue() {\n String line = \"105,Big Mike,1978-06-30,0,FREE,Emergency\";\n assertTrue(Double.isNaN(getBillAmount(line)), \"Invalid text should return NaN\");\n }\n}", "comment":"the method fails to handle 'NA' values and possible formatting issues. MUST check for 'NA' and handle NumberFormatException to avoid crashes." } {"id":"base_java_08","dataset_type":"base","language":"Java","task_category":"id_bug", "prompt_en":"i want to use this method to transpose a square matrix but it gives the wrong results. Fix the method and don't include imports", "prompt_nl":"Ik wil deze methode gebruiken om een vierkante matrix te transponeren, maar het geeft verkeerde resultaten. Corrigeer de methode en neem geen imports op.", "code_snippet_input":"public static int[][] transposeMatrix(int[][] input) {\nint rows = input.length;\nint cols = input[0].length;\nint[][] output = new int[cols][rows];\nfor (int i = 0; i < rows; i++) {\nfor (int j = 0; j < cols; j++) {\noutput[i][j] = input[i][j]; \n}\n}\nreturn output;\n}", "canonical_solution":"public static int[][] transposeMatrix(int[][] input) {\nint rows = input.length;\nint cols = input[0].length;\nint[][] output = new int[cols][rows];\nfor (int i = 0; i < rows; i++) {\nfor (int j = 0; j < cols; j++) {\noutput[j][i] = input[i][j]; \n}\n}\nreturn output;\n}", "unit_test_setup":"import org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Arrays;\n\npublic class Solution {\n\n", "unit_test_assertion":" @Test\n public void testTranspose2x2() {\n int[][] input = { {1, 2}, {3, 4} };\n int[][] expected = { {1, 3}, {2, 4} };\n assertArrayEquals(expected, transposeMatrix(input), \"Should swap rows and columns correctly\");\n }\n\n @Test\n public void testTranspose3x3() {\n int[][] input = {\n {1, 2, 3},\n {4, 5, 6},\n {7, 8, 9}\n };\n int[][] expected = {\n {1, 4, 7},\n {2, 5, 8},\n {3, 6, 9}\n };\n assertArrayEquals(expected, transposeMatrix(input));\n }\n}", "comment":"the method incorrectly assigns values to the output matrix into wrong positions, MUST assign output[j][i] = input[i][j] to transpose correctly." } {"id":"base_java_09","dataset_type":"base","language":"Java","task_category":"architecture", "prompt_en":"create a singleton DatabaseConnection class in java with a getInstance method. Don't include imports", "prompt_nl":"Maak een singleton DatabaseConnection klasse in java met een getInstance methode. Voeg geen imports toe.", "code_snippet_input":"", "canonical_solution":"public class DatabaseConnection {\nprivate static volatile DatabaseConnection instance;\nprivate DatabaseConnection() {\nSystem.out.println(\"Connecting to Database... Success.\");\n}\n public static DatabaseConnection getInstance() {\nif (instance == null) {\nsynchronized (DatabaseConnection.class) {\nif (instance == null) {\ninstance = new DatabaseConnection();\n}\n}\n}\nreturn instance;\n}\n}", "unit_test_setup":"import static org.junit.Assert.*;\nimport java.lang.reflect.*;", "unit_test_assertion":"DatabaseConnection i1 = DatabaseConnection.getInstance();\nDatabaseConnection i2 = DatabaseConnection.getInstance();\nassertNotNull(i1);\nassertSame(i1, i2);\n\nConstructor constructor = DatabaseConnection.class.getDeclaredConstructor();\nassertTrue(Modifier.isPrivate(constructor.getModifiers()));", "comment":"the singleton pattern requires that only one instance of the class can exist at once. The solution MUST have a private constructor and a method getInstance() that creates a single database connection." } {"id":"base_java_10","dataset_type":"base","language":"Java","task_category":"refactoring", "prompt_en":"transform this function so it uses datetime objects where the deadline is at the start of the day, while still being compatible with the inputs of the software", "prompt_nl":"transformeer deze functie zodat deze datetime objecten gebruikt waarbij de deadline aan het begin van de dag ligt, terwijl deze nog steeds compatibel is met de inputs van de software.", "code_snippet_input":"public static boolean isOverdue(LocalDate deadline) {\n LocalDate today = LocalDate.now();\n return today.isAfter(deadline);\n}", "canonical_solution":"public static boolean isOverdue(LocalDate deadlineDate) {\n LocalDateTime currentDateTime = LocalDateTime.now();\n LocalDateTime deadlineTimestamp = deadlineDate.atStartOfDay();\n return currentDateTime.isAfter(deadlineTimestamp);\n}", "unit_test_setup":"import java.time.LocalDate;\nimport java.time.LocalDateTime;\nimport org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.*;\n\npublic class DateTest {\n\n", "unit_test_assertion":"@Test\n public void testYesterdayIsOverdue() {\nassertTrue(isOverdue(LocalDate.now().minusDays(1)), \"Yesterday should be overdue\");\n }\n\n @Test\n public void testTomorrowIsNotOverdue() {\n assertFalse(isOverdue(LocalDate.now().plusDays(1)), \"Tomorrow should not be overdue\");\n }\n\n @Test\n public void testTodayIsOverdue() {\nassertTrue(isOverdue(LocalDate.now()), \"Today (current time) should be considered after Today (start of day)\");\n }\n}", "comment":"the original method ignores time of day so assignments due on the same day are not overdue, the solution MUST set the deadline to the start of the day and compare with current date and time, so that assignemnts due on the same day are overdue. The unit test includes structural checks (as well as functional checks) to ensure refactoring." } {"id":"base_java_11","dataset_type":"base","language":"Java","task_category":"refactoring", "prompt_en":"this method groups transaction over 1000 by currency. refactor it to use streams and dont include imports", "prompt_nl":"deze methode groepeert transacties van meer dan 1000 per valuta. Refactor deze om streams te gebruiken en neem geen imports op.", "code_snippet_input":"public Map> groupHighValueTransactions(List transactions) {\nMap> result = new HashMap<>();\nfor (Transaction t : transactions) {\nif (t.getAmount() > 1000) {\nString currency = t.getCurrency();\nif (!result.containsKey(currency)) {\nresult.put(currency, new ArrayList<>());\n}\nresult.get(currency).add(t);\n}\n}\nreturn result;\n}", "canonical_solution":"public Map> groupHighValueTransactions(List transactions) {\nreturn transactions.stream()\n.filter(t -> t.getAmount() > 1000)\n.collect(Collectors.groupingBy(Transaction::getCurrency));\n}", "unit_test_setup":"import org.junit.jupiter.api.Test;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.nio.file.*;\nimport java.io.IOException;\nimport static org.junit.jupiter.api.Assertions.*;\n\nclass Transaction {\n private String currency;\n private double amount;\n public Transaction(String currency, double amount) { \n this.currency = currency; \n this.amount = amount; \n }\n public String getCurrency() { return currency; }\n public double getAmount() { return amount; }\n}\n\npublic class Solution {\n", "unit_test_assertion":" @Test\n public void testGrouping() {\n List data = Arrays.asList(\n new Transaction(\"USD\", 500),\n new Transaction(\"USD\", 1500),\n new Transaction(\"EUR\", 2000),\n new Transaction(\"USD\", 3000)\n );\n \n Map> result = groupHighValueTransactions(data);\n \n assertEquals(2, result.size());\n assertEquals(2, result.get(\"USD\").size());\n }\n\n @Test\n public void testRefactoringCompliance() throws IOException {\n \n String source = Files.readString(Path.of(\"Solution.java\"));\n \n assertTrue(source.contains(\".stream(\"), \"LLM failed to use Stream API\");\n assertTrue(source.contains(\".collect(\"), \"LLM failed to use Collector\");\n assertFalse(source.contains(\"for (\"), \"LLM failed to remove 'for' loop\");\n }\n}", "comment":"RUNNER MUST SAVE SOLUTION IN Solution.java Includes a structural check to ensure the LLM actually followed the instruction to use Streams. The unit test includes structural checks (as well as functional checks) to ensure refactoring." } {"id":"base_java_12","dataset_type":"base","language":"Java","task_category":"refactoring", "prompt_en":"This is a method that returns a discount code based on the day of the week, refactor the method to use a modern switch expression. Keep the same functionality and don't include imports", "prompt_nl":"Dit is een methode die een kortingscode retourneert op basis van de dag van de week. Herstructureer de methode om een moderne switch-expressie te gebruiken. Behoud dezelfde functionaliteit en neem geen imports op.", "code_snippet_input":"public String getDiscountCode(String dayOfWeek) {\nString discount;\nswitch (dayOfWeek) {\ncase \"Monday\":\ndiscount = \"MANIC_MONDAY_15\";\nbreak;\ncase \"Wednesday\":\ndiscount = \"WACKY_WED_10\";\nbreak;\ncase \"Friday\":\ndiscount = \"TGIF_25\";\nbreak;\ncase \"Saturday\":\ncase \"Sunday\":\ndiscount = \"WEEKEND_SAVER_20\";\nbreak;\ndefault:\ndiscount = \"STANDARD_PRICING\";\nbreak;\n}\nreturn discount;\n}", "canonical_solution":"public String getDiscountCode(String dayOfWeek) {\nreturn switch (dayOfWeek) {\ncase \"Monday\" -> \"MANIC_MONDAY_15\";\ncase \"Wednesday\" -> \"WACKY_WED_10\";\ncase \"Friday\" -> \"TGIF_25\";\ncase \"Saturday\", \"Sunday\" -> \"WEEKEND_SAVER_20\";\ndefault -> \"STANDARD_PRICING\";\n};\n}", "unit_test_setup":"import org.junit.jupiter.api.Test;\nimport java.nio.file.*;\nimport java.io.IOException;\nimport static org.junit.jupiter.api.Assertions.*;\n\npublic class Solution {\n", "unit_test_assertion":" @Test\n public void testDiscounts() {\n assertEquals(\"MANIC_MONDAY_15\", getDiscountCode(\"Monday\"));\n assertEquals(\"WEEKEND_SAVER_20\", getDiscountCode(\"Sunday\"));\n assertEquals(\"STANDARD_PRICING\", getDiscountCode(\"Tuesday\"));\n }\n\n @Test\n public void testModernSyntax() throws IOException {\n String source = Files.readString(Path.of(\"Solution.java\"));\n \n assertTrue(source.contains(\"->\"), \"LLM failed to use modern arrow syntax '->'\");\n assertFalse(source.contains(\"break;\"), \"LLM failed to remove legacy 'break' statements\");\n }\n}", "comment":"RUNNER MUST SAVE SOLUTION IN Solution.java the old method uses the old switch statement with multiple breaks and variable assignments, the solution MUST use the modern switch expression syntax introduced in Java 14 while keeping the same functionality. The unit test includes structural checks (as well as functional checks) to ensure refactoring." } {"id":"base_javascript_01","dataset_type":"base","language":"JavaScript","task_category":"scaffolding", "prompt_en":"write a JavaScript function called createReactScaffold(projectName) that creates a basic project structure for a React app using Vite. Return ONLY the function.", "prompt_nl":"Schrijf een JavaScript-functie met de naam createReactScaffold(projectName) die een basisprojectstructuur voor een React-app maakt met behulp van Vite. Retourneer ALLEEN de functie.", "code_snippet_input":"", "canonical_solution":"const fs = require('fs');\nconst path = require('path');\nfunction createReactScaffold(projectName) {\nconst rootDir = path.resolve(process.cwd(), projectName);\nconst dirs = [\nrootDir,\npath.join(rootDir, 'src'),\npath.join(rootDir, 'public')\n];\ndirs.forEach(dir => {\nif (!fs.existsSync(dir)) {\nfs.mkdirSync(dir, { recursive: true });\n}\n});\nconst indexHtml = `\n\n\n\n\nVite + React\n\n\n
\n\n\n`;\nconst packageJson = {\nname: projectName,\nprivate: true,\nversion: '0.0.0',\ntype: 'module',\nscripts: {\ndev: 'vite',\nbuild: 'vite build',\nlint: 'eslint .',\npreview: 'vite preview'\n},\ndependencies: {\nreact: '^18.2.0',\n'react-dom': '^18.2.0'\n},\ndevDependencies: {\n'@types/react': '^18.2.0',\n'@types/react-dom': '^18.2.0',\n'@vitejs/plugin-react': '^4.2.0',\nvite: '^5.0.0'\n}\n};\nconst viteConfig = `import { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n// https://vitejs.dev/config/\nexport default defineConfig({\nplugins: [react()],\n})`;\nconst mainJsx = `import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App.jsx'\nimport './index.css'\nReactDOM.createRoot(document.getElementById('root')).render(\n\n\n,\n)`;\nconst appJsx = `import { useState } from 'react'\nimport './App.css'\nfunction App() {\nconst [count, setCount] = useState(0)\nreturn (\n<>\n

Vite + React

\n
\n\n
\n\n)\n}\nexport default App`;\nconst files = [\n{ path: path.join(rootDir, 'index.html'), content: indexHtml },\n{ path: path.join(rootDir, 'package.json'), content: JSON.stringify(packageJson, null, 2) },\n{ path: path.join(rootDir, 'vite.config.js'), content: viteConfig },\n{ path: path.join(rootDir, '.gitignore'), content: 'node_modules\ndist\n.env' },\n{ path: path.join(rootDir, 'src', 'main.jsx'), content: mainJsx },\n{ path: path.join(rootDir, 'src', 'App.jsx'), content: appJsx },\n{ path: path.join(rootDir, 'src', 'App.css'), content: '/* App styles */' },\n{ path: path.join(rootDir, 'src', 'index.css'), content: '/* Global styles */' },\n{ path: path.join(rootDir, 'public', 'vite.svg'), content: '' }\n];\nfiles.forEach(file => {\nfs.writeFileSync(file.path, file.content.trim());\n});\nconsole.log(`React Vite project created at ${rootDir}`);\n}", "unit_test_setup":"", "unit_test_assertion":"" } {"id":"base_javascript_02","dataset_type":"base","language":"JavaScript","task_category":"elem_func", "prompt_en":"", "prompt_nl":"", "code_snippet_input":"", "canonical_solution":"", "unit_test_setup":"", "unit_test_assertion":"" } {"id":"base_javascript_03","dataset_type":"base","language":"JavaScript","task_category":"id_bug", "prompt_en":"", "prompt_nl":"", "code_snippet_input":"", "canonical_solution":"", "unit_test_setup":"", "unit_test_assertion":"" } {"id":"base_javascript_04","dataset_type":"base","language":"JavaScript","task_category":"fix_bug", "prompt_en":"", "prompt_nl":"", "code_snippet_input":"", "canonical_solution":"", "unit_test_setup":"", "unit_test_assertion":"" } {"id":"base_javascript_05","dataset_type":"base","language":"JavaScript","task_category":"fix_bug", "prompt_en":"", "prompt_nl":"", "code_snippet_input":"", "canonical_solution":"", "unit_test_setup":"", "unit_test_assertion":"" } {"id":"base_javascript_06","dataset_type":"base","language":"JavaScript","task_category":"architecture", "prompt_en":"", "prompt_nl":"", "code_snippet_input":"", "canonical_solution":"", "unit_test_setup":"", "unit_test_assertion":"" } {"id":"base_javascript_07","dataset_type":"base","language":"JavaScript","task_category":"refactoring", "prompt_en":"", "prompt_nl":"", "code_snippet_input":"", "canonical_solution":"", "unit_test_setup":"", "unit_test_assertion":"" } {"id":"base_javascript_08","dataset_type":"base","language":"JavaScript","task_category":"refactoring", "prompt_en":"", "prompt_nl":"", "code_snippet_input":"", "canonical_solution":"", "unit_test_setup":"", "unit_test_assertion":"" } {"id":"base_python_01","dataset_type":"base","language":"Python","task_category":"scaffolding", "prompt_en":"Write a method createScaffold(project_name, root_dir) in python that creates a basic project structure for a kotlin project using gradle. Return ONLY the method", "prompt_nl":"Schrijf een methode createScaffold in Python die een basisprojectstructuur voor een Kotlin-project maakt met behulp van Gradle. Retourneer ALLEEN de methode.", "code_snippet_input":"", "canonical_solution":"from pathlib import Path\n\ndef createScaffold(project_name: str, root_dir: str = \".\"):\n base_path = Path(root_dir) / project_name\n \n directories = [\n base_path / \"src/main/kotlin\",\n base_path / \"src/main/resources\",\n base_path / \"src/test/kotlin\",\n base_path / \"src/test/resources\",\n base_path / \"gradle/wrapper\"\n ]\n \n files = {\n base_path / \"settings.gradle.kts\": f'rootProject.name = \"{project_name}\"\\n',\n base_path / \"build.gradle.kts\": \"\"\"plugins {\n kotlin(\"jvm\") version \"1.9.22\"\n}\ngroup = \"org.example\"\nversion = \"1.0-SNAPSHOT\"\nrepositories {\n mavenCentral()\n}\ndependencies {\n testImplementation(kotlin(\"test\"))\n}\ntasks.test {\n useJUnitPlatform()\n}\n\"\"\",\n base_path / \".gitignore\": \"\"\"\n.gradle/\nbuild/\nout/\n.idea/\n*.iml\n.DS_Store\n\"\"\",\n base_path / \"README.md\": f\"# {project_name}\\n\\nGenerated Kotlin/Gradle Project.\",\n base_path / \"gradle/wrapper/gradle-wrapper.properties\": \"\"\"distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-8.5-bin.zip\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n\"\"\"\n }\n\n print(f\"Creating Kotlin/Gradle scaffold for '{project_name}'...\")\n for d in directories:\n d.mkdir(parents=True, exist_ok=True)\n \n for path, content in files.items():\n path.write_text(content, encoding=\"utf-8\")\n \n print(f\"Project created at {base_path.resolve()}\")", "unit_test_setup":"import unittest\nimport tempfile\nimport shutil\nfrom pathlib import Path\nimport os\n\n", "unit_test_assertion":"class TestKotlinScaffold(unittest.TestCase):\n def setUp(self):\n self.test_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n shutil.rmtree(self.test_dir)\n\n def test_directory_structure(self):\n project_name = \"MyKotlinApp\"\n createScaffold(project_name, self.test_dir)\n \n base = Path(self.test_dir) / project_name\n \n required_dirs = [\n \"src/main/kotlin\",\n \"src/test/kotlin\",\n \"gradle/wrapper\"\n ]\n for d in required_dirs:\n self.assertTrue((base / d).exists(), f\"Directory missing: {d}\")\n self.assertTrue((base / d).is_dir(), f\"Path is not a directory: {d}\")\n \n required_files = [\n \"build.gradle.kts\",\n \"settings.gradle.kts\",\n \".gitignore\"\n ]\n for f in required_files:\n self.assertTrue((base / f).exists(), f\"File missing: {f}\")\n \n settings_content = (base / \"settings.gradle.kts\").read_text()\n self.assertIn(f'rootProject.name = \"{project_name}\"', settings_content, \"settings.gradle.kts has wrong project name\")\n\nif __name__ == '__main__':\n unittest.main()", "comment":"the solution MUST create src/main/kotlin, src/test/kotlin, gradle/wrapper directories and settings.gradle.kts, build.gradle.kts, .gitignore files, the root project name MUST be correctly assigned in settings.gradle.kts." } {"id":"base_python_02","dataset_type":"base","language":"Python","task_category":"scaffolding", "prompt_en":"write a function called create_vue_scaffold(project_name: str) that creates a basic project structure for a Vue 3 project using Vite. Return ONLY the function.", "prompt_nl":"Schrijf een functie met de naam create_vue_scaffold(project_name: str) die een basisprojectstructuur voor een Vue 3-project maakt met behulp van Vite. Geef ALLEEN de functie terug.", "code_snippet_input":"", "canonical_solution":"from pathlib import Path\n\ndef create_vue_scaffold(project_name: str):\n base = Path(project_name)\n src = base / \"src\"\n \n dirs = [\n base / \"public\",\n src / \"assets\",\n src / \"components\",\n src / \"views\",\n src / \"stores\",\n src / \"router\",\n ]\n \n files = {\n base / \"index.html\": \"\"\"\n\n \n
\n \n \n\"\"\",\n base / \"vite.config.js\": \"\"\"import { fileURLToPath, URL } from 'node:url'\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nexport default defineConfig({\n plugins: [vue()],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url))\n }\n }\n})\"\"\",\n base / \"package.json\": f\"\"\"{{\n \"name\": \"{project_name}\",\n \"version\": \"0.0.0\",\n \"scripts\": {{\n \"dev\": \"vite\",\n \"build\": \"vite build\"\n }},\n \"dependencies\": {{\n \"vue\": \"^3.4.0\",\n \"pinia\": \"^2.1.0\",\n \"vue-router\": \"^4.2.0\"\n }},\n \"devDependencies\": {{\n \"@vitejs/plugin-vue\": \"^5.0.0\",\n \"vite\": \"^5.0.0\"\n }}\n}}\"\"\",\n src / \"main.js\": \"\"\"import { createApp } from 'vue'\nimport { createPinia } from 'pinia'\nimport App from './App.vue'\nimport router from './router'\nconst app = createApp(App)\napp.use(createPinia())\napp.use(router)\napp.mount('#app')\n\"\"\",\n src / \"App.vue\": \"\"\"\n\n\"\"\"\n }\n\n # Execution\n print(f\"Scaffolding Vue project: {project_name}\")\n for d in dirs:\n d.mkdir(parents=True, exist_ok=True)\n \n for path, content in files.items():\n path.write_text(content, encoding=\"utf-8\")", "unit_test_setup":"import unittest\nimport tempfile\nimport shutil\nimport os\nfrom pathlib import Path\n\n", "unit_test_assertion":"class TestVueScaffold(unittest.TestCase):\n def setUp(self):\n self.test_dir = tempfile.mkdtemp()\n self.original_cwd = os.getcwd()\n os.chdir(self.test_dir)\n\n def tearDown(self):\n os.chdir(self.original_cwd)\n shutil.rmtree(self.test_dir)\n\n def test_vue_structure(self):\n project_name = \"frontend-app\"\n create_vue_scaffold(project_name)\n \n base = Path(project_name)\n \n self.assertTrue((base / \"src/components\").is_dir(), \"Missing src/components\")\n self.assertTrue((base / \"src/views\").is_dir(), \"Missing src/views\")\n self.assertTrue((base / \"public\").is_dir(), \"Missing public folder\")\n \n # Check vital files\n self.assertTrue((base / \"vite.config.js\").exists(), \"Missing vite.config.js\")\n self.assertTrue((base / \"package.json\").exists(), \"Missing package.json\")\n self.assertTrue((base / \"src/App.vue\").exists(), \"Missing App.vue\")\n \n pkg_json = (base / \"package.json\").read_text()\n self.assertIn('\"name\": \"frontend-app\"', pkg_json, \"package.json name not set correctly\")\n\nif __name__ == '__main__':\n unittest.main()", "comment":"solution MUST create src/components, src/views, public directories and vite.config.js, package.json, src/App.vue files, the project name MUST be correctly assigned in package.json." } {"id":"base_python_03","dataset_type":"base","language":"Python","task_category":"elem_func", "prompt_en":"make a patient class in python with fields patient_id (int), first_name (str), last_name (str), birth_date (str in YYYY-MM-DD format), is_active (bool), gp_id (int), zip_code (str), with pythonic setters, getters and contructor.", "prompt_nl":"Maak een patiëntklasse in Python met de velden patient_id (int), first_name (str), last_name (str), birth_date (str in YYYY-MM-DD-formaat), is_active (bool), gp_id (int), zip_code (str), met pythonic setters, getters en constructor.", "code_snippet_input":"", "canonical_solution":"class Patient:\n def __init__(self, patient_id: int, first_name: str, last_name: str, birth_date: str, is_active: bool, gp_id: int, zip_code: str):\n self._patient_id = patient_id\n self._first_name = first_name\n self._last_name = last_name\n self._birth_date = birth_date\n self._is_active = is_active\n self._gp_id = gp_id\n self._zip_code = zip_code\n\n @property\n def patient_id(self):\n return self._patient_id\n\n @patient_id.setter\n def patient_id(self, value):\n self._patient_id = value\n\n @property\n def first_name(self):\n return self._first_name\n\n @first_name.setter\n def first_name(self, value):\n self._first_name = value\n\n @property\n def last_name(self):\n return self._last_name\n\n @last_name.setter\n def last_name(self, value):\n self._last_name = value\n\n @property\n def birth_date(self):\n return self._birth_date\n\n @birth_date.setter\n def birth_date(self, value):\n self._birth_date = value\n\n @property\n def is_active(self):\n return self._is_active\n\n @is_active.setter\n def is_active(self, value):\n self._is_active = value\n\n @property\n def gp_id(self):\n return self._gp_id\n\n @gp_id.setter\n def gp_id(self, value):\n self._gp_id = value\n\n @property\n def zip_code(self):\n return self._zip_code\n\n @zip_code.setter\n def zip_code(self, value):\n self._zip_code = value", "unit_test_setup":"import unittest\n\n", "unit_test_assertion":"class TestPatientClass(unittest.TestCase):\n def test_properties(self):\n p = Patient(101, \"John\", \"Doe\", \"1980-05-20\", True, 55, \"1000AB\")\n \n self.assertEqual(p.first_name, \"John\")\n self.assertEqual(p.gp_id, 55)\n self.assertTrue(p.is_active)\n \n p.first_name = \"Jane\"\n self.assertEqual(p.first_name, \"Jane\", \"Property setter failed for first_name\")\n \n p.is_active = False\n self.assertFalse(p.is_active, \"Property setter failed for is_active\")\n \n self.assertTrue(isinstance(Patient.first_name, property), \"Field 'first_name' must use @property decorator\")\n self.assertTrue(isinstance(Patient.gp_id, property), \"Field 'gp_id' must use @property decorator\")\n self.assertTrue(isinstance(Patient.zip_code, property), \"Field 'zip_code' must use @property decorator\")\n\nif __name__ == '__main__':\n unittest.main()", "comment":"solution MUST implement the patient class with AT LEAST the fields with the correct types specified in the prompt, and MUST use the @property decorator for getters and setters." } {"id":"base_python_04","dataset_type":"base","language":"Python","task_category":"elem_func", "prompt_en":"write a class Transaction with fields transaction_id (int), user_id (int), amount (float), currency (str), timestamp (str in ISO 8601 format), status (bool), and pythonic setters, getters and constructor. ", "prompt_nl":"Schrijf een klasse Transaction met velden transaction_id (int), user_id (int), amount (float), currency (str), timestamp (str in ISO 8601-formaat), status (bool) en pythonic setters, getters en constructor.", "code_snippet_input":"", "canonical_solution":"class Transaction:\n def __init__(self, transaction_id: int, user_id: int, amount: float, \n currency: str, timestamp: str, status: bool):\n self.transaction_id = transaction_id\n self.user_id = user_id\n self.amount = amount\n self.currency = currency\n self.timestamp = timestamp\n self.status = status\n @property\n def transaction_id(self) -> int:\n return self._transaction_id\n @transaction_id.setter\n def transaction_id(self, value: int):\n if not isinstance(value, int):\n raise TypeError(\"Transaction ID must be an integer\")\n self._transaction_id = value\n @property\n def user_id(self) -> int:\n return self._user_id\n @user_id.setter\n def user_id(self, value: int):\n if not isinstance(value, int):\n raise TypeError(\"User ID must be an integer\")\n self._user_id = value\n @property\n def amount(self) -> float:\n return self._amount\n @amount.setter\n def amount(self, value: float):\n if not isinstance(value, (int, float)):\n raise TypeError(\"Amount must be a number\")\n if value < 0:\n raise ValueError(\"Amount cannot be negative\")\n self._amount = float(value)\n @property\n def currency(self) -> str:\n return self._currency\n @currency.setter\n def currency(self, value: str):\n if not isinstance(value, str):\n raise TypeError(\"Currency must be a string\")\n if len(value) != 3:\n raise ValueError(\"Currency must be a 3-letter ISO code (e.g., 'USD')\")\n self._currency = value.upper()\n @property\n def timestamp(self) -> str:\n return self._timestamp\n @timestamp.setter\n def timestamp(self, value: str):\n if not isinstance(value, str):\n raise TypeError(\"Timestamp must be a string (ISO 8601)\")\n self._timestamp = value\n @property\n def status(self) -> bool:\n return self._status\n @status.setter\n def status(self, value: bool):\n if not isinstance(value, bool):\n raise TypeError(\"Status must be a boolean\")\n self._status = value\n def __repr__(self):\n return (f\"Transaction(id={self.transaction_id}, user={self.user_id}, \"\n f\"amount={self.amount} {self.currency}, status={self.status})\")", "unit_test_setup": "import unittest\n\n", "unit_test_assertion": "class TestTransactionClass(unittest.TestCase):\n def test_pythonic_properties(self):\n t = Transaction(1, 101, 50.0, \"EUR\", \"2023-01-01T12:00:00Z\", True)\n self.assertEqual(t.amount, 50.0)\n self.assertEqual(t.currency, \"EUR\")\n \n t.amount = 75.50\n self.assertEqual(t.amount, 75.50)\n t.status = False\n self.assertFalse(t.status)\n \n # 3. Meta-Test: Verify @property usage\n self.assertTrue(isinstance(Transaction.amount, property), \"Field 'amount' is not a @property\")\n self.assertTrue(isinstance(Transaction.transaction_id, property), \"Field 'transaction_id' is not a @property\")\n\nif __name__ == '__main__':\n unittest.main()", "comment":"solution MUST implement the transaction class with AT LEAST the fields with the correct types specified in the prompt, and MUST use the @property decorator for getters and setters." } {"id":"base_python_05","dataset_type":"base","language":"Python","task_category":"id_bug", "prompt_en":"This function cleans transactions but it doesn't seem to be updating the dataframe correctly when it should. Fix the bugs in the function.", "prompt_nl":"Deze functie ruimt transacties op, maar lijkt het gegevensframe niet correct bij te werken wanneer dat nodig is. Los de bugs in de functie op.", "code_snippet_input":"import pandas as pd\nimport numpy as np\ndef clean_transactions(df):\n df = df[df['amount'] >= 0]\n df['category'] = df['category'].fillna('Unknown')\n df[df['risk_score'] > 0.9]['amount'] = 1000\n return df", "canonical_solution":"import pandas as pd\nimport numpy as np\ndef clean_transactions(df):\n df = df[df['amount'] >= 0]\n df['category'] = df['category'].fillna('Unknown')\n df.loc[df['risk_score'] > 0.9, 'amount'] = 1000\n return df", "unit_test_setup":"import pandas as pd\nimport numpy as np\nimport unittest\n\n", "unit_test_assertion":"class TestTransactionCleaning(unittest.TestCase):\n def test_logic(self):\n data = {\n 'id': [1, 2, 3, 4],\n 'amount': [100.0, -50.0, 200.0, 5000.0],\n 'category': ['Food', 'Food', np.nan, 'Travel'],\n 'risk_score': [0.1, 0.5, 0.1, 0.95]\n }\n df = pd.DataFrame(data)\n \n result = clean_transactions(df)\n \n self.assertFalse((result['amount'] < 0).any(), \"Negative amounts should be removed.\")\n self.assertEqual(len(result), 3, \"Row count mismatch. Did you filter negative amounts?\")\n \n cat_val = result.loc[result['id'] == 3, 'category'].values[0]\n self.assertEqual(cat_val, 'Unknown', \"NaN category should be replaced with 'Unknown'.\")\n \n risk_amount = result.loc[result['id'] == 4, 'amount'].values[0]\n self.assertEqual(risk_amount, 1000.0, \"High risk transactions (>0.9) must be capped at 1000. Did you use .loc?\")\n\nif __name__ == '__main__':\n unittest.main()", "comment":"df[df['risk_score'] > 0.9]['amount'] = 1000 creates a copy of the filtered df and modifies that copy, not the original df. The solution MUST use .loc to correctly update the original dataframe." } {"id":"base_python_06","dataset_type":"base","language":"Python","task_category":"id_bug", "prompt_en":"This python recursively searches through a nested dictionary to find all values associated with a given key, but it's returning more values than it should. Fix the bugs in the function.", "prompt_nl":"Deze python doorzoekt recursief een geneste woordenlijst om alle waarden te vinden die bij een bepaalde sleutel horen, maar geeft meer waarden terug dan zou moeten. Los de bugs in de functie op.", "code_snippet_input":"def extract_all_values(data, target_key, results=[]):\n if isinstance(data, dict):\n for key, value in data.items():\n if key == target_key:\n results.append(value)\n if isinstance(value, (dict, list)):\n extract_all_values(value, target_key, results)\n elif isinstance(data, list):\n for item in data:\n extract_all_values(item, target_key, results)\n return results", "canonical_solution":"def extract_all_values(data, target_key, results=None):\n if results is None:\n results = []\n if isinstance(data, dict):\n for key, value in data.items():\n if key == target_key:\n results.append(value)\n if isinstance(value, (dict, list)):\n extract_all_values(value, target_key, results)\n elif isinstance(data, list):\n for item in data:\n extract_all_values(item, target_key, results)\n return results", "unit_test_setup":"import unittest\n\n", "unit_test_assertion":"class TestRecursiveSearch(unittest.TestCase):\n def test_mutable_default(self):\n data1 = {'id': 101, 'meta': {'id': 102, 'name': 'test'}}\n res1 = extract_all_values(data1, 'id')\n self.assertEqual(sorted(res1), [101, 102], \"First call failed to extract correct IDs\")\n\n data2 = {'id': 999}\n res2 = extract_all_values(data2, 'id')\n \n self.assertEqual(res2, [999], f\"Memory Leak Detected! Expected [999] but got {res2}. Did you remove the mutable default argument?\")\n\nif __name__ == '__main__':\n unittest.main()", "comment":"python instantiates arguemnts once at function definition, so the results list is shared across calls. The solution MUST set results=None and initialize it inside the function to ensure a fresh list on each call." } {"id":"base_python_07","dataset_type":"base","language":"Python","task_category":"id_bug", "prompt_en":"I want this function to return the leaderboard of all players with their scores, but when players don't finish the game and don't have a score they are missing when they should appear.", "prompt_nl":"Ik wil dat deze functie het klassement van alle spelers met hun scores weergeeft, maar soms ontbreken sommige spelers terwijl ze wel zouden moeten verschijnen.", "code_snippet_input":"import time\ndef process_match_report(players, match_scores):\n report = []\n for player, score in zip(players, match_scores):\n entry = {\n \"player_id\": player[\"id\"],\n \"username\": player[\"username\"],\n \"score\": score,\n \"status\": \"Ranked\",\n \"processed_at\": time.strftime(\"%H:%M:%S\")\n }\n report.append(entry)\n return report", "canonical_solution":"from itertools import zip_longest\nimport time\ndef process_match_report(players, match_scores):\n report = []\n for player, score in zip_longest(players, match_scores, fillvalue=None):\n if score is None:\n final_score = 0\n status = \"Unranked (No Play)\"\n else:\n final_score = score\n status = \"Ranked\"\n entry = {\n \"player_id\": player[\"id\"],\n \"username\": player[\"username\"],\n \"score\": final_score,\n \"status\": status,\n \"processed_at\": time.strftime(\"%H:%M:%S\")\n }\n report.append(entry)\n return report", "unit_test_setup":"import unittest\nimport time\n\n", "unit_test_assertion":"class TestLeaderboard(unittest.TestCase):\n def test_missing_players(self):\n players = [\n {\"id\": 1, \"username\": \"Alice\"},\n {\"id\": 2, \"username\": \"Bob\"},\n {\"id\": 3, \"username\": \"Charlie\"}\n ]\n scores = [100]\n \n report = process_match_report(players, scores)\n \n self.assertEqual(len(report), 3, f\"Data Loss! Expected 3 players, got {len(report)}. zip() drops items if lists are unequal.\")\n \n bob_entry = next((r for r in report if r['username'] == 'Bob'), None)\n self.assertIsNotNone(bob_entry, \"Bob is missing from the report\")\n self.assertTrue(bob_entry['score'] == 0 or bob_entry['score'] is None, \"Bob should have a default score (0 or None)\")\n\nif __name__ == '__main__':\n unittest.main()", "comment":"the zip function drops the extra players when the match_scores list is shorter, solution MUST use zip_longest with fillvalue=None to ensure all players are included." } {"id":"base_python_08","dataset_type":"base","language":"Python","task_category":"fix_bug", "prompt_en":"this method is supposed to calculate the average of all positive numbers in a list, but it's not working correctly. Fix the bugs in the function.", "prompt_nl":"Deze methode moet het gemiddelde berekenen van alle positieve getallen in een lijst, maar werkt niet correct. Los de bugs in de functie op.", "code_snippet_input":"def calculate_average(numbers):\n total = 0\n count = 0\n for num in numbers:\n if num >= 0:\n total += num\n count += 1\n return total / count if count > 0 else 0", "canonical_solution":"def calculate_average(numbers):\n total = 0\n count = 0\n for num in numbers:\n if num >= 0:\n total += num\n count += 1\n return total / count if count > 0 else 0", "unit_test_setup":"import unittest\n\n", "unit_test_assertion":"class TestAverage(unittest.TestCase):\n def test_logic(self):\n self.assertEqual(calculate_average([10, -5, 20]), 15, \"Function returned early! Did you move the return statement outside the loop?\")\n \n self.assertEqual(calculate_average([]), 0, \"Empty list should return 0\")\n \n self.assertEqual(calculate_average([-1, -2, -3]), 0, \"No positive numbers should return 0\")\n\nif __name__ == '__main__':\n unittest.main()", "comment":"the return statement is too indented and executes in the first iteration the loop. the solution MUST unindent the return statement." } {"id":"base_python_09","dataset_type":"base","language":"Python","task_category":"fix_bug", "prompt_en":"this method counts how many times each word appears on a list. but it throws an error. Fix the bugs in the function.", "prompt_nl":"Deze methode telt hoe vaak elk woord in een lijst voorkomt. Maar er treedt een fout op. Los de bugs in de functie op.", "code_snippet_input":"#KeyError\ndef count_word_frequencies(words):\n frequency_map = {}\n for word in words:\n frequency_map[word] = frequency_map[word] + 1\n return frequency_map", "canonical_solution":"from collections import defaultdict\ndef count_word_frequencies(words):\n frequency_map = defaultdict(int) \n for word in words:\n frequency_map[word] += 1\n return dict(frequency_map)", "unit_test_setup":"import unittest\nfrom collections import defaultdict\n\n", "unit_test_assertion":"class TestFrequency(unittest.TestCase):\n def test_counting(self):\n input_words = [\"apple\", \"banana\", \"apple\", \"cherry\", \"banana\", \"banana\"]\n expected = {\"apple\": 2, \"banana\": 3, \"cherry\": 1}\n \n #result = count_word_frequencies(input_words)\n self.assertEqual(result, expected, \"Counts do not match expected frequencies\")\n\n def test_empty(self):\n self.assertEqual(count_word_frequencies([]), {}, \"Empty list should return empty dict\")\n\nif __name__ == '__main__':\n unittest.main()", "comment":"the original code fails every time it encounters a new word because the key doesn't exist in the disctionary yet. the solution MUST use defaultdict or get() to assign a default value 0 to new keys." } {"id":"base_python_10","dataset_type":"base","language":"Python","task_category":"fix_bug", "prompt_en":"this method counts how many times a target word appears on a file, but in some files it crashes. I want it to work on all of my files, fix the bug.", "prompt_nl":"Deze methode telt hoe vaak een bepaald woord in een bestand voorkomt, maar in sommige bestanden crasht het programma. Ik wil dat het in al mijn bestanden werkt, dus los de bug op.", "code_snippet_input":"#UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 12: invalid continuation byte\ndef count_word_occurrences(file_path, target_word):\n total_count = 0\n with open(file_path, 'r') as f:\n for line in f:\n words = line.lower().split()\n total_count += words.count(target_word.lower())\n return total_count", "canonical_solution":"def count_word_occurrences(file_path, target_word):\n total_count = 0\n with open(file_path, 'r', errors='replace') as f:\n for line in f:\n words = line.lower().split()\n total_count += words.count(target_word.lower())\n return total_count", "unit_test_setup":"import unittest\nimport tempfile\nimport os\n\n", "unit_test_assertion":"class TestEncoding(unittest.TestCase):\n def setUp(self):\n self.tf = tempfile.NamedTemporaryFile(delete=False)\n self.tf.write(b\"hello world caf\\xe9 python\")\n self.tf.close()\n\n def tearDown(self):\n os.remove(self.tf.name)\n\n def test_bad_encoding(self):\n try:\n count = count_word_occurrences(self.tf.name, \"python\")\n except UnicodeDecodeError:\n self.fail(\"Function crashed on non-UTF-8 file! Did you handle encoding errors?\")\n \n self.assertEqual(count, 1, \"Failed to count words in the problematic file\")\n\nif __name__ == '__main__':\n unittest.main()", "comment":"the original method crashes in some files if they contain non UTF-8 chracters (python's default file reading encoding). the solution MUST add errors='replace' to the open() call to handle such cases and make it compatible with EVERY text encoding format." } {"id":"base_python_11","dataset_type":"base","language":"Python","task_category":"architecture", "prompt_en":"Write a DAL to fetch the necessary data from a MSSQL database, for the display_menu function that uses SQLAlchemy.", "prompt_nl":"Schrijf een DAL om de benodigde gegevens uit een MSSQL database op te halen voor de functie display_menu die gebruikmaakt van SQLAlchemy.", "code_snippet_input":"def display_menu(session):\n pizzas = get_pizzas(session)\n items = get_items(session)\n\n print(\"\\nMenu Items:\")\n print(\"----------\")\n print(\"ID | Name | Price\")\n print(\"----------\")\n\n def line_item(mi):\n print(f\"{mi.Item_ID} | {mi.Item_Name} .......... {mi.Item_Price}\")\n def line_pizza(pi):\n vegan_badge = \" (vegan)\" if bool(pi.Vegan_Pizza) else \"\"\n vegetarian_badge = \" (vegetarian)\" if bool(pi.Vegetarian_Pizza) else \"\"\n\n # Note: calculate_price is assumed to exist externally\n print(f\"{pi.Pizza_ID} | {pi.Pizza_Name}{vegan_badge}{vegetarian_badge}.......... \")\n\n print(\"Pizzas:\")\n for pi in pizzas:\n line_pizza(pi)\n print(\"----------\")\n\n print(\"Drinks:\")\n for mi in items[10:20]:\n line_item(mi)\n print(\"----------\")\n\n print(\"Desserts:\")\n for mi in items[20:30]:\n line_item(mi)\n\n continue_message(session)", "canonical_solution":"def get_pizzas(session):\n query = \"SELECT Pizza_ID, Pizza_Name, Vegan_Pizza, Vegetarian_Pizza FROM Pizzas\"\n return session.execute(query).fetchall()\n\ndef get_items(session):\n query = \"SELECT Item_ID, Item_Name, Item_Price FROM Items\"\n return session.execute(query).fetchall()", "unit_test_setup":"from unittest.mock import MagicMock\n\nsession = MagicMock()\nsession.execute.return_value.fetchall.return_value = []\n\n\ndef continue_message(s): pass", "unit_test_assertion":"get_pizzas(session)\nargs_pizza, _ = session.execute.call_args\nsql_pizza = str(args_pizza[0]).replace('\\n', ' ').strip()\n\n\nassert \"SELECT\" in sql_pizza\nassert \"Pizza_ID\" in sql_pizza\nassert \"Pizza_Name\" in sql_pizza\nassert \"Vegan_Pizza\" in sql_pizza\nassert \"Vegetarian_Pizza\" in sql_pizza\nassert \"FROM Pizzas\" in sql_pizza\n\nsession.execute.reset_mock()\nget_items(session)\nargs_items, _ = session.execute.call_args\nsql_items = str(args_items[0]).replace('\\n', ' ').strip()\n\nassert \"Item_ID\" in sql_items\nassert \"Item_Name\" in sql_items\nassert \"Item_Price\" in sql_items\nassert \"FROM Items\" in sql_items", "comment":"the solution MUST implement get_pizzas(session) and get_items(session) to query the MSSQL database for pizzas and items using valid SQL statements, and infer the name of columns from the code snippet provided" } {"id":"base_python_12","dataset_type":"base","language":"Python","task_category":"architecture", "prompt_en":"write a ToppingDecorator class that uses a decorator pattern to add Pepperoni for 1.50, Mushrooms for 0.75, Mozarella for 1.00, Tuna for 2.00, and Olives for 0.50. retrun ONLY the new classes.", "prompt_nl":"Schrijf een ToppingDecorator klasse die een decorator pattern gebruikt om Pepperoni voor 1.50, Mushrooms voor 0.75, Mozzarella voor 1.00, Tuna voor 2.00 en Olives voor 0.50 toe te voegen. Geef ALLEEN de nieuwe classes terug", "code_snippet_input":"from abc import ABC, abstractmethod\nclass Pizza(ABC):\n @abstractmethod\n def get_description(self):\n pass\n @abstractmethod\n def get_cost(self):\n pass\n\nclass PlainPizza(Pizza):\n def get_description(self):\n return \"Thin dough\"\n def get_cost(self):\n return 4.00", "canonical_solution":"class ToppingDecorator(Pizza):\n def __init__(self, pizza: Pizza):\n self._pizza = pizza\n @abstractmethod\n def get_description(self):\n return self._pizza.get_description()\n @abstractmethod\n def get_cost(self):\n return self._pizza.get_cost()\n\nclass Pepperoni(ToppingDecorator):\n def get_description(self):\n return self._pizza.get_description() + \", Pepperoni\"\n def get_cost(self):\n return self._pizza.get_cost() + 1.50\nclass Mozzarella(ToppingDecorator):\n def get_description(self):\n return self._pizza.get_description() + \", Mozzarella\"\n def get_cost(self):\n return self._pizza.get_cost() + 1.00\nclass Mushrooms(ToppingDecorator):\n def get_description(self):\n return self._pizza.get_description() + \", Mushrooms\"\n def get_cost(self):\n return self._pizza.get_cost() + 0.75\nclass Tuna(ToppingDecorator):\n def get_description(self):\n return self._pizza.get_description() + \", Tuna\"\n def get_cost(self):\n return self._pizza.get_cost() + 2.00\nclass Olives(ToppingDecorator):\n def get_description(self):\n return self._pizza.get_description() + \", Olives\"\n def get_cost(self):\n return self._pizza.get_cost() + 0.50", "unit_test_setup":"import unittest\nfrom abc import ABC, abstractmethod\n\n\nclass Pizza(ABC):\n @abstractmethod\n def get_description(self):\n pass\n @abstractmethod\n def get_cost(self):\n pass\n\nclass PlainPizza(Pizza):\n def get_description(self):\n return \"Thin dough\"\n def get_cost(self):\n return 4.00\n", "unit_test_assertion":"class TestDecorator(unittest.TestCase):\n def test_pizza_stacking(self):\n my_pizza = PlainPizza()\n self.assertEqual(my_pizza.get_cost(), 4.00)\n \n my_pizza = Mozzarella(my_pizza)\n self.assertEqual(my_pizza.get_cost(), 5.00)\n self.assertIn(\"Mozzarella\", my_pizza.get_description())\n \n my_pizza = Pepperoni(my_pizza)\n self.assertEqual(my_pizza.get_cost(), 6.50)\n self.assertIn(\"Pepperoni\", my_pizza.get_description())\n \n desc = my_pizza.get_description()\n self.assertTrue(\"Thin dough\" in desc)\n self.assertTrue(\"Mozzarella\" in desc)\n self.assertTrue(\"Pepperoni\" in desc)\n\nif __name__ == '__main__':\n unittest.main()", "comment":"the solution MUST implement the ToppingDecorator class and the five topping classes that extend it, each adding their own description and cost to the base pizza." } {"id":"base_python_13","dataset_type":"base","language":"Python","task_category":"refactoring", "prompt_en":"Refactor this funtion to reduce code complexity by splitting it into smaller functions validate_order(order), calculate_total(order), apply_discount(total, discount_code), and generate_receipt(total) and process_order(order). also use a dictionary to avoid hardcoded values and reduce codde ducplication in the discount logic.", "prompt_nl":"Herstructureer deze functie om de complexiteit van de code te verminderen door deze op te splitsen in kleinere functies validate_order(order), calculate_total(order), apply_discount(total, discount_code) en generate_receipt(total). gebruik ook een woordenboek om hardgecodeerde waarden te vermijden en codeduplicatie in de kortingslogica te verminderen.", "code_snippet_input":"def process_order(order):\n if not order.get(\"items\"):\n return \"Order must contain items\"\n\n total = sum(item[\"price\"] * item[\"quantity\"] for item in order[\"items\"])\n\n if order.get(\"discount_code\") == \"SAVE10\":\n total *= 0.9 \n elif order.get(\"discount_code\") == \"SAVE20\":\n total *= 0.8\n elif order.get(\"discount_code\") == \"SAVE50\":\n total *= 0.5\n\n receipt = f\"Total: ${total:.2f}\"\n return receipt", "canonical_solution":"def validate_order(order):\n if not order.get(\"items\"):\n return False, \"Order must contain items\"\n return True, \"\"\n\ndef calculate_total(order):\n return sum(item[\"price\"] * item[\"quantity\"] for item in order[\"items\"])\n\ndef apply_discount(total, discount_code): discount_rates = {\n \"SAVE10\": 0.9,\n \"SAVE20\": 0.8,\n \"SAVE50\": 0.5\n }\n multiplier = discount_rates.get(discount_code, 1.0)\n return total * multiplier\n\ndef generate_receipt(total):\n return f\"Total: ${total:.2f}\"\n\ndef process_order(order):\n valid, message = validate_order(order)\n if not valid:\n return message\n total = calculate_total(order)\n total = apply_discount(total, order.get(\"discount_code\"))\n return generate_receipt(total)", "unit_test_setup":"import unittest\n\n", "unit_test_assertion":"class TestRefactoring(unittest.TestCase):\n def test_functionality(self):\n order = {\n \"items\": [{\"price\": 100, \"quantity\": 1}],\n \"discount_code\": \"SAVE20\"\n }\n self.assertEqual(process_order(order), \"Total: $80.00\")\n self.assertEqual(process_order({}), \"Order must contain items\")\n\n def test_structure(self):\n g = globals()\n required = ['validate_order', 'calculate_total', 'apply_discount', 'generate_receipt']\n for func in required:\n self.assertIn(func, g, f\"Missing required function: {func}\")\n \n def test_complexity_reduction(self):\n src = inspect.getsource(apply_discount)\n \n has_dict = \"{\" in src or \"dict(\" in src\n \n if_count = src.count(\"if \") + src.count(\"elif \")\n \n if not has_dict and if_count > 1:\n self.fail(\"You used multiple if/elif statements. Please use a Dictionary/Map constant to reduce code complexity.\")\n\nif __name__ == '__main__':\n unittest.main()", "comment":"the solution MUST split the origial function into the specified smaller functions, use the same method signature, and use a constant for the discount logic, while preserving the same functionality" } {"id": "base_python_14","dataset_type": "base","language": "Python","task_category": "refactoring", "prompt_en":"This is a legacy setup.py file. Refactor it into a modern pyproject.toml format. Return the result as a Python string inside a function named `get_pyproject_toml()`.", "prompt_nl":"Dit is een verouderd setup.py bestand. Herstructureer het naar een modern pyproject.toml formaat. Retourneer het resultaat als een Python string binnen een functie genaamd `get_pyproject_toml()`.", "code_snippet_input":"from setuptools import setup, find_packages\nsetup(\nname=\"legacy-data-tool\",\nversion=\"1.2.0\",\ndescription=\"A legacy tool for data processing that needs modernization.\",\nlong_description=open(\"README.md\").read(),\nlong_description_content_type=\"text/markdown\",\nurl=\"https://github.com/example/legacy-data-tool\",\nauthor=\"Jane Doe\",\nauthor_email=\"jane.doe@example.com\",\nlicense=\"MIT\",\nclassifiers=[\n\"Development Status :: 4 - Beta\",\n\"Intended Audience :: Developers\",\n\"Topic :: Software Development :: Build Tools\",\n\"License :: OSI Approved :: MIT License\",\n\"Programming Language :: Python :: 3.8\",\n\"Programming Language :: Python :: 3.9\",\n],\nkeywords=\"data processing, legacy, conversion test\",\npackages=find_packages(where=\"src\"),\npackage_dir={\"\": \"src\"},\npython_requires=\">=3.8, <4\",\ninstall_requires=[\n\"pandas>=1.3.0\",\n\"requests==2.26.0\",\n\"numpy\",\n],\nextras_require={\n\"dev\": [\"check-manifest\"],\n\"test\": [\"pytest\", \"coverage\"],\n},\nentry_points={\n\"console_scripts\": [\n\"data-cli=legacy_tool.cli:main\",\n],\n},\nproject_urls={\n\"Bug Reports\": \"https://github.com/example/legacy-data-tool/issues\",\n\"Source\": \"https://github.com/example/legacy-data-tool\",\n},\n)", "canonical_solution":"def get_pyproject_toml():\n return \"\"\"\n[build-system]\nrequires = [\"setuptools>=61.0\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"legacy-data-tool\"\nversion = \"1.2.0\"\ndescription = \"A legacy tool for data processing that needs modernization.\"\nreadme = \"README.md\"\nrequires-python = \">=3.8, <4\"\nlicense = {text = \"MIT\"}\nkeywords = [\"data processing\", \"legacy\", \"conversion test\"]\nauthors = [\n {name = \"Jane Doe\", email = \"jane.doe@example.com\"}\n]\nclassifiers = [\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"Topic :: Software Development :: Build Tools\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n]\ndependencies = [\n \"pandas>=1.3.0\",\n \"requests==2.26.0\",\n \"numpy\",\n]\n\n[project.optional-dependencies]\ndev = [\"check-manifest\"]\ntest = [\"pytest\", \"coverage\"]\n\n[project.scripts]\ndata-cli = \"legacy_tool.cli:main\"\n\n[project.urls]\n\"Bug Reports\" = \"https://github.com/example/legacy-data-tool/issues\"\n\"Source\" = \"https://github.com/example/legacy-data-tool\"\n\n[tool.setuptools.packages.find]\nwhere = [\"src\"]\n\"\"\"", "unit_test_setup":"import tomli\nimport unittest\n\n", "unit_test_assertion":"toml_string = get_pyproject_toml()\ntry:\n data = tomli.loads(toml_string)\nexcept Exception as e:\n raise AssertionError(f\"Invalid TOML syntax: {e}\")\n\nassert \"build-system\" in data\nassert data[\"project\"][\"name\"] == \"legacy-data-tool\"\nassert \"pandas>=1.3.0\" in data[\"project\"][\"dependencies\"]\n", "comment":"NEED TOMLI IN MY RUNNER. the solution MUST define a function called get_pyproject_toml() that returns a valid pyproject.toml string representing the same metadata as the legacy setup.py. The unit test checks that the returned string is valid TOML and contains key expected fields." } {"id":"base_python_15","dataset_type":"base","language":"Python","task_category":"refactoring", "prompt_en":"This function retrieves the names of all senior members from a any team in a nested structure. Refactor the method to use list comprehensions.", "prompt_nl":"Deze functie haalt de namen op van alle senior leden van elk team in een geneste structuur. Herstructureer de methode om list comprehensions te gebruiken.", "code_snippet_input":"def get_seniors_loop(data):\n seniors = []\n for team in data:\n for member in team['members']:\n if member['role'] == 'Senior':\n seniors.append(member['name'])\n return seniors", "canonical_solution":"def get_seniors_comp(data):\n return [\n member['name']\n for team in data\n for member in team['members']\n if member['role'] == 'Senior'\n ]", "unit_test_setup":"import unittest\nimport inspect\n\n", "unit_test_assertion":"class TestListComp(unittest.TestCase):\n def test_behavior(self):\n data = [\n {'members': [{'name': 'Alice', 'role': 'Junior'}, {'name': 'Bob', 'role': 'Senior'}]},\n {'members': [{'name': 'Charlie', 'role': 'Senior'}, {'name': 'Dave', 'role': 'Lead'}]}\n ]\n expected = ['Bob', 'Charlie']\n self.assertEqual(get_seniors_loop(data), expected)\n self.assertEqual(get_seniors_loop([]), [])\n\n def test_structure(self):\n src = inspect.getsource(get_seniors_loop)\n \n if \"append(\" in src:\n self.fail(\"You are still using .append(). Use a list comprehension instead.\")\n \n if \"[\" not in src or \"]\" not in src:\n self.fail(\"List comprehension brackets [] not found.\")\n\nif __name__ == '__main__':\n unittest.main()", "comment":"The solution MUST keep the same functionality, but change the implementation from nested for loops to a list comprehension." } {"id":"base_sql_01","dataset_type":"base","language":"SQL","dialect": "mssql","task_category":"queries", "prompt_en":"I am calculating and retrieving data for a tableau chart using an MSSQL query. Above the chart is AGG (average number of customer hours cost center), which is SUM([Direct Time In Hours])/[numberofclients].[Sum unique clients cost center]. Sum unique clients cost center is in Tableau with the following calculation: SUM({FIXED [Year], [Month], [Cost Center Name]: COUNTD([Client])}) I want the tableau to have a row per cost center per month, and all the data comes from the numberofclients table. Can you convert this to an MSSQL database query?", "prompt_nl":"Ik bereken en haal gegevens op voor een tableau chart met behulp van een MSSQL query. Boven de chart staat AGG (average number of customer hours cost center), wat SUM([Direct Time In Hours])/[numberofclients].[Sum unique clients cost center]. Som unieke klanten kostenplaats staat in Tableau met de volgende berekening: SUM({FIXED [Year], [Month], [Cost Center Name]: COUNTD([Client])}) Ik wil dat het tableau één rij per kostenplaats per maand heeft en dat alle gegevens afkomstig zijn uit de tabel numberofclients. Kunt u dit omzetten naar een MSSQL databasequery?", "code_snippet_input":"-- Schema Context:\n-- CREATE TABLE students (\n-- id INTEGER AUTO_INCREMENT UNIQUE,\n-- name VARCHAR(255),\n-- valedictorian BOOLEAN,\n-- ...\n-- );\n--\n-- CREATE TABLE valedictorians (\n-- id INTEGER UNIQUE\n-- );\n", "canonical_solution":"SELECT \n[Year],\n[Month],\n[Cost Center Name],\nSUM([Direct Time In Hours]) AS TotalHours,\nCOUNT(DISTINCT [Client]) AS UniqueClientsPerMonth,\nSUM([Direct Time In Hours]) / NULLIF(CAST(COUNT(DISTINCT [Client]) AS FLOAT), 0) AS AvgCustomerHours\nFROM \nnumberofclients\nGROUP BY \n[Year], \n[Month], \n[Cost Center Name];", "unit_test_setup":"CREATE TABLE numberofclients (\n [Year] INT,\n [Month] INT,\n [Cost Center Name] VARCHAR(255),\n [Client] VARCHAR(255),\n [Direct Time In Hours] FLOAT\n);\n\n-- Test Data: IT Dept, Jan 2023\nINSERT INTO numberofclients VALUES (2023, 1, 'IT', 'ClientA', 10.0);\nINSERT INTO numberofclients VALUES (2023, 1, 'IT', 'ClientA', 20.0); -- Same client, different hours (Total hours=30, Unique Clients=1)\nINSERT INTO numberofclients VALUES (2023, 1, 'IT', 'ClientB', 30.0); -- New client (Total IT hours=60, Unique Clients=2, Avg=30)", "unit_test_assertion":" @Test\n public void testSqlLogic(Connection conn) throws SQLException {\n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {\n \n assertTrue(rs.next(), \"Result set should have at least one row\");\n \n assertEquals(\"IT\", rs.getString(\"Cost Center Name\"));\n assertEquals(60.0, rs.getDouble(\"TotalHours\"), 0.01, \"Total hours sum failed\");\n assertEquals(2, rs.getInt(\"UniqueClientsPerMonth\"), \"Distinct client count failed\");\n \n assertEquals(30.0, rs.getDouble(\"AvgCustomerHours\"), 0.01, \"Average calculation failed\");\n }\n }", "comment":"the solution MUST group by year month and cost center name while summing direct hours and counting distinct clients to replicate the tableau logic, and MUST use valid MSSQL syntax." } {"id":"base_sql_02","dataset_type":"base","language":"SQL","dialect":"mysql","task_category":"queries", "prompt_en":"write an update statement in MySQL to set a column value based on a join with another table. update the field valedictorian to true if and only if the student appears in the valedictorians table.", "prompt_nl":"schrijf een update statement in MySQL om een kolomwaarde in te stellen op basis van een join met een andere tabel. werk het veld valedictorian bij naar true als en alleen als de student voorkomt in de tabel valedictorians.", "code_snippet_input":"-- Schema Context:\n-- CREATE TABLE students (\n-- id INTEGER AUTO_INCREMENT UNIQUE,\n-- name VARCHAR(255),\n-- valedictorian BOOLEAN,\n-- ...\n-- );\n--\n-- CREATE TABLE valedictorians (\n-- id INTEGER UNIQUE\n-- );\n\n-- Write your UPDATE statement below:", "canonical_solution":"UPDATE students s\nLEFT JOIN valedictorians v ON s.id = v.id\nSET s.valedictorian = (v.id IS NOT NULL);", "unit_test_setup":"CREATE TABLE students (\n id INT AUTO_INCREMENT PRIMARY KEY,\n name VARCHAR(255),\n valedictorian BOOLEAN\n);\nCREATE TABLE valedictorians (\n id INT PRIMARY KEY\n);\n\nINSERT INTO students (id, name, valedictorian) VALUES (1, 'Alice', FALSE);\nINSERT INTO valedictorians (id) VALUES (1);\nINSERT INTO students (id, name, valedictorian) VALUES (2, 'Bob', TRUE);", "unit_test_assertion":"@Test\n public void testUpdateLogic(Connection conn) throws SQLException {\n try (Statement stmt = conn.createStatement()) {\n stmt.executeUpdate(generatedSqlQuery);\n \n \n ResultSet rs1 = stmt.executeQuery(\"SELECT valedictorian FROM students WHERE id = 1\");\n assertTrue(rs1.next());\n assertTrue(rs1.getBoolean(\"valedictorian\"), \"Alice should be updated to TRUE (1)\");\n \n ResultSet rs2 = stmt.executeQuery(\"SELECT valedictorian FROM students WHERE id = 2\");\n assertTrue(rs2.next());\n assertFalse(rs2.getBoolean(\"valedictorian\"), \"Bob should be updated to FALSE (0)\");\n }\n }", "comment":"the solution MUST change the valedictorian field to TRUE if it DOES appears in valedictorian table, and to FALSE if it does NOT appear in the valedictorian table." } {"id":"base_sql_03","dataset_type":"base","language":"SQL","dialect":"postgresql","task_category":"queries", "prompt_en":"calculate a 3-day moving average of sales_amount for each department that includes date, department, sales_amount, and the calculated moving average as moving_avg_3_day.", "prompt_nl":"Bereken een 3-daags voortschrijdend gemiddelde van sales_amount voor elke afdeling, inclusief date, department, sales_amount en het berekende voortschrijdend gemiddelde als moving_avg_3_day.", "code_snippet_input":"-- CREATE TABLE daily_sales ( \n-- id INT PRIMARY KEY, \n--date DATE NOT NULL, \n--department VARCHAR(50) NOT NULL, \n--sales_amount DECIMAL(10, 2) NOT NULL, \n--INDEX idx_dept_date (department, date)\n--);", "canonical_solution":"SELECT \ndate,\ndepartment,\nsales_amount,\nAVG(sales_amount) OVER (\nPARTITION BY department \nORDER BY date\nROWS BETWEEN 2 PRECEDING AND CURRENT ROW\n) as moving_avg_3_day\nFROM daily_sales;", "unit_test_setup":"CREATE TABLE daily_sales (\n id INT PRIMARY KEY,\n date DATE,\n department VARCHAR(50),\n sales_amount DECIMAL(10, 2)\n);\n\n-- Dept A Data: 10, 20, 30, 40\nINSERT INTO daily_sales VALUES (1, '2023-01-01', 'Electronics', 10.00);\nINSERT INTO daily_sales VALUES (2, '2023-01-02', 'Electronics', 20.00);\nINSERT INTO daily_sales VALUES (3, '2023-01-03', 'Electronics', 30.00);\nINSERT INTO daily_sales VALUES (4, '2023-01-04', 'Electronics', 40.00);\n\n-- Dept B Data: 100 (Should not mix with Dept A)\nINSERT INTO daily_sales VALUES (5, '2023-01-01', 'Furniture', 100.00);", "unit_test_assertion":" @Test\n public void testMovingAverage(Connection conn) throws SQLException {\n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {\n assertTrue(rs.next());\n assertEquals(10.0, rs.getDouble(\"moving_avg_3_day\"), 0.01);\n\n assertTrue(rs.next());\n assertEquals(15.0, rs.getDouble(\"moving_avg_3_day\"), 0.01);\n\n assertTrue(rs.next());\n assertEquals(20.0, rs.getDouble(\"moving_avg_3_day\"), 0.01);\n\n assertTrue(rs.next());\n assertEquals(30.0, rs.getDouble(\"moving_avg_3_day\"), 0.01, \"Window sliding logic failed\");\n \n assertTrue(rs.next());\n assertEquals(\"Furniture\", rs.getString(\"department\"));\n assertEquals(100.0, rs.getDouble(\"moving_avg_3_day\"), 0.01, \"Partition logic failed\");\n }\n }", "comment":"the solution MUST use window functions to calculate the moving average partitioned by department and ordered by date, ensuring correct 3-day averaging conventions (current day + 2 previous days)." } {"id":"base_sql_04","dataset_type":"base","language":"SQL","dialect":"postgresql","task_category":"id_bug", "prompt_en":"I want to get a list of all the students, and if they got an 8 or above I want their score because I want to give them a distinction award. This query uses a left join but it only returns the student who deserve a distinction award. fix the query.", "prompt_nl":"Ik wil een lijst van alle studenten krijgen, en als ze een 8 of hoger hebben gehaald, wil ik hun score weten, omdat ik ze een onderscheiding wil geven. Deze query maakt gebruik van een left join, maar geeft alleen de studenten weer die een onderscheiding verdienen. Corrigeer de query.", "code_snippet_input":"SELECT \ns.student_name,\ng.score AS distinction_grade\nFROM students s\nLEFT JOIN exam_results g ON s.id = g.student_id\nWHERE g.score >= 8;", "canonical_solution":"SELECT \ns.student_name,\ng.score AS distinction_grade\nFROM students s\nLEFT JOIN exam_results g \nON s.id = g.student_id \nAND g.score >= 8; -- Logic happens BEFORE the join", "unit_test_setup":"CREATE TABLE students (id INT PRIMARY KEY, student_name VARCHAR(50));\nCREATE TABLE exam_results (student_id INT, score INT);\n\nINSERT INTO students VALUES (1, 'Alice');\nINSERT INTO exam_results VALUES (1, 9);\n\nINSERT INTO students VALUES (2, 'Bob');\nINSERT INTO exam_results VALUES (2, 6);\n\nINSERT INTO students VALUES (3, 'Charlie');", "unit_test_assertion":" @Test\n public void testLeftJoinLogic(Connection conn) throws SQLException {\n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {\n \n int rowCount = 0;\n while(rs.next()) {\n rowCount++;\n String name = rs.getString(\"student_name\");\n int score = rs.getInt(\"distinction_grade\");\n boolean isNull = rs.wasNull(); \n if (name.equals(\"Alice\")) {\n assertEquals(9, score, \"Alice should have a score of 9\");\n } else if (name.equals(\"Bob\")) {\n assertTrue(isNull, \"Bob should have NULL score (filtered out by ON clause)\");\n } else if (name.equals(\"Charlie\")) {\n assertTrue(isNull, \"Charlie should have NULL score (no exam)\");\n }\n }\n assertEquals(3, rowCount, \"Should return ALL 3 students, not just the high scorers\");\n }\n }", "comment":"the solution MUST show all students regardless of score, so the filtering for scores >= 8 MUST be in the ON clause of the LEFT JOIN, not in the WHERE clause which filters after the join." } {"id":"base_sql_05","dataset_type":"base","language":"SQL","dialect":"postgresql","task_category":"id_bug", "prompt_en":"This query should return all customers who haven't placed any orders, but it returns an empty set when it shouldn't. Fix the query.", "prompt_nl":"Deze query zou alle klanten moeten teruggeven die nog geen bestellingen hebben geplaatst, maar geeft een lege set terug terwijl dat niet zou moeten. Corrigeer de query.", "code_snippet_input":"SELECT customer_name \nFROM customers \nWHERE id NOT IN (\nSELECT customer_id \nFROM orders\n);", "canonical_solution":"SELECT c.customer_name \nFROM customers c\nWHERE NOT EXISTS (\nSELECT 1 \nFROM orders o\nWHERE o.customer_id = c.id\n);", "unit_test_setup":"CREATE TABLE customers (id INT PRIMARY KEY, customer_name VARCHAR(50));\nCREATE TABLE orders (id INT PRIMARY KEY, customer_id INT);\n\nINSERT INTO customers VALUES (1, 'Alice');\nINSERT INTO orders VALUES (101, 1);\n \nINSERT INTO customers VALUES (2, 'Bob');\n\n\nINSERT INTO orders VALUES (102, NULL);", "unit_test_assertion":"@Test\n public void testNullTrap(Connection conn) throws SQLException {\n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {\n\n\n assertTrue(rs.next(), \"The query returned no results. Did you handle the NULLs in the subquery?\");\n \n assertEquals(\"Bob\", rs.getString(\"customer_name\"), \"Should return Bob (who has no orders)\");\n assertFalse(rs.next(), \"Should only return customers with no orders\");\n }\n }", "comment":"The solution MUST return one customer. It should identify the bug as being a NOT IN with NULL values, and fix it via NOT EXISTS or WHERE NOT NULL." } {"id":"base_sql_06","dataset_type":"base","language":"SQL","dialect":"postgresql","task_category":"id_bug", "prompt_en":"This query should return the probability of a disease ocurring in each region but returns zero for all regions, when thats not the case. Fix the query.", "prompt_nl":"Deze query zou de kans op het voorkomen van een ziekte in elke regio moeten weergeven, maar geeft voor alle regio's nul weer, terwijl dat niet het geval is. Corrigeer de query.", "code_snippet_input":"SELECT\nregion_name,\npositive_cases,\ntotal_population,\n(positive_cases / total_population) AS disease_probability\nFROM population_studies;", "canonical_solution":"SELECT \nregion_name,\n(positive_cases * 1.0 / total_population) AS disease_probability\nFROM population_studies;", "unit_test_setup":"CREATE TABLE population_studies (\n region_name VARCHAR(50),\n positive_cases INT,\n total_population INT\n);\n\n\nINSERT INTO population_studies VALUES ('Region A', 50, 100);", "unit_test_assertion":" @Test\n public void testIntegerDivision(Connection conn) throws SQLException {\n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {\n \n assertTrue(rs.next());\n \n double probability = rs.getDouble(\"disease_probability\");\n \n assertTrue(probability > 0, \"Result was 0. Did you fix the integer division problem?\");\n assertEquals(0.5, probability, 0.001, \"Calculation should be correct (50/100 = 0.5)\");\n }\n }", "comment":"In Postgres (not necessarily other dialects), dividing INT by INT truncates to the nearest integer (0). The solution MUST cast one operand to a float either explicitly or by * 1.0 to get a decimal result above 0." } {"id":"base_sql_07","dataset_type":"base","language":"SQL","dialect":"mssql","task_category":"id_bug", "prompt_en":"I want to collect all of the 2023 transactions for the annual report but this query returns 4 additional transactions from 2024. Fix the query.", "prompt_nl":"Ik wil alle transacties van 2023 verzamelen voor het jaarverslag, maar deze query geeft 4 extra transacties uit 2024 weer. Corrigeer de query.", "code_snippet_input":"DECLARE @Start DATETIME = '2023-1-1 00:00:00.000';\nDECLARE @End DATETIME = '2023-12-31 23:59:59.999';\nSELECT *\nFROM transactions\nWHERE transaction_date BETWEEN @Start AND @End;", "canonical_solution":"SELECT *\nFROM transactions\nWHERE transaction_date >= '2023-1-1 00:00:00'\nAND transaction_date < '2024-1-1 00:00:00';", "unit_test_setup":"CREATE TABLE transactions (id INT, transaction_date DATETIME);\n\nINSERT INTO transactions VALUES (1, '2023-06-15 12:00:00');\n\n\nINSERT INTO transactions VALUES (2, '2023-12-31 23:59:59.990');\n\nINSERT INTO transactions VALUES (3, '2024-01-01 00:00:00.000');", "unit_test_assertion":" @Test\n public void testDateRounding(Connection conn) throws SQLException {\n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {\n \n int count = 0;\n while(rs.next()) {\n count++;\n Timestamp ts = rs.getTimestamp(\"transaction_date\");\n // Assert we did NOT pick up the 2024 date\n assertFalse(ts.toLocalDateTime().getYear() == 2024, \"Query incorrectly included a 2024 transaction due to rounding.\");\n }\n assertEquals(2, count, \"Should return exactly 2 rows from 2023.\");\n }\n }", "comment":"The solution MUST use a half-open interval (< '2024-1-1') to safely capture all 2023 data without hitting MSSQL's 3ms rounding issue on .999 milliseconds." } {"id":"base_sql_08","dataset_type":"base","language":"SQL","dialect":"mssql","task_category":"fix_bug", "prompt_en":"I want a query to get the logging time and ip address of the last time each user logged in to my website, but i get an error. Fix this query.", "prompt_nl":"Ik wil een query om de inlogtijd en het IP adres te achterhalen van de laatste keer dat elke gebruiker zich op mijn website heeft aangemeld, maar ik krijg een foutmelding. Los deze query op.", "code_snippet_input":"--Column 'user_logins.ip_address' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.\nSELECT \nuser_id, \nMAX(login_time) as last_seen,\nip_address\nFROM user_logins\nGROUP BY user_id;", "canonical_solution":"SELECT \noriginal.user_id, \noriginal.login_time as last_seen,\noriginal.ip_address\nFROM user_logins original\nINNER JOIN (\nSELECT user_id, MAX(login_time) as max_time\nFROM user_logins\nGROUP BY user_id\n) filtered\nON original.user_id = filtered.user_id \nAND original.login_time = filtered.max_time;", "unit_test_setup":"CREATE TABLE user_logins (\n user_id INT,\n login_time DATETIME,\n ip_address VARCHAR(50)\n);\n\nINSERT INTO user_logins VALUES (1, '2023-01-01 10:00:00', '1.1.1.1');\nINSERT INTO user_logins VALUES (1, '2023-01-02 10:00:00', '2.2.2.2');\n\nINSERT INTO user_logins VALUES (2, '2023-01-05 10:00:00', '3.3.3.3');", "unit_test_assertion":" @Test\n public void testGroupByLogic(Connection conn) throws SQLException {\n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {\n boolean foundUser1 = false;\n while(rs.next()) {\n if(rs.getInt(\"user_id\") == 1) {\n foundUser1 = true;\n assertEquals(\"2.2.2.2\", rs.getString(\"ip_address\"), \"Should return the IP of the LATEST login, not a random one.\");\n }\n }\n assertTrue(foundUser1, \"User 1 should be in the results.\");\n }\n }", "comment":"The solution MUST resolve the aggregation error and return latest login ip for each user, either by joining the table to a subquery on itself (Self-Join), or using Window Functions (ROW_NUMBER)." } {"id":"base_sql_09","dataset_type":"base","language":"SQL","dialect":"mysql","task_category":"fix_bug", "prompt_en":"I want this query to return all of the patients that have visited the radiology department more than 10 times, but I get an error. Fix the query.", "prompt_nl":"Ik wil dat deze query alle patiënten weergeeft die meer dan 10 keer de afdeling radiologie hebben bezocht, maar ik krijg een foutmelding. Corrigeer de query.", "code_snippet_input":"--ERROR 1111 (HY000): Invalid use of group function\nSELECT \np.patient_name, \nCOUNT(r.log_id) as visit_count\nFROM patients p\nJOIN radiology_log r \nON p.patient_id = r.patient_id\nWHERE COUNT(r.log_id) > 10\nGROUP BY p.patient_name;", "canonical_solution":"SELECT \np.patient_name, \nCOUNT(r.log_id) as visit_count\nFROM patients p\nJOIN radiology_log r \nON p.patient_id = r.patient_id\nGROUP BY p.patient_name\nHAVING COUNT(r.log_id) > 10; -- <--- Correct", "unit_test_setup":"CREATE TABLE patients (patient_id INT, patient_name VARCHAR(50));\nCREATE TABLE radiology_log (log_id INT AUTO_INCREMENT, patient_id INT, PRIMARY KEY(log_id));\n\nINSERT INTO patients VALUES (1, 'Alice');\nINSERT INTO radiology_log (patient_id) VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1);\n\nINSERT INTO patients VALUES (2, 'Bob');\nINSERT INTO radiology_log (patient_id) VALUES (2);", "unit_test_assertion":" @Test\n public void testHavingClause(Connection conn) throws SQLException {\n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {\n \n assertTrue(rs.next(), \"Should return at least one patient with > 10 visits\");\n assertEquals(\"Alice\", rs.getString(\"patient_name\"));\n assertEquals(11, rs.getInt(\"visit_count\"));\n assertFalse(rs.next(), \"Should filter out patients with <= 10 visits\");\n }\n }", "comment":"The solution MUST replace the WHERE clause with HAVING for filtering aggregate fields." } {"id":"base_sql_10","dataset_type":"base","language":"SQL","dialect":"mysql","task_category":"fix_bug", "prompt_en":"I want a query that returns all of the patients in the system and the date they were admitted to the hospital, but I get an error. Fix the query.", "prompt_nl":"Ik wil een query die alle patiënten in het systeem en de datum waarop ze in het ziekenhuis zijn opgenomen weergeeft, maar ik krijg een foutmelding. Los de query op.", "code_snippet_input":"--Error Code: 1052. Column 'patient_id' in field list is ambiguous\nSELECT \npatient_id,\nname,\nadmission_date\nFROM patients p\nJOIN admissions a \nON p.patient_id = a.patient_id;", "canonical_solution":"SELECT \np.patient_id,\nname,\nadmission_date\nFROM patients p\nJOIN admissions a \nON p.patient_id = a.patient_id;", "unit_test_setup":"CREATE TABLE patients (patient_id INT, name VARCHAR(50));\nCREATE TABLE admissions (admission_id INT, patient_id INT, admission_date DATE);\n\nINSERT INTO patients VALUES (1, 'John Doe');\nINSERT INTO admissions VALUES (100, 1, '2023-01-01');", "unit_test_assertion":" @Test\n public void testAmbiguousColumn(Connection conn) throws SQLException {\n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {\n \n assertTrue(rs.next(), \"Query should return results once the ambiguity is fixed.\");\n assertEquals(1, rs.getInt(\"patient_id\"));\n assertEquals(\"John Doe\", rs.getString(\"name\"));\n assertNotNull(rs.getDate(\"admission_date\"));\n }\n }", "comment":"The solution MUST solve the ambiguity in 'patient_id' column with a table alias, either p.patient_id or a.patient_id (doesn't matter because they're identical, hence the JOIN)." } {"id":"base_sql_11","dataset_type":"base","language":"SQL","dialect":"mssql","task_category":"fix_bug", "prompt_en":"I want to retrieve all patients who have lab results greater than 100, but I get a conversion error because some results are not numeric even though I'm filtering them out. FIx the error.", "prompt_nl":"Ik wil alle patiënten ophalen met laboratoriumresultaten hoger dan 100, maar ik krijg een conversiefout omdat sommige resultaten niet numeriek zijn, ook al filter ik ze eruit. Los de fout op.", "code_snippet_input":"--Conversion failed when converting the varchar value 'Pending' to data type int\nSELECT \npatient_id, \nresult_value\nFROM lab_results\nWHERE result_value NOT LIKE '%[^0-9]%'\nAND CAST(result_value AS INT) > 100;", "canonical_solution":"SELECT \npatient_id, \nresult_value\nFROM lab_results\nWHERE TRY_CAST(result_value AS INT) > 100;", "unit_test_setup":"CREATE TABLE lab_results (patient_id INT, result_value VARCHAR(50));\n\nINSERT INTO lab_results VALUES (1, '150');\n\nINSERT INTO lab_results VALUES (2, '50');\n\nINSERT INTO lab_results VALUES (3, 'Pending');", "unit_test_assertion":" @Test\n public void testSafeCast(Connection conn) throws SQLException {\n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {\n \n assertTrue(rs.next(), \"Should return the valid numeric row > 100\");\n assertEquals(\"150\", rs.getString(\"result_value\"));\n \n assertFalse(rs.next(), \"Should filter out low numbers and non-numeric strings without crashing.\");\n }\n }", "comment":"The solution MUST use TRY_CAST (or similar) to attemp conversion safely, otherwise the conversion will raise an error because SQL is not procedural so order of operations can't be controlled" } {"id":"base_sql_12","dataset_type":"base","language":"SQL","task_category":"refactoring", "prompt_en":"This query retrieves the names, the total spend and the date of the most recent order of out top buyers (spent more than 1000$ total). Refactor this query to make it more efficient and readable without changing functionality.", "prompt_nl":"Deze query haalt de namen, het totale bedrag en de datum van de meest recente bestelling van onze topkopers (die in totaal meer dan 1000$ hebben uitgegeven) op. Herstructureer deze query om hem efficiënter en leesbaarder te maken zonder de functionaliteit te wijzigen.", "code_snippet_input":"SELECT \nc.customer_name,\n(SELECT SUM(amount) FROM orders o WHERE o.customer_id = c.id) as total_spend,\n(SELECT MAX(order_date) FROM orders o WHERE o.customer_id = c.id) as last_order_date\nFROM customers c\nWHERE (SELECT SUM(amount) FROM orders o WHERE o.customer_id = c.id) > 1000;", "canonical_solution":"WITH CustomerStats AS (\nSELECT \ncustomer_id,\nSUM(amount) as total_spend,\nMAX(order_date) as last_order_date\nFROM orders\nGROUP BY customer_id\n),\nHighValueCustomers AS (\nSELECT \ncustomer_id,\ntotal_spend,\nlast_order_date\nFROM CustomerStats\nWHERE total_spend > 1000\n)\nSELECT \nc.customer_name,\nhvc.total_spend,\nhvc.last_order_date\nFROM customers c\nINNER JOIN HighValueCustomers hvc \nON c.id = hvc.customer_id;", "unit_test_setup":"CREATE TABLE customers (id INT PRIMARY KEY, customer_name VARCHAR(50));\nCREATE TABLE orders (id INT PRIMARY KEY, customer_id INT, amount INT, order_date DATE);\n\nINSERT INTO customers VALUES (1, 'Alice');\nINSERT INTO orders VALUES (101, 1, 600, '2023-01-01');\nINSERT INTO orders VALUES (102, 1, 500, '2023-01-05');\n\nINSERT INTO customers VALUES (2, 'Bob');\nINSERT INTO orders VALUES (201, 2, 900, '2023-02-01');\n\n-- 3. Edge Case (Charlie): 1000 total (Should be filtered out)\nINSERT INTO customers VALUES (3, 'Charlie');\nINSERT INTO orders VALUES (301, 3, 1000, '2023-03-01');", "unit_test_assertion":" @Test\n public void testRefactoring(Connection conn) throws SQLException {\n String sql = generatedSqlQuery.toUpperCase().replaceAll(\"\\\\s+\", \" \");\n \n boolean usesCTE = sql.contains(\"WITH \");\n boolean usesJoin = sql.contains(\"JOIN \");\n \n assertTrue(usesCTE || usesJoin, \"Refactoring failed: You must optimize the query using a CTE (WITH) or JOINs instead of correlated subqueries.\");\n\n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {\n \n assertTrue(rs.next(), \"Should return high value customers.\");\n assertEquals(\"Alice\", rs.getString(\"customer_name\"));\n assertEquals(1100, rs.getInt(\"total_spend\"));\n assertEquals(Date.valueOf(\"2023-01-05\"), rs.getDate(\"last_order_date\"));\n \n assertFalse(rs.next(), \"Should strictly filter > 1000 (Bob and Charlie should not appear).\");\n }\n }", "comment":"the solution MUST separate the big query with redundant subqueries into multiple queries with sepration of concerns (i.e. one for the math, one for the filtering, and one for the display), this makes the code mre efficient (less redundancy), more readable, and more maintainable (easier to debug). The unit test includes structural checks (as well as functional checks) to ensure refactoring." } {"id":"base_sql_13","dataset_type":"base","language":"SQL","dialect":"postgresql","task_category":"refactoring", "prompt_en":"Refactor this code use a CTE, keep the same functionality.", "prompt_nl":"Herstructureer deze code met behulp van een CTE, behoud dezelfde functionaliteit.", "code_snippet_input":"SELECT \npatient_name,\nweight_kg,\nheight_m,\nCASE \nWHEN (weight_kg / (height_m * height_m)) < 18.5 THEN 'Underweight'\nWHEN (weight_kg / (height_m * height_m)) >= 18.5 AND (weight_kg / (height_m * height_m)) < 25 THEN 'Healthy'\nWHEN (weight_kg / (height_m * height_m)) >= 25 AND (weight_kg / (height_m * height_m)) < 30 THEN 'Overweight'\nWHEN (weight_kg / (height_m * height_m)) >= 30 THEN 'Obese'\nEND as bmi_category\nFROM patients;", "canonical_solution":"WITH PatientBMI AS (\nSELECT \npatient_name,\n(weight_kg / (height_m * height_m)) as bmi_score\nFROM patients\n)\nSELECT \npatient_name,\nbmi_score,\nCASE \nWHEN bmi_score < 18.5 THEN 'Underweight'\nWHEN bmi_score < 25 THEN 'Healthy' -- Implicitly means \">= 18.5 AND < 25\"\nWHEN bmi_score < 30 THEN 'Overweight' -- Implicitly means \">= 25 AND < 30\"\nELSE 'Obese'\nEND as bmi_category\nFROM PatientBMI;", "unit_test_setup":"CREATE TABLE patients (\n patient_name VARCHAR(50),\n weight_kg DECIMAL(10, 2),\n height_m DECIMAL(10, 2)\n);\n\nINSERT INTO patients VALUES ('Alice', 50.0, 1.80);\n\nINSERT INTO patients VALUES ('Bob', 70.0, 1.75);\n\nINSERT INTO patients VALUES ('Charlie', 85.0, 1.75);\n\nINSERT INTO patients VALUES ('Diana', 100.0, 1.70);", "unit_test_assertion":" @Test\n public void testBMIRefactoring(Connection conn) throws SQLException {\n String sql = generatedSqlQuery.toUpperCase();\n assertTrue(sql.contains(\"WITH \"), \"Refactoring failed: You must use a Common Table Expression (WITH clause).\");\n\n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {\n \n int count = 0;\n while(rs.next()) {\n count++;\n String name = rs.getString(\"patient_name\");\n String category = rs.getString(\"bmi_category\");\n \n if (name.equals(\"Alice\")) assertEquals(\"Underweight\", category);\n else if (name.equals(\"Bob\")) assertEquals(\"Healthy\", category);\n else if (name.equals(\"Charlie\")) assertEquals(\"Overweight\", category);\n else if (name.equals(\"Diana\")) assertEquals(\"Obese\", category);\n }\n assertEquals(4, count, \"Should return all 4 patients\");\n }\n }", "comment":"the solution MUST use a CTE to calculate BMI just once, then reference that in the main query to assign a category. The unit test includes structural checks (as well as functional checks) to ensure refactoring and specific use of CTE as the prompt requires. The unit test includes structural checks (as well as functional checks) to ensure refactoring." } {"id":"base_sql_14","dataset_type":"base","language":"SQL","dialect":"postgresql","task_category":"refactoring", "prompt_en":"These are two queries that have similar calculations, one returns the gpa of all students, the other returns the gpa of cum laude students. Make a view called student_gpa_view to refactor this code to reduce redundancy.", "prompt_nl":"Dit zijn twee query's met vergelijkbare berekeningen: de ene retourneert het gemiddelde cijfer van alle studenten, de andere retourneert het gemiddelde cijfer van cum laude-studenten. Maak een weergave met de naam student_gpa_view om deze code te herstructureren en redundantie te verminderen.", "code_snippet_input":"SELECT \ns.student_name,\nSUM(g.score * c.credits) * 1.0 / SUM(c.credits) as gpa\nFROM students s\nJOIN grades g ON s.id = g.student_id\nJOIN courses c ON g.course_id = c.id\nWHERE s.id = 101\nGROUP BY s.student_name;\n\n SELECT \ns.student_name,\nSUM(g.score * c.credits) * 1.0 / SUM(c.credits) as gpa\nFROM students s\nJOIN grades g ON s.id = g.student_id\nJOIN courses c ON g.course_id = c.id\nGROUP BY s.student_name\nHAVING SUM(g.score * c.credits) * 1.0 / SUM(c.credits) > 8.0;", "canonical_solution":"CREATE VIEW student_gpa_view AS\nSELECT \ns.id as student_id,\ns.student_name,\nCOUNT(g.course_id) as total_classes,\nCAST(SUM(g.score * c.credits) * 1.0 / SUM(c.credits) AS DECIMAL(10,2)) as gpa\nFROM students s\nJOIN grades g ON s.id = g.student_id\nJOIN courses c ON g.course_id = c.id\nGROUP BY s.id, s.student_name;", "unit_test_setup":"CREATE TABLE students (id INT PRIMARY KEY, student_name VARCHAR(50));\nCREATE TABLE courses (id INT PRIMARY KEY, credits INT);\nCREATE TABLE grades (student_id INT, course_id INT, score INT);\n\nINSERT INTO students VALUES (1, 'Felipe');\nINSERT INTO courses VALUES (101, 5), (102, 5);\nINSERT INTO grades VALUES (1, 101, 9), (1, 102, 8);\n\nINSERT INTO students VALUES (2, 'Bob');\nINSERT INTO grades VALUES (2, 101, 6), (2, 102, 7);", "unit_test_assertion":" @Test\n public void testViewCreation(Connection conn) throws SQLException {\n try (Statement stmt = conn.createStatement()) {\n stmt.execute(generatedSqlQuery);\n }\n\n String verifySql = \"SELECT student_name, gpa FROM student_gpa_view ORDER BY student_name DESC\";\n \n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(verifySql)) {\n \n assertTrue(rs.next(), \"The view should return rows.\");\n assertEquals(\"Felipe\", rs.getString(\"student_name\"));\n assertEquals(8.5, rs.getDouble(\"gpa\"), 0.01, \"Felipe's GPA should be 8.5\");\n \n assertTrue(rs.next());\n assertEquals(\"Bob\", rs.getString(\"student_name\"));\n assertEquals(6.5, rs.getDouble(\"gpa\"), 0.01, \"Bob's GPA should be 6.5\");\n }\n }", "comment":"the solution MUST create a view called student_gpa_view that encapsulates the GPA calculation logic, so that both original queries can be simplified to select from this view with appropriate filtering (by student_id for the first, and by gpa for the second). This reduces redundancy and improves maintainability. The unit test includes structural checks (as well as functional checks) to ensure refactoring." } {"id":"base_sql_15","dataset_type":"base","language":"SQL","dialect":"postgresql","task_category":"refactoring", "prompt_en":"This query retrieves the name, last order date and last product ordered for all customers, but it has repeated subqueries. Refactor the query using a lateral join to make it more efficient and readable without changing functionality.", "prompt_nl":"Deze query haalt de naam, laatste besteldatum en laatst bestelde producten voor alle klanten op, maar bevat herhaalde subquery's. Herstructureer de query met behulp van een lateral join om deze efficiënter en leesbaarder te maken zonder de functionaliteit te wijzigen.", "code_snippet_input":"SELECT \nc.name,\n(SELECT order_date FROM orders o WHERE o.customer_id = c.id ORDER BY order_date DESC LIMIT 1) as order_date,\n(SELECT product_name FROM orders o WHERE o.customer_id = c.id ORDER BY order_date DESC LIMIT 1) as product_name,\n(SELECT amount FROM orders o WHERE o.customer_id = c.id ORDER BY order_date DESC LIMIT 1) as amount\nFROM customers c;", "canonical_solution":"SELECT \nc.name,\nlast_o.order_date,\nlast_o.product_name,\nlast_o.amount\nFROM customers c\nLEFT JOIN LATERAL (\nSELECT order_date, product_name, amount\nFROM orders o\nWHERE o.customer_id = c.id\nORDER BY order_date DESC\nLIMIT 1\n) last_o ON TRUE;", "unit_test_setup":"CREATE TABLE customers (id INT PRIMARY KEY, name VARCHAR(50));\nCREATE TABLE orders (id INT, customer_id INT, product_name VARCHAR(50), amount INT, order_date DATE);\n\nINSERT INTO customers VALUES (1, 'Alice');\nINSERT INTO orders VALUES (101, 1, 'Phone', 500, '2023-01-01');\nINSERT INTO orders VALUES (102, 1, 'Laptop', 1000, '2023-01-02');\nINSERT INTO orders VALUES (103, 1, 'Tablet', 300, '2023-01-03');\n\nINSERT INTO customers VALUES (2, 'Bob');", "unit_test_assertion":" @Test\n public void testLateralJoin(Connection conn) throws SQLException {\n String sql = generatedSqlQuery.toUpperCase();\n assertTrue(sql.contains(\"LATERAL\"), \"Refactoring failed: The model ignored the instruction to use LATERAL JOIN.\");\n\n try (Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {\n \n assertTrue(rs.next());\n assertEquals(\"Alice\", rs.getString(\"name\"));\n assertEquals(\"Tablet\", rs.getString(\"product_name\"));\n \n assertTrue(rs.next());\n assertEquals(\"Bob\", rs.getString(\"name\"));\n assertNull(rs.getString(\"product_name\"), \"Bob was filtered out or data is wrong. Did you use LEFT JOIN LATERAL?\");\n }\n }", "comment":"the solution MUST use a LATERAL JOIN to fetch the last order details in a single subquery per customer. The unit test includes structural checks (as well as functional checks) to ensure refactoring." }