{"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", "unit_test_assertion":"\n @Test\n public void testDirectoryCreation(@TempDir Path tempDir) throws IOException {\n createScaffold(tempDir.toString());\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 }", "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.", "prompt_nl":"maak een staff klasse met constructor, setters en getters met ten minste name, birthdate, gender, position, salary, hire date en department.", "code_snippet_input":"", "canonical_solution":"import java.math.BigDecimal;\nimport java.time.LocalDate;\n\npublic class Staff {\n private String name;\n private LocalDate birthDate;\n private String gender;\n private String position;\n private BigDecimal salary;\n private LocalDate hireDate;\n private String department;\n\n public Staff(String name, LocalDate birthDate, String gender, String position, BigDecimal salary, 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 public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public LocalDate getBirthDate() {\n return birthDate;\n }\n\n public void setBirthDate(LocalDate birthDate) {\n this.birthDate = birthDate;\n }\n\n public String getGender() {\n return gender;\n }\n\n public void setGender(String gender) {\n this.gender = gender;\n }\n\n public String getPosition() {\n return position;\n }\n\n public void setPosition(String position) {\n this.position = position;\n }\n\n public BigDecimal getSalary() {\n return salary;\n }\n\n public void setSalary(BigDecimal salary) {\n this.salary = salary;\n }\n\n public LocalDate getHireDate() {\n return hireDate;\n }\n\n public void setHireDate(LocalDate hireDate) {\n this.hireDate = hireDate;\n }\n\n public String getDepartment() {\n return department;\n }\n\n public void setDepartment(String department) {\n this.department = department;\n }\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.*;\n\n", "unit_test_assertion":"class 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(\n \"Alice Johnson\", \n birthDate, \n \"Female\", \n \"Data Scientist\", \n new java.math.BigDecimal(\"75000.00\"), \n hireDate, \n \"R&D\"\n );\n }\n @Test\n void testConstructorAndGetters() {\n assertEquals(\"Alice Johnson\", staff.getName());\n }\n @Test\n void testSalaryIsBigDecimal() {\n assertNotNull(staff.getSalary());\n assertTrue(staff.getSalary() instanceof java.math.BigDecimal);\n assertEquals(new java.math.BigDecimal(\"75000.00\"), staff.getSalary());\n }\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). MUST use big decimal for salary to avoid floating point arithmetic mistakes. solution must be parsed to remove imports." } {"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.", "prompt_nl":"waarom krijg ik een compilatie error in deze code? Los het op.", "code_snippet_input":"/*Local variable counter defined in an enclosing scope must be final or effectively final*/ \npublic static List generateResults() {\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});\nreturn results;\n}", "canonical_solution":"import java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\n\npublic static List generateResults() {\nList 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});\nreturn results;\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\n", "unit_test_assertion":"\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}", "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", "prompt_nl":"waarom krijg ik een compilatie error in deze code? Los het op.", "code_snippet_input":"/*name clash: method(List) has the same erasure as method(List)*/\npublic String sort(List data) {\n return \"Sorting strings\";\n}\n\npublic String sort(List data) {\n return \"Sorting integers\";\n}", "canonical_solution":"public String sortStrings(List data) {\n return \"Sorting strings\";\n }\n\n public String sortIntegers(List data) {\n return \"Sorting integers\";\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", "unit_test_assertion":"\n @Test\n public void testMethodsAreDistinct() {\n Solution sol = new Solution();\n String result1 = sol.sortStrings(new ArrayList());\n String result2 = sol.sortIntegers(new ArrayList());\n\n assertEquals(\"Sorting strings\", result1);\n assertEquals(\"Sorting integers\", result2);\n }", "comment":"Java type erasure means List and List both become List at runtime, preventing overloading. The solution must rename the methods. Note: Added instantiation of Solution in test assertion to ensure it runs regardless of static/instance context." } {"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*/\nclass OfficeMachine implements Printer, Scanner {\n}", "canonical_solution":"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":"@Test\npublic void testConflictResolution() {\n OfficeMachine machine = new OfficeMachine();\n assertEquals(\"Printing document...\", machine.process(), \"Should return Printer's output\");\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.", "prompt_nl":"Waarom krijg ik verkeerde resultaten in deze code? De methode retourneert geen lijst met transacties in de doelvaluta. Corrigeer de methode.", "code_snippet_input":"class DataFilter {\n public List filterByCurrency(List data, String targetCurrency) {\n List result = new ArrayList<>();\n for (Transaction t : data) {\n if (t.getCurrency() == targetCurrency) {\n result.add(t);\n }\n }\n return result;\n }\n}", "canonical_solution":"class DataFilter {\n public List filterByCurrency(List data, String targetCurrency) {\n List result = new ArrayList<>();\n for (Transaction t : data) {\n if (targetCurrency.equals(t.getCurrency())) {\n result.add(t);\n }\n }\n return 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}", "unit_test_assertion":"class 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.", "prompt_nl":"Waarom leest deze methode de csv-gegevens niet correct? Repareer de methode.", "code_snippet_input":"/* CSV 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.*;", "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 }", "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.", "prompt_nl":"Ik wil deze methode gebruiken om een vierkante matrix te transponeren, maar het geeft verkeerde resultaten. Corrigeer de methode.", "code_snippet_input":"public static int[][] transposeMatrix(int[][] input) {\n int rows = input.length;\n int cols = input[0].length;\n int[][] output = new int[cols][rows];\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n output[i][j] = input[i][j];\n }\n }\n return output;\n}", "canonical_solution":"public static int[][] transposeMatrix(int[][] input) {\n int rows = input.length;\n int cols = input[0].length;\n int[][] output = new int[cols][rows];\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n output[j][i] = input[i][j];\n }\n }\n return output;\n}", "unit_test_setup":"import org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.*;\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 }", "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 static singleton DatabaseConnection class in java with a getInstance method.", "prompt_nl":"Maak een statische singleton DatabaseConnection klasse in java met een getInstance methode.", "code_snippet_input":"", "canonical_solution": "public static class DatabaseConnection {\n private static volatile DatabaseConnection instance;\n private DatabaseConnection() {}\n public static DatabaseConnection getInstance() {\n if (instance == null) {\n synchronized (DatabaseConnection.class) {\n if (instance == null) {\n instance = new DatabaseConnection();\n }\n }\n }\n return instance;\n }\n}", "unit_test_setup": "import org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.lang.reflect.*;", "unit_test_assertion": "@Test\n public void testSingletonUniqueInstance() throws InterruptedException {\n DatabaseConnection[] instances = new DatabaseConnection[2];\n Thread t1 = new Thread(() -> instances[0] = DatabaseConnection.getInstance());\n Thread t2 = new Thread(() -> instances[1] = DatabaseConnection.getInstance());\n t1.start();\n t2.start();\n t1.join();\n t2.join();\n assertNotNull(instances[0]);\n assertSame(instances[0], instances[1], \"Both threads must receive the exact same instance\");\n }\n\n @Test\n public void testConstructorIsPrivate() throws Exception {\n Constructor constructor = DatabaseConnection.class.getDeclaredConstructor();\n assertTrue(Modifier.isPrivate(constructor.getModifiers()), \"Constructor must be private\");\n }", "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\n", "unit_test_assertion":"@Test\n public void testYesterdayIsOverdue() {\n assertTrue(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() {\n assertTrue(isOverdue(LocalDate.now()), \"Today (current time) should be considered after Today (start of day)\");\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", "prompt_nl":"deze methode groepeert transacties van meer dan 1000 per valuta. Refactor deze om streams te gebruiken.", "code_snippet_input":"public Map> groupHighValueTransactions(List transactions) {\n Map> result = new HashMap<>();\n for (Transaction t : transactions) {\n if (t.getAmount() > 1000) {\n String currency = t.getCurrency();\n if (!result.containsKey(currency)) {\n result.put(currency, new ArrayList<>());\n }\n result.get(currency).add(t);\n }\n }\n return 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", "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 String source = Files.readString(Path.of(\"Solution.java\"));\n String solutionPart = source.split(\"testGrouping\")[0];\n assertTrue(solutionPart.contains(\".stream(\"), \"LLM failed to use Stream API\");\n assertTrue(solutionPart.contains(\".collect(\"), \"LLM failed to use Collector\");\n assertFalse(solutionPart.contains(\"for (\"), \"LLM failed to remove 'for' loop\");\n }", "comment":"the unit test includes structural checks (as well as functional checks) to ensure refactoring, the solution MUST use streams and collectors to filter and group the transactions, and remove the explicit for loop and if statements." } {"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", "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.", "code_snippet_input":"public String getDiscountCode(String dayOfWeek) {\n String discount;\n switch (dayOfWeek) {\n case \"Monday\":\n discount = \"MANIC_MONDAY_15\";\n break;\n case \"Wednesday\":\n discount = \"WACKY_WED_10\";\n break;\n case \"Friday\":\n discount = \"TGIF_25\";\n break;\n case \"Saturday\":\n case \"Sunday\":\n discount = \"WEEKEND_SAVER_20\";\n break;\n default:\n discount = \"STANDARD_PRICING\";\n break;\n }\n return discount;\n}", "canonical_solution":"public String getDiscountCode(String dayOfWeek) {\n return switch (dayOfWeek) {\n case \"Monday\" -> \"MANIC_MONDAY_15\";\n case \"Wednesday\" -> \"WACKY_WED_10\";\n case \"Friday\" -> \"TGIF_25\";\n case \"Saturday\", \"Sunday\" -> \"WEEKEND_SAVER_20\";\n default -> \"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", "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 String solutionPart = source.split(\"testGrouping\")[0];\n assertTrue(solutionPart.contains(\"->\"), \"LLM failed to use modern arrow syntax '->'\");\n assertFalse(solutionPart.contains(\"break;\"), \"LLM failed to remove legacy 'break' statements\");\n }", "comment":"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":"function createReactScaffold(projectName) {\n const rootDir = path.resolve(process.cwd(), projectName);\n const dirs = [\n rootDir,\n path.join(rootDir, 'src'),\n path.join(rootDir, 'public')\n ];\n\n dirs.forEach(dir => {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n });\n const indexHtml = `\n\n\n \n \n Vite + React\n\n\n
\n \n\n`;\n const packageJson = {\n name: projectName,\n private: true,\n version: '0.0.0',\n type: 'module',\n scripts: {\n dev: 'vite',\n build: 'vite build',\n lint: 'eslint .',\n preview: 'vite preview'\n },\n dependencies: {\n react: '^18.2.0',\n 'react-dom': '^18.2.0'\n },\n devDependencies: {\n '@types/react': '^18.2.0',\n '@types/react-dom': '^18.2.0',\n '@vitejs/plugin-react': '^4.2.0',\n vite: '^5.0.0'\n }\n };\n const viteConfig = `import { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n})`;\n\n const 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)`;\n\n const appJsx = `import { useState } from 'react'\nimport './App.css'\nfunction App() {\n const [count, setCount] = useState(0)\n return (\n <>\n

Vite + React

\n
\n \n
\n \n )\n}\nexport default App`;\n\n const 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 ];\n files.forEach(file => {\n fs.writeFileSync(file.path, file.content.trim());\n });\n\n console.log(`React Vite project created at ${rootDir}`);\n}", "unit_test_setup":"const { vol } = require('memfs');\nconst fs = require('fs');\nconst path = require('path');\njest.mock('fs', () => require('memfs').fs);\n\ndescribe('createReactScaffold', () => {\n beforeEach(() => {\n vol.reset();\n });\n\n const projectName = 'test-app';", "unit_test_assertion":"test('should create the correct directory structure', () => {\n createReactScaffold(projectName);\n const rootPath = path.resolve(process.cwd(), projectName);\n expect(fs.existsSync(rootPath)).toBe(true);\n expect(fs.existsSync(path.join(rootPath, 'src'))).toBe(true);\n expect(fs.existsSync(path.join(rootPath, 'public'))).toBe(true);\n });\n\n test('should generate a valid package.json with the project name', () => {\n createReactScaffold(projectName);\n const pkgPath = path.resolve(process.cwd(), projectName, 'package.json');\n const pkgContent = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));\n expect(pkgContent.name).toBe(projectName);\n expect(pkgContent.dependencies).toHaveProperty('react');\n expect(pkgContent.scripts).toHaveProperty('dev', 'vite');\n });\n\n test('should create main.jsx with React hydration logic', () => {\n createReactScaffold(projectName);\n const mainJsxPath = path.resolve(process.cwd(), projectName, 'src', 'main.jsx');\n const content = fs.readFileSync(mainJsxPath, 'utf8');\n expect(content).toContain(\"ReactDOM.createRoot\");\n expect(content).toContain(\"\");\n });\n});", "comment":"the solution MUST physically create directories, it must use modern Vite 5 and React 18 dependencies, (additionally React.StrictMode is preferred). the unit test uses mocks to verify file and directory creation. solution should be cleaned before processing to remove any const declarations." } {"id":"base_javascript_02","dataset_type":"base","language":"JavaScript","task_category":"elem_func", "prompt_en":"Create a constructor function called createUser(name, email, password, role, joinDate, isActive) that initilizes a user object with such properties in JavScript. The constructor should also include a method called getProfile() that returns a string with the user's name and email. Return ONLY the constructor function.", "prompt_nl":"Maak een constructor function met de naam createUser(name, email, password, role, joinDate, isActive) die een user object met dergelijke eigenschappen in JavaScript initialiseert. De constructor moet ook een methode bevatten met de naam getProfile() die een tekenreeks met de naam en het e-mailadres van de gebruiker retourneert. Retourneer ALLEEN de constructor function.", "code_snippet_input":"", "canonical_solution":"function createUser(name, email, password, role, joinDate, isActive) {\n this.name = name;\n this.email = email;\n this.password = password;\n this.role = role;\n this.joinDate = joinDate;\n this.isActive = isActive;\n this.getProfile = function() {\n return `${this.name} (${this.email})`;\n };\n}", "unit_test_setup":"describe('createUser constructor', () => {\n const userData = {\n name: 'Name Surname',\n email: 'email@example.com',\n password: 'securePassword123',\n role: 'Admin',\n joinDate: '2026-01-01',\n isActive: true\n };", "unit_test_assertion":"test('initialize all user properties', () => {\n const user = new createUser(\n userData.name,\n userData.email,\n userData.password,\n userData.role,\n userData.joinDate,\n userData.isActive\n );\n expect(user.name).toBe(userData.name);\n expect(user.email).toBe(userData.email);\n expect(user.password).toBe(userData.password);\n expect(user.role).toBe(userData.role);\n expect(user.joinDate).toBe(userData.joinDate);\n expect(user.isActive).toBe(userData.isActive);\n });", "comment":"the solution MUST have a construcotor function called createUser, with the fields name, email, password, role, joinDate and isActive. it MUST also have a privileged method getProfile() inside the contructor, and this MUST return the name and email of the object." } {"id":"base_javascript_03","dataset_type":"base","language":"JavaScript","task_category":"id_bug", "prompt_en":"This function should turn all of the grades of the students that did not receive a grade into 0, but it doesn't work. Fix the bug and return ONLY the fixed function.", "prompt_nl":"Deze function zou alle cijfers van de studenten die geen cijfer hebben gekregen, moeten veranderen in 0, maar dat werkt niet. Los het bug op en stuur ALLEEN de opgeloste function terug.", "code_snippet_input":"function fixMissingGrades(students) {\n return students.map(student => {\n if (student.grade == NaN) {\n return {\n ...student,\n grade: 0\n };\n }\n return student;\n });\n}", "canonical_solution":"function fixMissingGrades(students) {\n return students.map(student => {\n if (isNaN(student.grade)) {\n return {\n ...student,\n grade: 0\n };\n }\n return student;\n });\n}", "unit_test_setup":"describe('fixMissingGrades', () => {\n const inputDataset = [\n { name: 'Alice', grade: 85 },\n { name: 'Bob', grade: NaN },\n { name: 'Charlie', grade: 0 },\n { name: 'Diana', grade: undefined }\n ];", "unit_test_assertion":"test('should replace NaN grades with 0', () => {\n const result = fixMissingGrades(inputDataset);\n const bob = result.find(s => s.name === 'Bob');\n expect(bob.grade).toBe(0);\n });\n\n test('should not modify existing valid grades', () => {\n const result = fixMissingGrades(inputDataset);\n const alice = result.find(s => s.name === 'Alice');\n const charlie = result.find(s => s.name === 'Charlie');\n expect(alice.grade).toBe(85);\n expect(charlie.grade).toBe(0);\n });\n\n test('should return a new array and not mutate the original', () => {\n const result = fixMissingGrades(inputDataset);\n expect(result).not.toBe(inputDataset);\n expect(result[1]).not.toBe(inputDataset[1]);\n });", "comment":"the bug is that NaN==NaN is always false in JavaScript, so the conditional statement is never statisfied. the solution MUST use isNaN(student.grade) instead, the solution MUST also correctly handle cases where the grade value is undefined, as this is also not a valid grade and should be set to 0. the solution MUST return the given function implementation with minimal changes, so for example the solution MUST create a new array instead of mutatting th eoriginal." } {"id":"base_javascript_04","dataset_type":"base","language":"JavaScript","task_category":"fix_bug", "prompt_en":"I dont know why this code throws a reference error, the variable settings is defined in the global scope. Fix the bug and return ONLY the fixed code.", "prompt_nl":"Ik weet niet waarom deze code een referentiefout geeft, de variabele settings is gedefinieerd in de globale scope. Los de bug op en stuur ALLEEN de gecorrigeerde code terug.", "code_snippet_input":"// ReferenceError: Cannot access 'settings' before initialization\nfunction initializeApp() {\n const results = {};\n results.initial = settings.theme; \n\n if (settings.version.startsWith(\"2\")) {\n const settings = { theme: \"light\" };\n results.override = settings.theme;\n }\n\n return results;\n}", "canonical_solution":"const settings = {\n theme: \"dark\",\n version: \"2.1.0\"\n};\n\nfunction initializeApp() {\n const results = {};\n results.initial = settings.theme; \n\n if (settings.version.startsWith(\"2\")) {\n const localSettings = { theme: \"light\" };\n results.override = localSettings.theme;\n }\n return results;\n}", "unit_test_setup":"describe('initializeApp Robust Evaluation', () => {\n global.settings = {\n theme: \"dark\",\n version: \"2.1.0\"\n };", "unit_test_assertion":"test('fixed version should produce correct theme values regardless of implementation', () => {\n const output = initializeApp();\n expect(output).toBeDefined();\n expect(output.initial).toBe(\"dark\");\n expect(output.override).toBe(\"light\");\n });", "comment":"in javascript local variables declared with const are visible in the entire scope, but not initialized until the declaration is reached, so the local settings are shadowing the global settings. the solution MUST find a way to use the global settings without causing a reference error, for example renaming the local variable to avoid the name collision, or using globalThis.settings." } {"id":"base_javascript_05","dataset_type":"base","language":"JavaScript","task_category":"fix_bug", "prompt_en":"The following code can't access the prefix variable even though it's defined in the same object. Fix the bug and return ONLY the fixed code.", "prompt_nl":"De volgende code heeft geen toegang tot de prefix variabele, ook al is deze in hetzelfde object gedefinieerd. Los de bug op en stuur ALLEEN de gecorrigeerde code terug.", "code_snippet_input":"// TypeError: Cannot read properties of undefined (reading 'prefix')\nconst logger = {\n prefix: 'LOG:',\n delayedLog(msg) {\n return new Promise((resolve) => {\n setTimeout(function() {\n resolve(`${this.prefix} ${msg}`);\n }, 10);\n });\n }\n};", "canonical_solution":"const logger = {\n prefix: 'LOG:',\n delayedLog(msg) {\n return new Promise((resolve) => {\n setTimeout(() => {\n resolve(`${this.prefix} ${msg}`);\n }, 10);\n });\n }\n};", "unit_test_setup":"describe('Logger Context Evaluation', () => {", "unit_test_assertion":"test('should correctly resolve with the prefix and message', async () => {\n const result = await logger.delayedLog('Hello');\n expect(result).toBe('LOG: Hello');\n });", "comment":"the bug is that the function passed to setTimeout has its own 'this' context, so 'this.prefix' is undefined. the solution MUST pass the 'this' context of the logger object to setTimeout, for example by using an arrow function, or by storing 'this' in a varibable and using that variable inside setTimeout" } {"id":"base_javascript_06","dataset_type":"base","language":"JavaScript","task_category":"architecture", "prompt_en":"Create a self-contained MVC module for a UserComponent in JavaScript. The module must be a single class that internally separates the user data in a state object, a template() method that returns a string of HTML, and an updateUser(newName, newAge) controller method that updates the user data and returns the new template. Return ONLY the class.", "prompt_nl":"Maak een zelfstandige MVC module voor een UserComponent in JavaScript. De module moet bestaan uit één klasse die intern de gebruikersgegevens scheidt in een state object, een template() methode die een string met HTML retourneert en een updateUser(newName, newAge) controller methode die de gebruikersgegevens bijwerkt en het nieuwe template retourneert. Retourneer ALLEEN de klasse.", "code_snippet_input":"", "canonical_solution":"class UserComponent {\n constructor(initialName, initialAge) {\n this._state = {\n name: initialName,\n age: initialAge\n };\n }\n\n template() {\n return `\n
\n

User Profile

\n

Name: ${this._state.name}

\n

Age: ${this._state.age}

\n
\n `;\n }\n\n updateUser(newName, newAge) {\n this._state.name = newName;\n this._state.age = newAge;\n return this.template();\n }\n}", "unit_test_setup":"describe('UserComponent Architecture', () => {\n const initialData = { name: 'Alice', age: 25 };\n const userComp = new UserComponent(initialData.name, initialData.age);", "unit_test_assertion":"test('Initial state should render correctly', () => {\n const html = userComp.template();\n expect(html).toContain('Alice');\n expect(html).toContain('25');\n});\n\ntest('updateUser should change data and return new HTML', () => {\n const newName = 'Bob';\n const newAge = 30;\n const updatedHtml = userComp.updateUser(newName, newAge);\n \n expect(updatedHtml).toContain(newName);\n expect(updatedHtml).toContain(newAge.toString());\n \n // Verify re-rendering also reflects the change\n expect(userComp.template()).toContain(newName);\n});", "comment":"the solution MUST be a single class called UserComponent, it MUST have an internal state object to hold user data, a method template() that returns a string of HTML representing the user profile, and a method updateUser(newName, newAge) that updates the internal state and returns the updated template. the llm should infer from the updateUser signature that the fields in the state object should be name and age, and that the template should include these fields." } {"id":"base_javascript_07","dataset_type":"base","language":"JavaScript","task_category":"refactoring", "prompt_en":"Refactor this UserComponent class to separate concerns using a react functional component using hooks. Keep the same functionality and return ONLY the refactored code.", "prompt_nl":"Herstructureer deze UserComponent klasse om zaken te scheiden met behulp van een react functional component met hooks. Behoud dezelfde functionaliteit en lever ALLEEN de geherstructureerde code in.", "code_snippet_input":"class UserComponent {\n constructor(initialName, initialAge) {\n this._state = {\n name: initialName,\n age: initialAge\n };\n }\n\n template() {\n return `\n
\n

User Profile

\n

Name: ${this._state.name}

\n

Age: ${this._state.age}

\n
\n `;\n }\n\n updateUser(newName, newAge) {\n this._state.name = newName;\n this._state.age = newAge;\n return this.template();\n }\n}", "canonical_solution":"import React, { [Image of React useState hook data flow diagram] useState } from 'react';\n\nconst UserComponent = ({ initialName, initialAge }) => {\n const [user, setUser] = useState({ name: initialName, age: initialAge });\n\n const updateUser = (newName, newAge) => {\n setUser({ name: newName, age: newAge });\n };\n\n return (\n
\n

User Profile

\n

Name: {user.name}

\n

Age: {user.age}

\n \n
\n );\n};", "unit_test_setup":"import { render, screen, fireEvent } from '@testing-library/react';\nimport UserComponent from './UserComponent';\nimport '@testing-library/jest-dom';", "unit_test_assertion":"test('should render initial data and update on interaction', async () => {\n render();\n\n expect(screen.getByText(/Name:.*Alice/i)).toBeInTheDocument();\n expect(screen.getByText(/Age:.*25/i)).toBeInTheDocument();\n\n const button = screen.getByRole('button');\n fireEvent.click(button);\n\n expect(screen.getByText(/Name:.*Bob/i)).toBeInTheDocument();\n expect(screen.getByText(/Age:.*30/i)).toBeInTheDocument();\n});", "comment":"the solution MUST be refactored into a React functional component using hooks, the internal state MUST be managed with useState, and the updateUser function MUST should update the state accordingly. The template method MUST be replaced with JSX returned by the functional component. The functionality of rendering user data and updating it MUST be preserved." } {"id":"base_javascript_08","dataset_type":"base","language":"JavaScript","task_category":"refactoring", "prompt_en":"Refactor this React Router v5 code to React Router v6, ensuring that the authentication guard and nested routes are properly updated. Keep the same functionality and return ONLY the refactored code in a single code block.", "prompt_nl":"Herstructureer deze React Router v5 code naar React Router v6 en zorg ervoor dat de authenticatiebeveiliging en geneste routes correct worden bijgewerkt. Behoud dezelfde functionaliteit en retourneer ALLEEN de geherstructureerde code in één codeblok.", "code_snippet_input":"import React from 'react';\nimport { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';\nimport { AuthProvider, useAuth } from './context/AuthContext';\n\nconst PrivateRoute = ({ children, ...rest }) => {\n const { isAuthenticated } = useAuth();\n return (\n \n isAuthenticated ? (\n children\n ) : (\n \n )\n }\n />\n );\n};\nconst App = () => {\n return (\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n );\n};", "canonical_solution":"import React from 'react';\nimport { \n createBrowserRouter, \n RouterProvider, \n Navigate, \n Outlet \n} from 'react-router-dom';\nimport { AuthProvider, useAuth } from './context/AuthContext';\n\nconst AuthGuard = () => {\n const { isAuthenticated } = useAuth();\n return isAuthenticated ? : ;\n};\n\nconst DashboardLayout = () => (\n
\n \n
\n \n
\n
\n);\n\nconst router = createBrowserRouter([\n {\n path: \"/\",\n element: ,\n },\n {\n path: \"/login\",\n element: ,\n },\n {\n element: ,\n children: [\n {\n path: \"dashboard\",\n element: ,\n children: [\n { index: true, element: },\n { path: \"settings\", element: },\n ],\n },\n ],\n },\n {\n path: \"*\",\n element: ,\n },\n]);\n\nconst App = () => {\n return (\n \n \n \n );\n};\n\nexport default App;", "unit_test_setup":"import { render, screen, cleanup } from '@testing-library/react';\nimport App from './App';\nimport { AuthContext } from './context/AuthContext';\n\nconst renderAppWithAuth = (isAuthenticated) => {\n return render(\n \n \n \n );\n};", "unit_test_assertion":"test('security guard redirects to login when unauthorized', async () => {\n window.history.pushState({}, 'Test page', '/dashboard');\n renderAppWithAuth(false);\n\n expect(screen.getByText(/Login/i)).toBeInTheDocument();\n expect(screen.queryByText(/Overview/i)).not.toBeInTheDocument();\n});", "comment":"the solution MUST refactor the routing logic to use React Router v6's, the test allows for multiple possible implementations, but the overall structure of the app and the functionality of protected routes MUST be preserved." } {"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\": \".gradle/\\build/\\nout/\\n.idea/\\n*.iml\\n.DS_Store\",\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 Patient klasse 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 Transaction class 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 Transaction klasse 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 klassen 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): \ndiscount_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\nimport inspect\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_loop(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 numberofclients (\n-- [Year] INT,\n-- [Month] INT,\n-- [Cost Center Name] VARCHAR(255),\n-- [Client] VARCHAR(255),\n-- [Direct Time In Hours] FLOAT\n-- );", "canonical_solution":"SELECT \n [Year],\n [Month],\n [Cost Center Name],\n SUM([Direct Time In Hours]) AS TotalHours,\n COUNT(DISTINCT [Client]) AS UniqueClientsPerMonth,\n SUM([Direct Time In Hours]) / NULLIF(CAST(COUNT(DISTINCT [Client]) AS FLOAT), 0) AS AvgCustomerHours\nFROM \n numberofclients\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-- );", "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);\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 \n date,\n department,\n sales_amount,\n AVG(sales_amount) OVER (\n PARTITION BY department \n ORDER BY date\n ROWS 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\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\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 \n s.student_name,\n g.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 \n s.student_name,\n g.score AS distinction_grade\nFROM students s\nLEFT JOIN exam_results g \n ON s.id = g.student_id \n AND g.score >= 8;", "unit_test_setup":"CREATE TABLE students (\n id INT PRIMARY KEY, \n student_name VARCHAR(50)\n);\n\nCREATE TABLE exam_results (\n student_id INT, \n score INT\n);\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 (\n SELECT customer_id \n FROM orders\n);", "canonical_solution":"SELECT c.customer_name \nFROM customers c \nWHERE NOT EXISTS (\n SELECT 1 \n FROM orders o \n WHERE o.customer_id = c.id\n);", "unit_test_setup":"CREATE TABLE customers (\n id INT PRIMARY KEY, \n customer_name VARCHAR(50)\n);\n\nCREATE TABLE orders (\n id INT PRIMARY KEY, \n customer_id INT\n);\n\nINSERT INTO customers VALUES (1, 'Alice');\nINSERT INTO orders VALUES (101, 1);\n\nINSERT INTO customers VALUES (2, 'Bob');\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\n region_name,\n positive_cases,\n total_population,\n (positive_cases / total_population) AS disease_probability\nFROM population_studies;", "canonical_solution":"SELECT \n region_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\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';\n\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, \n transaction_date DATETIME\n);\n\nINSERT INTO transactions VALUES (1, '2023-06-15 12:00:00');\nINSERT INTO transactions VALUES (2, '2023-12-31 23:59:59.990');\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 \n-- not contained in either an aggregate function or the GROUP BY clause.\nSELECT \n user_id, \n MAX(login_time) AS last_seen,\n ip_address\nFROM user_logins\nGROUP BY user_id, ip_address;", "canonical_solution":"SELECT \n original.user_id, \n original.login_time AS last_seen,\n original.ip_address\nFROM user_logins original\nINNER JOIN (\n SELECT \n user_id, \n MAX(login_time) AS max_time\n FROM user_logins\n GROUP 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');\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 \n p.patient_name, \n COUNT(r.log_id) AS visit_count\nFROM patients p\nJOIN radiology_log r \n ON p.patient_id = r.patient_id\nWHERE COUNT(r.log_id) > 10\nGROUP BY p.patient_name;", "canonical_solution":"SELECT \n p.patient_name, \n COUNT(r.log_id) AS visit_count\nFROM patients p\nJOIN radiology_log r \n ON p.patient_id = r.patient_id\nGROUP BY p.patient_name\nHAVING COUNT(r.log_id) > 10;", "unit_test_setup":"CREATE TABLE patients (\n patient_id INT, \n patient_name VARCHAR(50)\n);\n\nCREATE TABLE radiology_log (\n log_id INT AUTO_INCREMENT, \n patient_id INT, \n PRIMARY KEY(log_id)\n);\n\nINSERT INTO patients VALUES (1, 'Alice');\nINSERT INTO radiology_log (patient_id) \nVALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1);\n\nINSERT INTO patients VALUES (2, 'Bob');\nINSERT INTO radiology_log (patient_id) \nVALUES (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 \n patient_id, \n name, \n admission_date\nFROM patients p\nJOIN admissions a \n ON p.patient_id = a.patient_id;", "canonical_solution":"SELECT \n p.patient_id, \n p.name, \n a.admission_date\nFROM patients p\nJOIN admissions a \n ON p.patient_id = a.patient_id;", "unit_test_setup":"CREATE TABLE patients (\n patient_id INT, \n name VARCHAR(50)\n);\n\nCREATE TABLE admissions (\n admission_id INT, \n patient_id INT, \n 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 \n patient_id, \n result_value\nFROM lab_results\nWHERE result_value NOT LIKE '%[^0-9]%'\n AND CAST(result_value AS INT) > 100;", "canonical_solution":"SELECT \n patient_id, \n result_value\nFROM lab_results\nWHERE TRY_CAST(result_value AS INT) > 100;", "unit_test_setup":"CREATE TABLE lab_results (\n patient_id INT, \n result_value VARCHAR(50)\n);\n\nINSERT INTO lab_results VALUES (1, '150');\nINSERT INTO lab_results VALUES (2, '50');\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","dialect":"postgresql","task_category":"refactoring", "prompt_en":"This query retrieves the names, the total spend and the date of the most recent order of our 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 \n c.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 (\n SELECT \n customer_id,\n SUM(amount) AS total_spend,\n MAX(order_date) AS last_order_date\n FROM orders\n GROUP BY customer_id\n),\nHighValueCustomers AS (\n SELECT \n customer_id,\n total_spend,\n last_order_date\n FROM CustomerStats\n WHERE total_spend > 1000\n)\nSELECT \n c.customer_name,\n hvc.total_spend,\n hvc.last_order_date\nFROM customers c\nINNER JOIN HighValueCustomers hvc \n ON c.id = hvc.customer_id;", "unit_test_setup":"CREATE TABLE customers (\n id INT PRIMARY KEY, \n customer_name VARCHAR(50)\n);\nCREATE TABLE orders (\n id INT PRIMARY KEY, \n customer_id INT, \n amount INT, \n 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');\nINSERT INTO customers VALUES (2, 'Bob');\nINSERT INTO orders VALUES (201, 2, 900, '2023-02-01');\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 \n patient_name,\n weight_kg,\n height_m,\n CASE \n WHEN (weight_kg / (height_m * height_m)) < 18.5 THEN 'Underweight'\n WHEN (weight_kg / (height_m * height_m)) >= 18.5 AND (weight_kg / (height_m * height_m)) < 25 THEN 'Healthy'\n WHEN (weight_kg / (height_m * height_m)) >= 25 AND (weight_kg / (height_m * height_m)) < 30 THEN 'Overweight'\n WHEN (weight_kg / (height_m * height_m)) >= 30 THEN 'Obese'\n END 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 \n s.student_name,\n SUM(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;\n\nSELECT \n s.student_name,\n SUM(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 \n s.id AS student_id,\n s.student_name,\n COUNT(g.course_id) AS total_classes,\n CAST(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 \n c.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 \n c.name,\n last_o.order_date,\n last_o.product_name,\n last_o.amount\nFROM customers c\nLEFT JOIN LATERAL (\n SELECT order_date, product_name, amount\n FROM orders o\n WHERE o.customer_id = c.id\n ORDER BY order_date DESC\n LIMIT 1\n) last_o ON TRUE;", "unit_test_setup":"CREATE TABLE customers (\n id INT PRIMARY KEY, \n name VARCHAR(50)\n);\n\nCREATE TABLE orders (\n id INT, \n customer_id INT, \n product_name VARCHAR(50), \n amount INT, \n order_date DATE\n);\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');\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." }