Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
11
19
dataset_type
stringclasses
2 values
language
stringclasses
7 values
task_category
stringclasses
11 values
prompt_en
stringlengths
57
550
prompt_nl
stringlengths
62
566
code_snippet_input
stringlengths
0
2.02k
canonical_solution
stringlengths
86
3.05k
unit_test_setup
stringlengths
0
543
unit_test_assertion
stringlengths
172
1.27k
comment
stringlengths
86
465
dialect
stringclasses
3 values
base_java_01
base
Java
scaffolding
write a static method createScaffold(String rootDir) in java that creates a basic project structure for maven. Return ONLY the method
Schrijf een statische methode createScaffold(String rootDir) in Java die een basisprojectstructuur voor Maven creëert. Retourneer ALLEEN de methode.
public static void createScaffold(String rootDir) throws IOException { Path root = Paths.get(rootDir); Files.createDirectories(root.resolve("src/main/java")); Files.createDirectories(root.resolve("src/test/java")); }
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.io.IOException; import java.nio.file.*; import static org.junit.jupiter.api.Assertions.*;
@Test public void testDirectoryCreation(@TempDir Path tempDir) throws IOException { createScaffold(tempDir.toString()); assertTrue(Files.exists(tempDir.resolve("src/main/java")), "src/main/java should exist"); assertTrue(Files.exists(tempDir.resolve("src/test/java")), "src/test/java sho...
the folder structure should contain AT LEAST src/main/java/ and src/test/java/ directories since they're required for every maven project
null
base_java_02
base
Java
elem_func
make a staff class with constructor, setters and getters with at least name, birthdate, gender, position, salary, hire date, and department.
maak een staff klasse met constructor, setters en getters met ten minste name, birthdate, gender, position, salary, hire date en department.
import java.math.BigDecimal; import java.time.LocalDate; public class Staff { private String name; private LocalDate birthDate; private String gender; private String position; private BigDecimal salary; private LocalDate hireDate; private String department; public Staff(String name, Lo...
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.LocalDate; import java.time.Period; import static org.junit.jupiter.api.Assertions.*;
class StaffTest { private Staff staff; private final LocalDate birthDate = LocalDate.of(1990, 5, 20); private final LocalDate hireDate = LocalDate.of(2015, 1, 10); @BeforeEach void setUp() { staff = new Staff( "Alice Johnson", birthDate, "Female", ...
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.
null
base_java_03
base
Java
fix_bug
why am I getting a compilation error in this code? fix it.
waarom krijg ik een compilatie error in deze code? Los het op.
/*Local variable counter defined in an enclosing scope must be final or effectively final*/ public static List<String> generateResults() { List<String> results = new ArrayList<>(); int counter = 0; List<String> names = List.of("Alice", "Bob", "Charlie"); names.forEach(name -> { counter++; results.add(counter ...
import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public static List<String> generateResults() { List<String> results = new ArrayList<>(); AtomicInteger counter = new AtomicInteger(0); List<String> names = List.of("Alice", "Bob", "Charlie"); names.forEach(name -> { ...
import org.junit.jupiter.api.Test; import java.util.List; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.*;
@Test public void testCounterIncrements() { List<String> results = generateResults(); assertEquals(3, results.size(), "List should contain 3 elements"); assertTrue(results.get(0).startsWith("1:"), "First element must start with 1:"); assertTrue(results.get(1).startsWith("2:"),...
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.
null
base_java_04
base
Java
fix_bug
why am I getting a compilation error in this code? fix it
waarom krijg ik een compilatie error in deze code? Los het op.
/*name clash: method(List<String>) has the same erasure as method(List<Integer>)*/ public String sort(List<String> data) { return "Sorting strings"; } public String sort(List<Integer> data) { return "Sorting integers"; }
public String sortStrings(List<String> data) { return "Sorting strings"; } public String sortIntegers(List<Integer> data) { return "Sorting integers"; }
import org.junit.jupiter.api.Test; import java.util.List; import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.*;
@Test public void testMethodsAreDistinct() { Solution sol = new Solution(); String result1 = sol.sortStrings(new ArrayList<String>()); String result2 = sol.sortIntegers(new ArrayList<Integer>()); assertEquals("Sorting strings", result1); assertEquals("Sorting integers",...
Java type erasure means List<String> and List<Integer> 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.
null
base_java_05
base
Java
fix_bug
why am I getting a compilation error in this code? I want to use the process from printer. Output only the fixed class.
Waarom krijg ik een compilatiefout in deze code? Ik wil het proces van printer gebruiken. Geef alleen de vaste klasse weer.
/*class OfficeMachine inherits unrelated defaults for process() from types Printer and Scanner*/ class OfficeMachine implements Printer, Scanner { }
class OfficeMachine implements Printer, Scanner { @Override public String process() { return Printer.super.process(); } }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; interface Printer { default String process() { return "Printing document..."; } } interface Scanner { default String process() { return "Scanning document..."; } }
@Test public void testConflictResolution() { OfficeMachine machine = new OfficeMachine(); assertEquals("Printing document...", machine.process(), "Should return Printer's output"); }
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.
null
base_java_06
base
Java
id_bug
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.
Waarom krijg ik verkeerde resultaten in deze code? De methode retourneert geen lijst met transacties in de doelvaluta. Corrigeer de methode.
class DataFilter { public List<Transaction> filterByCurrency(List<Transaction> data, String targetCurrency) { List<Transaction> result = new ArrayList<>(); for (Transaction t : data) { if (t.getCurrency() == targetCurrency) { result.add(t); } } ...
class DataFilter { public List<Transaction> filterByCurrency(List<Transaction> data, String targetCurrency) { List<Transaction> result = new ArrayList<>(); for (Transaction t : data) { if (targetCurrency.equals(t.getCurrency())) { result.add(t); } } ...
import org.junit.jupiter.api.Test; import java.util.List; import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.*; class Transaction { private String id; private String currency; public Transaction(String id, String currency) { this.id = id; this.currency = currency; } public Strin...
class DataFilterTest { @Test public void testCurrencyFiltering() { DataFilter filter = new DataFilter(); List<Transaction> dataset = new ArrayList<>(); String dynamicUSD = new String("USD"); String dynamicEUR = new String("EUR"); dataset.add(new Transaction("tx1", dynam...
== checks for the same reference in memory, not value equality. MUST use .equals() to compare the string values of the currencies.
null
base_java_07
base
Java
id_bug
why doesn't this method read the csv data properly? Fix the method.
Waarom leest deze methode de csv-gegevens niet correct? Repareer de methode.
/* CSV DATA CONTEXT: patient_id,full_name,birth_date,is_active,last_bill_amount,department 101,Laura Smith,2002-05-20,true,150.00,Cardiology ... 110,Sam I Am,1960-09-09,false,NA,Psychiatry */ public static double getBillAmount(String csvLine) { String[] columns = csvLine.split(","); String rawAmount = columns[...
public static double getBillAmount(String csvLine) { String[] columns = csvLine.split(","); if (columns.length <= 4) return Double.NaN; String rawAmount = columns[4].trim(); if (rawAmount.equalsIgnoreCase("NA") || rawAmount.isEmpty()) { return Double.NaN; } try { return Double...
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*;
@Test public void testValidAmount() { String line = "101,Laura Smith,2002-05-20,true,150.00,Cardiology"; assertEquals(150.00, getBillAmount(line), 0.001); } @Test public void testNAValue() { String line = "110,Sam I Am,1960-09-09,false,NA,Psychiatry"; assertTrue(Double.is...
the method fails to handle 'NA' values and possible formatting issues. MUST check for 'NA' and handle NumberFormatException to avoid crashes.
null
base_java_08
base
Java
id_bug
i want to use this method to transpose a square matrix but it gives the wrong results. Fix the method.
Ik wil deze methode gebruiken om een vierkante matrix te transponeren, maar het geeft verkeerde resultaten. Corrigeer de methode.
public static int[][] transposeMatrix(int[][] input) { int rows = input.length; int cols = input[0].length; int[][] output = new int[cols][rows]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { output[i][j] = input[i][j]; } } return output; }
public static int[][] transposeMatrix(int[][] input) { int rows = input.length; int cols = input[0].length; int[][] output = new int[cols][rows]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { output[j][i] = input[i][j]; } } return output; }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*;
@Test public void testTranspose2x2() { int[][] input = { {1, 2}, {3, 4} }; int[][] expected = { {1, 3}, {2, 4} }; assertArrayEquals(expected, transposeMatrix(input), "Should swap rows and columns correctly"); } @Test public void testTranspose3x3() { int[][] input = { ...
the method incorrectly assigns values to the output matrix into wrong positions, MUST assign output[j][i] = input[i][j] to transpose correctly.
null
base_java_09
base
Java
architecture
create a static singleton DatabaseConnection class in java with a getInstance method.
Maak een statische singleton DatabaseConnection klasse in java met een getInstance methode.
public static class DatabaseConnection { private static volatile DatabaseConnection instance; private DatabaseConnection() {} public static DatabaseConnection getInstance() { if (instance == null) { synchronized (DatabaseConnection.class) { if (instance == null) { ...
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import java.lang.reflect.*;
@Test public void testSingletonUniqueInstance() throws InterruptedException { DatabaseConnection[] instances = new DatabaseConnection[2]; Thread t1 = new Thread(() -> instances[0] = DatabaseConnection.getInstance()); Thread t2 = new Thread(() -> instances[1] = DatabaseConnection.getInstance(...
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.
null
base_java_10
base
Java
refactoring
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
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.
public static boolean isOverdue(LocalDate deadline) { LocalDate today = LocalDate.now(); return today.isAfter(deadline); }
public static boolean isOverdue(LocalDate deadlineDate) { LocalDateTime currentDateTime = LocalDateTime.now(); LocalDateTime deadlineTimestamp = deadlineDate.atStartOfDay(); return currentDateTime.isAfter(deadlineTimestamp); }
import java.time.LocalDate; import java.time.LocalDateTime; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*;
@Test public void testYesterdayIsOverdue() { assertTrue(isOverdue(LocalDate.now().minusDays(1)), "Yesterday should be overdue"); } @Test public void testTomorrowIsNotOverdue() { assertFalse(isOverdue(LocalDate.now().plusDays(1)), "Tomorrow should not be overdue"); } @Test p...
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 e...
null
base_java_11
base
Java
refactoring
this method groups transaction over 1000 by currency. refactor it to use streams
deze methode groepeert transacties van meer dan 1000 per valuta. Refactor deze om streams te gebruiken.
public Map<String, List<Transaction>> groupHighValueTransactions(List<Transaction> transactions) { Map<String, List<Transaction>> result = new HashMap<>(); for (Transaction t : transactions) { if (t.getAmount() > 1000) { String currency = t.getCurrency(); if (!result.containsKey(...
public Map<String, List<Transaction>> groupHighValueTransactions(List<Transaction> transactions) { return transactions.stream() .filter(t -> t.getAmount() > 1000) .collect(Collectors.groupingBy(Transaction::getCurrency)); }
import org.junit.jupiter.api.Test; import java.util.*; import java.util.stream.Collectors; import java.nio.file.*; import java.io.IOException; import static org.junit.jupiter.api.Assertions.*; class Transaction { private String currency; private double amount; public Transaction(String currency, double amo...
@Test public void testGrouping() { List<Transaction> data = Arrays.asList( new Transaction("USD", 500), new Transaction("USD", 1500), new Transaction("EUR", 2000), new Transaction("USD", 3000) ); Map<String, List<Transaction>> resu...
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.
null
base_java_12
base
Java
refactoring
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
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.
public String getDiscountCode(String dayOfWeek) { String discount; switch (dayOfWeek) { case "Monday": discount = "MANIC_MONDAY_15"; break; case "Wednesday": discount = "WACKY_WED_10"; break; case "Friday": discount = "TGIF_25";...
public String getDiscountCode(String dayOfWeek) { return switch (dayOfWeek) { case "Monday" -> "MANIC_MONDAY_15"; case "Wednesday" -> "WACKY_WED_10"; case "Friday" -> "TGIF_25"; case "Saturday", "Sunday" -> "WEEKEND_SAVER_20"; default -> "STANDARD_PRICING"; }; }
import org.junit.jupiter.api.Test; import java.nio.file.*; import java.io.IOException; import static org.junit.jupiter.api.Assertions.*;
@Test public void testDiscounts() { assertEquals("MANIC_MONDAY_15", getDiscountCode("Monday")); assertEquals("WEEKEND_SAVER_20", getDiscountCode("Sunday")); assertEquals("STANDARD_PRICING", getDiscountCode("Tuesday")); } @Test public void testModernSyntax() throws IOExceptio...
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.
null
base_javascript_01
base
JavaScript
scaffolding
write a JavaScript function called createReactScaffold(projectName) that creates a basic project structure for a React app using Vite. Return ONLY the function.
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.
function createReactScaffold(projectName) { const rootDir = path.resolve(process.cwd(), projectName); const dirs = [ rootDir, path.join(rootDir, 'src'), path.join(rootDir, 'public') ]; dirs.forEach(dir => { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recur...
const { vol } = require('memfs'); const fs = require('fs'); const path = require('path'); jest.mock('fs', () => require('memfs').fs); describe('createReactScaffold', () => { beforeEach(() => { vol.reset(); }); const projectName = 'test-app';
test('should create the correct directory structure', () => { createReactScaffold(projectName); const rootPath = path.resolve(process.cwd(), projectName); expect(fs.existsSync(rootPath)).toBe(true); expect(fs.existsSync(path.join(rootPath, 'src'))).toBe(true); expect(fs.existsSync(path.join(rootPath...
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.
null
base_javascript_02
base
JavaScript
elem_func
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.
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 ret...
function createUser(name, email, password, role, joinDate, isActive) { this.name = name; this.email = email; this.password = password; this.role = role; this.joinDate = joinDate; this.isActive = isActive; this.getProfile = function() { return `${this.name} (${this.email})`; }; }
describe('createUser constructor', () => { const userData = { name: 'Name Surname', email: 'email@example.com', password: 'securePassword123', role: 'Admin', joinDate: '2026-01-01', isActive: true };
test('initialize all user properties', () => { const user = new createUser( userData.name, userData.email, userData.password, userData.role, userData.joinDate, userData.isActive ); expect(user.name).toBe(userData.name); expect(user.email).toBe(userData.email); exp...
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.
null
base_javascript_03
base
JavaScript
id_bug
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.
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.
function fixMissingGrades(students) { return students.map(student => { if (student.grade == NaN) { return { ...student, grade: 0 }; } return student; }); }
function fixMissingGrades(students) { return students.map(student => { if (isNaN(student.grade)) { return { ...student, grade: 0 }; } return student; }); }
describe('fixMissingGrades', () => { const inputDataset = [ { name: 'Alice', grade: 85 }, { name: 'Bob', grade: NaN }, { name: 'Charlie', grade: 0 }, { name: 'Diana', grade: undefined } ];
test('should replace NaN grades with 0', () => { const result = fixMissingGrades(inputDataset); const bob = result.find(s => s.name === 'Bob'); expect(bob.grade).toBe(0); }); test('should not modify existing valid grades', () => { const result = fixMissingGrades(inputDataset); const alice = res...
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 retu...
null
base_javascript_04
base
JavaScript
fix_bug
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.
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.
// ReferenceError: Cannot access 'settings' before initialization function initializeApp() { const results = {}; results.initial = settings.theme; if (settings.version.startsWith("2")) { const settings = { theme: "light" }; results.override = settings.theme; } return results; }
const settings = { theme: "dark", version: "2.1.0" }; function initializeApp() { const results = {}; results.initial = settings.theme; if (settings.version.startsWith("2")) { const localSettings = { theme: "light" }; results.override = localSettings.theme; } return results...
describe('initializeApp Robust Evaluation', () => { global.settings = { theme: "dark", version: "2.1.0" };
test('fixed version should produce correct theme values regardless of implementation', () => { const output = initializeApp(); expect(output).toBeDefined(); expect(output.initial).toBe("dark"); expect(output.override).toBe("light"); });
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 vari...
null
base_javascript_05
base
JavaScript
fix_bug
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.
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.
// TypeError: Cannot read properties of undefined (reading 'prefix') const logger = { prefix: 'LOG:', delayedLog(msg) { return new Promise((resolve) => { setTimeout(function() { resolve(`${this.prefix} ${msg}`); }, 10); }); } };
const logger = { prefix: 'LOG:', delayedLog(msg) { return new Promise((resolve) => { setTimeout(() => { resolve(`${this.prefix} ${msg}`); }, 10); }); } };
describe('Logger Context Evaluation', () => {
test('should correctly resolve with the prefix and message', async () => { const result = await logger.delayedLog('Hello'); expect(result).toBe('LOG: Hello'); });
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
null
base_javascript_06
base
JavaScript
architecture
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 templa...
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 e...
class UserComponent { constructor(initialName, initialAge) { this._state = { name: initialName, age: initialAge }; } template() { return ` <div class="user-card"> <h1>User Profile</h1> <p>Name: ${this._state.name}</p> <p>Age: ${this._state.age}</p> </di...
describe('UserComponent Architecture', () => { const initialData = { name: 'Alice', age: 25 }; const userComp = new UserComponent(initialData.name, initialData.age);
test('Initial state should render correctly', () => { const html = userComp.template(); expect(html).toContain('Alice'); expect(html).toContain('25'); }); test('updateUser should change data and return new HTML', () => { const newName = 'Bob'; const newAge = 30; const updatedHtml = userComp.updateUser(newN...
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 in...
null
base_javascript_07
base
JavaScript
refactoring
Refactor this UserComponent class to separate concerns using a react functional component using hooks. Keep the same functionality and return ONLY the refactored code.
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.
class UserComponent { constructor(initialName, initialAge) { this._state = { name: initialName, age: initialAge }; } template() { return ` <div class="user-card"> <h1>User Profile</h1> <p>Name: ${this._state.name}</p> <p>Age: ${this._state.age}</p> </di...
import React, { [Image of React useState hook data flow diagram] useState } from 'react'; const UserComponent = ({ initialName, initialAge }) => { const [user, setUser] = useState({ name: initialName, age: initialAge }); const updateUser = (newName, newAge) => { setUser({ name: newName, age: newAge }); }; ...
import { render, screen, fireEvent } from '@testing-library/react'; import UserComponent from './UserComponent'; import '@testing-library/jest-dom';
test('should render initial data and update on interaction', async () => { render(<UserComponent initialName="Alice" initialAge={25} />); expect(screen.getByText(/Name:.*Alice/i)).toBeInTheDocument(); expect(screen.getByText(/Age:.*25/i)).toBeInTheDocument(); const button = screen.getByRole('button'); fireE...
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 d...
null
base_javascript_08
base
JavaScript
refactoring
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.
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.
import React from 'react'; import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'; import { AuthProvider, useAuth } from './context/AuthContext'; const PrivateRoute = ({ children, ...rest }) => { const { isAuthenticated } = useAuth(); return ( <Route {...rest} render={(...
import React from 'react'; import { createBrowserRouter, RouterProvider, Navigate, Outlet } from 'react-router-dom'; import { AuthProvider, useAuth } from './context/AuthContext'; const AuthGuard = () => { const { isAuthenticated } = useAuth(); return isAuthenticated ? <Outlet /> : <Navigate to="/logi...
import { render, screen, cleanup } from '@testing-library/react'; import App from './App'; import { AuthContext } from './context/AuthContext'; const renderAppWithAuth = (isAuthenticated) => { return render( <AuthContext.Provider value={{ isAuthenticated }}> <App /> </AuthContext.Provider> ); };
test('security guard redirects to login when unauthorized', async () => { window.history.pushState({}, 'Test page', '/dashboard'); renderAppWithAuth(false); expect(screen.getByText(/Login/i)).toBeInTheDocument(); expect(screen.queryByText(/Overview/i)).not.toBeInTheDocument(); });
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.
null
base_python_01
base
Python
scaffolding
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
Schrijf een methode createScaffold in Python die een basisprojectstructuur voor een Kotlin-project maakt met behulp van Gradle. Retourneer ALLEEN de methode.
from pathlib import Path def createScaffold(project_name: str, root_dir: str = "."): base_path = Path(root_dir) / project_name directories = [ base_path / "src/main/kotlin", base_path / "src/main/resources", base_path / "src/test/kotlin", base_path / "src/test/resources", ...
import unittest import tempfile import shutil from pathlib import Path import os
class TestKotlinScaffold(unittest.TestCase): def setUp(self): self.test_dir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.test_dir) def test_directory_structure(self): project_name = "MyKotlinApp" createScaffold(project_name, self.test_dir) ba...
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.
null
base_python_02
base
Python
scaffolding
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.
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.
from pathlib import Path def create_vue_scaffold(project_name: str): base = Path(project_name) src = base / "src" dirs = [ base / "public", src / "assets", src / "components", src / "views", src / "stores", src / "router", ] files = { ...
import unittest import tempfile import shutil import os from pathlib import Path
class TestVueScaffold(unittest.TestCase): def setUp(self): self.test_dir = tempfile.mkdtemp() self.original_cwd = os.getcwd() os.chdir(self.test_dir) def tearDown(self): os.chdir(self.original_cwd) shutil.rmtree(self.test_dir) def test_vue_structure(self): p...
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.
null
base_python_03
base
Python
elem_func
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.
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.
class Patient: def __init__(self, patient_id: int, first_name: str, last_name: str, birth_date: str, is_active: bool, gp_id: int, zip_code: str): self._patient_id = patient_id self._first_name = first_name self._last_name = last_name self._birth_date = birth_date self._is_act...
import unittest
class TestPatientClass(unittest.TestCase): def test_properties(self): p = Patient(101, "John", "Doe", "1980-05-20", True, 55, "1000AB") self.assertEqual(p.first_name, "John") self.assertEqual(p.gp_id, 55) self.assertTrue(p.is_active) p.first_name = "Jane" ...
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.
null
base_python_04
base
Python
elem_func
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.
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.
class Transaction: def __init__(self, transaction_id: int, user_id: int, amount: float, currency: str, timestamp: str, status: bool): self.transaction_id = transaction_id self.user_id = user_id self.amount = amount self.currency = currency self.timestamp = t...
import unittest
class TestTransactionClass(unittest.TestCase): def test_pythonic_properties(self): t = Transaction(1, 101, 50.0, "EUR", "2023-01-01T12:00:00Z", True) self.assertEqual(t.amount, 50.0) self.assertEqual(t.currency, "EUR") t.amount = 75.50 self.assertEqual(t.amount, 75.5...
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.
null
base_python_05
base
Python
id_bug
This function cleans transactions but it doesn't seem to be updating the dataframe correctly when it should. Fix the bugs in the function.
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.
import pandas as pd import numpy as np def clean_transactions(df): df = df[df['amount'] >= 0] df['category'] = df['category'].fillna('Unknown') df[df['risk_score'] > 0.9]['amount'] = 1000 return df
import pandas as pd import numpy as np def clean_transactions(df): df = df[df['amount'] >= 0] df['category'] = df['category'].fillna('Unknown') df.loc[df['risk_score'] > 0.9, 'amount'] = 1000 return df
import pandas as pd import numpy as np import unittest
class TestTransactionCleaning(unittest.TestCase): def test_logic(self): data = { 'id': [1, 2, 3, 4], 'amount': [100.0, -50.0, 200.0, 5000.0], 'category': ['Food', 'Food', np.nan, 'Travel'], 'risk_score': [0.1, 0.5, 0.1, 0.95] } df = pd.DataFram...
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.
null
base_python_06
base
Python
id_bug
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.
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.
def extract_all_values(data, target_key, results=[]): if isinstance(data, dict): for key, value in data.items(): if key == target_key: results.append(value) if isinstance(value, (dict, list)): extract_all_values(value, target_key, results) elif isi...
def extract_all_values(data, target_key, results=None): if results is None: results = [] if isinstance(data, dict): for key, value in data.items(): if key == target_key: results.append(value) if isinstance(value, (dict, list)): extract_all_...
import unittest
class TestRecursiveSearch(unittest.TestCase): def test_mutable_default(self): data1 = {'id': 101, 'meta': {'id': 102, 'name': 'test'}} res1 = extract_all_values(data1, 'id') self.assertEqual(sorted(res1), [101, 102], "First call failed to extract correct IDs") data2 = {'id': 999} ...
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.
null
base_python_07
base
Python
id_bug
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.
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.
import time def process_match_report(players, match_scores): report = [] for player, score in zip(players, match_scores): entry = { "player_id": player["id"], "username": player["username"], "score": score, "status": "Ranked", "processed_at": t...
from itertools import zip_longest import time def process_match_report(players, match_scores): report = [] for player, score in zip_longest(players, match_scores, fillvalue=None): if score is None: final_score = 0 status = "Unranked (No Play)" else: final_scor...
import unittest import time
class TestLeaderboard(unittest.TestCase): def test_missing_players(self): players = [ {"id": 1, "username": "Alice"}, {"id": 2, "username": "Bob"}, {"id": 3, "username": "Charlie"} ] scores = [100] report = process_match_report(players, sc...
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.
null
base_python_08
base
Python
fix_bug
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.
Deze methode moet het gemiddelde berekenen van alle positieve getallen in een lijst, maar werkt niet correct. Los de bugs in de functie op.
def calculate_average(numbers): total = 0 count = 0 for num in numbers: if num >= 0: total += num count += 1 return total / count if count > 0 else 0
def calculate_average(numbers): total = 0 count = 0 for num in numbers: if num >= 0: total += num count += 1 return total / count if count > 0 else 0
import unittest
class TestAverage(unittest.TestCase): def test_logic(self): self.assertEqual(calculate_average([10, -5, 20]), 15, "Function returned early! Did you move the return statement outside the loop?") self.assertEqual(calculate_average([]), 0, "Empty list should return 0") self.as...
the return statement is too indented and executes in the first iteration the loop. the solution MUST unindent the return statement.
null
base_python_09
base
Python
fix_bug
this method counts how many times each word appears on a list. but it throws an error. Fix the bugs in the function.
Deze methode telt hoe vaak elk woord in een lijst voorkomt. Maar er treedt een fout op. Los de bugs in de functie op.
#KeyError def count_word_frequencies(words): frequency_map = {} for word in words: frequency_map[word] = frequency_map[word] + 1 return frequency_map
from collections import defaultdict def count_word_frequencies(words): frequency_map = defaultdict(int) for word in words: frequency_map[word] += 1 return dict(frequency_map)
import unittest from collections import defaultdict
class TestFrequency(unittest.TestCase): def test_counting(self): input_words = ["apple", "banana", "apple", "cherry", "banana", "banana"] expected = {"apple": 2, "banana": 3, "cherry": 1} result = count_word_frequencies(input_words) self.assertEqual(result, expected, "Counts...
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.
null
base_python_10
base
Python
fix_bug
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.
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.
#UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 12: invalid continuation byte def count_word_occurrences(file_path, target_word): total_count = 0 with open(file_path, 'r') as f: for line in f: words = line.lower().split() total_count += words.count(target_wo...
def count_word_occurrences(file_path, target_word): total_count = 0 with open(file_path, 'r', errors='replace') as f: for line in f: words = line.lower().split() total_count += words.count(target_word.lower()) return total_count
import unittest import tempfile import os
class TestEncoding(unittest.TestCase): def setUp(self): self.tf = tempfile.NamedTemporaryFile(delete=False) self.tf.write(b"hello world caf\xe9 python") self.tf.close() def tearDown(self): os.remove(self.tf.name) def test_bad_encoding(self): try: count =...
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.
null
base_python_11
base
Python
architecture
Write a DAL to fetch the necessary data from a MSSQL database, for the display_menu function that uses SQLAlchemy.
Schrijf een DAL om de benodigde gegevens uit een MSSQL database op te halen voor de functie display_menu die gebruikmaakt van SQLAlchemy.
def display_menu(session): pizzas = get_pizzas(session) items = get_items(session) print("\nMenu Items:") print("----------") print("ID | Name | Price") print("----------") def line_item(mi): print(f"{mi.Item_ID} | {mi.Item_Name} .......... {mi.Item_Price}") def line_pizza(pi):...
def get_pizzas(session): query = "SELECT Pizza_ID, Pizza_Name, Vegan_Pizza, Vegetarian_Pizza FROM Pizzas" return session.execute(query).fetchall() def get_items(session): query = "SELECT Item_ID, Item_Name, Item_Price FROM Items" return session.execute(query).fetchall()
from unittest.mock import MagicMock session = MagicMock() session.execute.return_value.fetchall.return_value = [] def continue_message(s): pass
get_pizzas(session) args_pizza, _ = session.execute.call_args sql_pizza = str(args_pizza[0]).replace('\n', ' ').strip() assert "SELECT" in sql_pizza assert "Pizza_ID" in sql_pizza assert "Pizza_Name" in sql_pizza assert "Vegan_Pizza" in sql_pizza assert "Vegetarian_Pizza" in sql_pizza assert "FROM Pizzas" in sql_pizz...
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
null
base_python_12
base
Python
architecture
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.
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
from abc import ABC, abstractmethod class Pizza(ABC): @abstractmethod def get_description(self): pass @abstractmethod def get_cost(self): pass class PlainPizza(Pizza): def get_description(self): return "Thin dough" def get_cost(self): return 4.00
class ToppingDecorator(Pizza): def __init__(self, pizza: Pizza): self._pizza = pizza @abstractmethod def get_description(self): return self._pizza.get_description() @abstractmethod def get_cost(self): return self._pizza.get_cost() class Pepperoni(ToppingDecorator): def g...
import unittest from abc import ABC, abstractmethod class Pizza(ABC): @abstractmethod def get_description(self): pass @abstractmethod def get_cost(self): pass class PlainPizza(Pizza): def get_description(self): return "Thin dough" def get_cost(self): return 4.0...
class TestDecorator(unittest.TestCase): def test_pizza_stacking(self): my_pizza = PlainPizza() self.assertEqual(my_pizza.get_cost(), 4.00) my_pizza = Mozzarella(my_pizza) self.assertEqual(my_pizza.get_cost(), 5.00) self.assertIn("Mozzarella", my_pizza.get_description...
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.
null
base_python_13
base
Python
refactoring
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 ...
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 ...
def process_order(order): if not order.get("items"): return "Order must contain items" total = sum(item["price"] * item["quantity"] for item in order["items"]) if order.get("discount_code") == "SAVE10": total *= 0.9 elif order.get("discount_code") == "SAVE20": total *= 0.8 ...
def validate_order(order): if not order.get("items"): return False, "Order must contain items" return True, "" def calculate_total(order): return sum(item["price"] * item["quantity"] for item in order["items"]) def apply_discount(total, discount_code): discount_rates = { "SAVE10": 0.9,...
import unittest import inspect
class TestRefactoring(unittest.TestCase): def test_functionality(self): order = { "items": [{"price": 100, "quantity": 1}], "discount_code": "SAVE20" } self.assertEqual(process_order(order), "Total: $80.00") self.assertEqual(process_order({}), "Order must cont...
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
null
base_python_14
base
Python
refactoring
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()`.
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()`.
from setuptools import setup, find_packages setup( name="legacy-data-tool", version="1.2.0", description="A legacy tool for data processing that needs modernization.", long_description=open("README.md").read(), long_description_content_type="text/markdown", url="https://github.com/example/legacy-data-tool", author="Jan...
def get_pyproject_toml(): return """ [build-system] requires = ["setuptools>=61.0"] build-backend = "setuptools.build_meta" [project] name = "legacy-data-tool" version = "1.2.0" description = "A legacy tool for data processing that needs modernization." readme = "README.md" requires-python = ">=3.8, <4" license = ...
import tomli import unittest
toml_string = get_pyproject_toml() try: data = tomli.loads(toml_string) except Exception as e: raise AssertionError(f"Invalid TOML syntax: {e}") assert "build-system" in data assert data["project"]["name"] == "legacy-data-tool" assert "pandas>=1.3.0" in data["project"]["dependencies"]
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.
null
base_python_15
base
Python
refactoring
This function retrieves the names of all senior members from a any team in a nested structure. Refactor the method to use list comprehensions.
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.
def get_seniors_loop(data): seniors = [] for team in data: for member in team['members']: if member['role'] == 'Senior': seniors.append(member['name']) return seniors
def get_seniors_loop(data): return [ member['name'] for team in data for member in team['members'] if member['role'] == 'Senior' ]
import unittest import inspect
class TestListComp(unittest.TestCase): def test_behavior(self): data = [ {'members': [{'name': 'Alice', 'role': 'Junior'}, {'name': 'Bob', 'role': 'Senior'}]}, {'members': [{'name': 'Charlie', 'role': 'Senior'}, {'name': 'Dave', 'role': 'Lead'}]} ] expected = ['Bob', ...
The solution MUST keep the same functionality, but change the implementation from nested for loops to a list comprehension.
null
base_sql_01
base
SQL
queries
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(...
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: ...
-- Schema Context: -- CREATE TABLE numberofclients ( -- [Year] INT, -- [Month] INT, -- [Cost Center Name] VARCHAR(255), -- [Client] VARCHAR(255), -- [Direct Time In Hours] FLOAT -- );
SELECT [Year], [Month], [Cost Center Name], SUM([Direct Time In Hours]) AS TotalHours, COUNT(DISTINCT [Client]) AS UniqueClientsPerMonth, SUM([Direct Time In Hours]) / NULLIF(CAST(COUNT(DISTINCT [Client]) AS FLOAT), 0) AS AvgCustomerHours FROM numberofclients GROUP BY [Year], [Mo...
CREATE TABLE numberofclients ( [Year] INT, [Month] INT, [Cost Center Name] VARCHAR(255), [Client] VARCHAR(255), [Direct Time In Hours] FLOAT ); -- Test Data: IT Dept, Jan 2023 INSERT INTO numberofclients VALUES (2023, 1, 'IT', 'ClientA', 10.0); INSERT INTO numberofclients VALUES (2023, 1, 'IT', 'Cl...
@Test public void testSqlLogic(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(generatedSqlQuery)) { assertTrue(rs.next(), "Result set should have at least one row"); assertE...
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.
mssql
base_sql_02
base
SQL
queries
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.
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.
-- Schema Context: -- CREATE TABLE students ( -- id INTEGER AUTO_INCREMENT UNIQUE, -- name VARCHAR(255), -- valedictorian BOOLEAN, -- ... -- ); -- -- CREATE TABLE valedictorians ( -- id INTEGER UNIQUE -- );
UPDATE students s LEFT JOIN valedictorians v ON s.id = v.id SET s.valedictorian = (v.id IS NOT NULL);
CREATE TABLE students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), valedictorian BOOLEAN ); CREATE TABLE valedictorians ( id INT PRIMARY KEY ); INSERT INTO students (id, name, valedictorian) VALUES (1, 'Alice', FALSE); INSERT INTO valedictorians (id) VALUES (1); INSERT INTO students (id, na...
@Test public void testUpdateLogic(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement()) { stmt.executeUpdate(generatedSqlQuery); ResultSet rs1 = stmt.executeQuery("SELECT valedictorian FROM students WHERE id = 1"); assertTrue(...
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.
mysql
base_sql_03
base
SQL
queries
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.
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.
-- CREATE TABLE daily_sales ( -- id INT PRIMARY KEY, -- date DATE NOT NULL, -- department VARCHAR(50) NOT NULL, -- sales_amount DECIMAL(10, 2) NOT NULL, -- INDEX idx_dept_date (department, date) -- );
SELECT date, department, sales_amount, AVG(sales_amount) OVER ( PARTITION BY department ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ) as moving_avg_3_day FROM daily_sales;
CREATE TABLE daily_sales ( id INT PRIMARY KEY, date DATE, department VARCHAR(50), sales_amount DECIMAL(10, 2) ); INSERT INTO daily_sales VALUES (1, '2023-01-01', 'Electronics', 10.00); INSERT INTO daily_sales VALUES (2, '2023-01-02', 'Electronics', 20.00); INSERT INTO daily_sales VALUES (3, '2023-01-03...
@Test public void testMovingAverage(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(generatedSqlQuery)) { assertTrue(rs.next()); assertEquals(10.0, rs.getDouble("moving_avg_3_day"), 0.01); ...
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).
postgresql
base_sql_04
base
SQL
id_bug
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.
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.
SELECT s.student_name, g.score AS distinction_grade FROM students s LEFT JOIN exam_results g ON s.id = g.student_id WHERE g.score >= 8;
SELECT s.student_name, g.score AS distinction_grade FROM students s LEFT JOIN exam_results g ON s.id = g.student_id AND g.score >= 8;
CREATE TABLE students ( id INT PRIMARY KEY, student_name VARCHAR(50) ); CREATE TABLE exam_results ( student_id INT, score INT ); INSERT INTO students VALUES (1, 'Alice'); INSERT INTO exam_results VALUES (1, 9); INSERT INTO students VALUES (2, 'Bob'); INSERT INTO exam_results VALUES (2, 6); INSERT ...
@Test public void testLeftJoinLogic(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(generatedSqlQuery)) { int rowCount = 0; while(rs.next()) { rowCount++; ...
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.
postgresql
base_sql_05
base
SQL
id_bug
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.
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.
SELECT customer_name FROM customers WHERE id NOT IN ( SELECT customer_id FROM orders );
SELECT c.customer_name FROM customers c WHERE NOT EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.id );
CREATE TABLE customers ( id INT PRIMARY KEY, customer_name VARCHAR(50) ); CREATE TABLE orders ( id INT PRIMARY KEY, customer_id INT ); INSERT INTO customers VALUES (1, 'Alice'); INSERT INTO orders VALUES (101, 1); INSERT INTO customers VALUES (2, 'Bob'); INSERT INTO orders VALUES (102, NULL);
@Test public void testNullTrap(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(generatedSqlQuery)) { assertTrue(rs.next(), "The query returned no results. Did you handle the NULLs in the subquery?"); ...
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.
postgresql
base_sql_06
base
SQL
id_bug
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.
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.
SELECT region_name, positive_cases, total_population, (positive_cases / total_population) AS disease_probability FROM population_studies;
SELECT region_name, (positive_cases * 1.0 / total_population) AS disease_probability FROM population_studies;
CREATE TABLE population_studies ( region_name VARCHAR(50), positive_cases INT, total_population INT ); INSERT INTO population_studies VALUES ('Region A', 50, 100);
@Test public void testIntegerDivision(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(generatedSqlQuery)) { assertTrue(rs.next()); double probability = rs.getDouble("disea...
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.
postgresql
base_sql_07
base
SQL
id_bug
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.
Ik wil alle transacties van 2023 verzamelen voor het jaarverslag, maar deze query geeft 4 extra transacties uit 2024 weer. Corrigeer de query.
DECLARE @Start DATETIME = '2023-1-1 00:00:00.000'; DECLARE @End DATETIME = '2023-12-31 23:59:59.999'; SELECT * FROM transactions WHERE transaction_date BETWEEN @Start AND @End;
SELECT * FROM transactions WHERE transaction_date >= '2023-1-1 00:00:00' AND transaction_date < '2024-1-1 00:00:00';
CREATE TABLE transactions ( id INT, transaction_date DATETIME ); INSERT INTO transactions VALUES (1, '2023-06-15 12:00:00'); INSERT INTO transactions VALUES (2, '2023-12-31 23:59:59.990'); INSERT INTO transactions VALUES (3, '2024-01-01 00:00:00.000');
@Test public void testDateRounding(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(generatedSqlQuery)) { int count = 0; while(rs.next()) { count++; Time...
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.
mssql
base_sql_08
base
SQL
fix_bug
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.
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.
-- Column 'user_logins.ip_address' is invalid in the select list because it is -- not contained in either an aggregate function or the GROUP BY clause. SELECT user_id, MAX(login_time) AS last_seen, ip_address FROM user_logins GROUP BY user_id, ip_address;
SELECT original.user_id, original.login_time AS last_seen, original.ip_address FROM user_logins original INNER JOIN ( SELECT user_id, MAX(login_time) AS max_time FROM user_logins GROUP BY user_id ) filtered ON original.user_id = filtered.user_id AND original.login_time = fil...
CREATE TABLE user_logins ( user_id INT, login_time DATETIME, ip_address VARCHAR(50) ); INSERT INTO user_logins VALUES (1, '2023-01-01 10:00:00', '1.1.1.1'); INSERT INTO user_logins VALUES (1, '2023-01-02 10:00:00', '2.2.2.2'); INSERT INTO user_logins VALUES (2, '2023-01-05 10:00:00', '3.3.3.3');
@Test public void testGroupByLogic(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(generatedSqlQuery)) { boolean foundUser1 = false; while(rs.next()) { if(rs.getInt("user_id") == 1) ...
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).
mssql
base_sql_09
base
SQL
fix_bug
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.
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.
-- ERROR 1111 (HY000): Invalid use of group function SELECT p.patient_name, COUNT(r.log_id) AS visit_count FROM patients p JOIN radiology_log r ON p.patient_id = r.patient_id WHERE COUNT(r.log_id) > 10 GROUP BY p.patient_name;
SELECT p.patient_name, COUNT(r.log_id) AS visit_count FROM patients p JOIN radiology_log r ON p.patient_id = r.patient_id GROUP BY p.patient_name HAVING COUNT(r.log_id) > 10;
CREATE TABLE patients ( patient_id INT, patient_name VARCHAR(50) ); CREATE TABLE radiology_log ( log_id INT AUTO_INCREMENT, patient_id INT, PRIMARY KEY(log_id) ); INSERT INTO patients VALUES (1, 'Alice'); INSERT INTO radiology_log (patient_id) VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1)...
@Test public void testHavingClause(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(generatedSqlQuery)) { assertTrue(rs.next(), "Should return at least one patient with > 10 visits"); asser...
The solution MUST replace the WHERE clause with HAVING for filtering aggregate fields.
mysql
base_sql_10
base
SQL
fix_bug
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.
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.
-- Error Code: 1052. Column 'patient_id' in field list is ambiguous SELECT patient_id, name, admission_date FROM patients p JOIN admissions a ON p.patient_id = a.patient_id;
SELECT p.patient_id, p.name, a.admission_date FROM patients p JOIN admissions a ON p.patient_id = a.patient_id;
CREATE TABLE patients ( patient_id INT, name VARCHAR(50) ); CREATE TABLE admissions ( admission_id INT, patient_id INT, admission_date DATE ); INSERT INTO patients VALUES (1, 'John Doe'); INSERT INTO admissions VALUES (100, 1, '2023-01-01');
@Test public void testAmbiguousColumn(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(generatedSqlQuery)) { assertTrue(rs.next(), "Query should return results once the ambiguity is fixed."); ...
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).
mysql
base_sql_11
base
SQL
fix_bug
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.
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.
-- Conversion failed when converting the varchar value 'Pending' to data type int SELECT patient_id, result_value FROM lab_results WHERE result_value NOT LIKE '%[^0-9]%' AND CAST(result_value AS INT) > 100;
SELECT patient_id, result_value FROM lab_results WHERE TRY_CAST(result_value AS INT) > 100;
CREATE TABLE lab_results ( patient_id INT, result_value VARCHAR(50) ); INSERT INTO lab_results VALUES (1, '150'); INSERT INTO lab_results VALUES (2, '50'); INSERT INTO lab_results VALUES (3, 'Pending');
@Test public void testSafeCast(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(generatedSqlQuery)) { assertTrue(rs.next(), "Should return the valid numeric row > 100"); assertEquals("150"...
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
mssql
base_sql_12
base
SQL
refactoring
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.
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.
SELECT c.customer_name, (SELECT SUM(amount) FROM orders o WHERE o.customer_id = c.id) as total_spend, (SELECT MAX(order_date) FROM orders o WHERE o.customer_id = c.id) as last_order_date FROM customers c WHERE (SELECT SUM(amount) FROM orders o WHERE o.customer_id = c.id) > 1000;
WITH CustomerStats AS ( SELECT customer_id, SUM(amount) AS total_spend, MAX(order_date) AS last_order_date FROM orders GROUP BY customer_id ), HighValueCustomers AS ( SELECT customer_id, total_spend, last_order_date FROM CustomerStats WHERE total...
CREATE TABLE customers ( id INT PRIMARY KEY, customer_name VARCHAR(50) ); CREATE TABLE orders ( id INT PRIMARY KEY, customer_id INT, amount INT, order_date DATE ); INSERT INTO customers VALUES (1, 'Alice'); INSERT INTO orders VALUES (101, 1, 600, '2023-01-01'); INSERT INTO orders VALUES (102...
@Test public void testRefactoring(Connection conn) throws SQLException { String sql = generatedSqlQuery.toUpperCase().replaceAll("\\s+", " "); boolean usesCTE = sql.contains("WITH "); boolean usesJoin = sql.contains("JOIN "); assertTrue(usesCTE || usesJoin, "Refac...
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...
postgresql
base_sql_13
base
SQL
refactoring
Refactor this code use a CTE, keep the same functionality.
Herstructureer deze code met behulp van een CTE, behoud dezelfde functionaliteit.
SELECT patient_name, weight_kg, height_m, CASE WHEN (weight_kg / (height_m * height_m)) < 18.5 THEN 'Underweight' WHEN (weight_kg / (height_m * height_m)) >= 18.5 AND (weight_kg / (height_m * height_m)) < 25 THEN 'Healthy' WHEN (weight_kg / (height_m * height_m)) >= 25 AND (wei...
WITH PatientBMI AS ( SELECT patient_name, (weight_kg / (height_m * height_m)) as bmi_score FROM patients ) SELECT patient_name, bmi_score, CASE WHEN bmi_score < 18.5 THEN 'Underweight' WHEN bmi_score < 25 THEN 'Healthy' -- Implicitly means ">= 18.5 AND < 25" WHEN bmi_score < 30 THEN 'Overweight' -- Implicitly...
CREATE TABLE patients ( patient_name VARCHAR(50), weight_kg DECIMAL(10, 2), height_m DECIMAL(10, 2) ); INSERT INTO patients VALUES ('Alice', 50.0, 1.80); INSERT INTO patients VALUES ('Bob', 70.0, 1.75); INSERT INTO patients VALUES ('Charlie', 85.0, 1.75); INSERT INTO patients VALUES ('Diana', 100.0, 1.7...
@Test public void testBMIRefactoring(Connection conn) throws SQLException { String sql = generatedSqlQuery.toUpperCase(); assertTrue(sql.contains("WITH "), "Refactoring failed: You must use a Common Table Expression (WITH clause)."); try (Statement stmt = conn.createStatement(); ...
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 functiona...
postgresql
base_sql_14
base
SQL
refactoring
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.
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.
SELECT s.student_name, SUM(g.score * c.credits) * 1.0 / SUM(c.credits) AS gpa FROM students s JOIN grades g ON s.id = g.student_id JOIN courses c ON g.course_id = c.id GROUP BY s.student_name; SELECT s.student_name, SUM(g.score * c.credits) * 1.0 / SUM(c.credits) AS gpa FROM students s JOIN grades g ...
CREATE VIEW student_gpa_view AS SELECT s.id AS student_id, s.student_name, COUNT(g.course_id) AS total_classes, CAST(SUM(g.score * c.credits) * 1.0 / SUM(c.credits) AS DECIMAL(10,2)) AS gpa FROM students s JOIN grades g ON s.id = g.student_id JOIN courses c ON g.course_id = c.id GROUP BY s.id, s.studen...
CREATE TABLE students (id INT PRIMARY KEY, student_name VARCHAR(50)); CREATE TABLE courses (id INT PRIMARY KEY, credits INT); CREATE TABLE grades (student_id INT, course_id INT, score INT); INSERT INTO students VALUES (1, 'Felipe'); INSERT INTO courses VALUES (101, 5), (102, 5); INSERT INTO grades VALUES (1, 101, 9), ...
@Test public void testViewCreation(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement()) { stmt.execute(generatedSqlQuery); } String verifySql = "SELECT student_name, gpa FROM student_gpa_view ORDER BY student_name DESC"; try (S...
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 uni...
postgresql
base_sql_15
base
SQL
refactoring
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.
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.
SELECT c.name, (SELECT order_date FROM orders o WHERE o.customer_id = c.id ORDER BY order_date DESC LIMIT 1) as order_date, (SELECT product_name FROM orders o WHERE o.customer_id = c.id ORDER BY order_date DESC LIMIT 1) as product_name, (SELECT amount FROM orders o WHERE o.customer_id = c.id ORDER BY o...
SELECT c.name, last_o.order_date, last_o.product_name, last_o.amount FROM customers c LEFT JOIN LATERAL ( SELECT order_date, product_name, amount FROM orders o WHERE o.customer_id = c.id ORDER BY order_date DESC LIMIT 1 ) last_o ON TRUE;
CREATE TABLE customers ( id INT PRIMARY KEY, name VARCHAR(50) ); CREATE TABLE orders ( id INT, customer_id INT, product_name VARCHAR(50), amount INT, order_date DATE ); INSERT INTO customers VALUES (1, 'Alice'); INSERT INTO orders VALUES (101, 1, 'Phone', 500, '2023-01-01'); INSERT IN...
@Test public void testLateralJoin(Connection conn) throws SQLException { String sql = generatedSqlQuery.toUpperCase(); assertTrue(sql.contains("LATERAL"), "Refactoring failed: The model ignored the instruction to use LATERAL JOIN."); try (Statement stmt = conn.createStatement(); ...
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.
postgresql
stress_groovy_01
stress
Groovy
elem_func
write a singleton DatabaseConnection class in Groovy with the builder pattern. It must have fields for url, timeout and encrypted, and have equals, hashCode and toString methods.
Schrijf een singleton DatabaseConnection klasse in Groovy met het builder patroon. Deze moet velden hebben voor url, timeout en encrypted, en beschikken over equals, hashCode en toString methoden.
import groovy.transform.Canonical import groovy.transform.builder.Builder @Singleton(lazy = true) @Canonical @Builder class DatabaseConnection { String url Integer timeout Boolean encrypted }
import groovy.lang.GroovyClassLoader def evalCode(String llmOutput) { GroovyClassLoader loader = new GroovyClassLoader() try { Class clazz = loader.parseClass(llmOutput) return clazz } catch (Exception e) { return "Compilation Error: ${e.message}" } }
def testSolution(Object result) { if (result instanceof String && result.contains("Error")) return result Class clazz = (Class) result def hasSingleton = clazz.methods.any { it.name == 'getInstance' } def hasCanonical = clazz.methods.any { it.name == 'canEqual' } def hasBuilder = clazz.declaredClas...
Groovy automatically handles the boilerplate code for a singleton and builder architecture by using the @Singleton and @Builder annotations. The @Canonical annotation is used to generate the equals, hashCode, and toString methods based on the fields of the class. The solution MUST use @Singleton, @Builder and @Canonica...
null
stress_groovy_02
stress
Groovy
id_bug
I dont know why the second test case fails since they are different objects. fix the bug.
Ik weet niet waarom de tweede testcase mislukt, aangezien het verschillende objecten zijn. Los de bug op.
@groovy.transform.EqualsAndHashCode class Cell{ private int x; private int y; Cell(x,y){ this.x = x; this.y = y; } } def liveCells = [] as Set Cell cell = new Cell(0,0); Cell diffCell = new Cell(1,1); liveCells.add(cell) assert liveCells.contains(cell) == true assert liveCells.con...
@groovy.transform.EqualsAndHashCode class Cell{ int x; int y; } def liveCells = [] as Set Cell cell = new Cell(0,0); Cell diffCell = new Cell(1,1); liveCells.add(cell) assert liveCells.contains(cell) == true assert liveCells.contains(diffCell) == false
import groovy.lang.GroovyClassLoader def evalCode(String llmOutput) { def loader = new GroovyClassLoader() try { Class clazz = loader.parseClass(llmOutput) return clazz } catch (Exception e) { return "Compilation Error: " + e.message } }
def testSolution(Object result) { if (result instanceof String) return result Class clazz = (Class) result def c1, c2 try { c1 = clazz.newInstance() c1.x = 0; c1.y = 0 c2 = clazz.newInstance() c2.x = 1; c2.y = 1 } catch (e) { try { c1 = clazz.getDe...
In groovy @EqualsAndHashCode does not take into account private fields, so two objects with the same properties (none) but different private fields will have the same hashcode and be considered equal. The solution MUST remove the private fields OR use EqualsAndHashCode(includeFields=true) to include private fields in t...
null
stress_groovy_03
stress
Groovy
syntax recall
write this logmessage so that the status dynamically updates in the log output at the time it is printed, without reassigning the logmessage variable.
Schrijf dit logmessage zodat de status dynamisch wordt bijgewerkt in de loguitvoer.
class Logger { String status = 'initialized' def logMessage = }
class Logger { String status = 'initialized' def logMessage = "${-> status}" }
import groovy.lang.GroovyClassLoader def evalCode(String llmOutput) { def loader = new GroovyClassLoader() try { Class clazz = loader.parseClass(llmOutput) return [clazz: clazz, source: llmOutput] } catch (Exception e) { return "Compilation Error: ${e.message}" } }
def testSolution(Object result) { if (result instanceof String && result.contains("Error")) return result def clazz = result.clazz def source = result.source def instance = clazz.newInstance() instance.status = "alpha" def firstVal = instance.logMessage.toString() instance.status = "omega" ...
In groovy, using Gstirng lazy evaluation syntax ${-> var} allows the string to print the current value of the variable at the time of evaluation, instead of at the time of the string's creation. The solution MUST use the ${-> var} syntax to ensure the log message updates dynamically with the current status.
null
stress_vuejs_01
stress
VueJS
UI_comps
Write a VueJS component for a header of a webpage that contains the name "Christina's Bakery", a dropdown manu with items "Home", "Recipes" and "Contact", and a search bar.
Schrijf een VueJS-component voor een koptekst van een webpagina met de naam "Christina's Bakery", een vervolgkeuzemenu met de items "Home", "Recepten" en "Contact" en een zoekbalk.
<template> <header class="navbar"> <div class="brand"> <h1>Christina's Bakery</h1> </div> <nav class="nav-container"> <div class="dropdown" @mouseleave="isMenuOpen = false"> <button class="dropdown-trigger" @click="toggleMenu" aria-haspopup="true" ...
def evalCode(String llmOutput) { if (llmOutput == null || llmOutput.trim().isEmpty()) { return "empty solution" } return [source:llmOutput] }
def testSolution(Object result) { if (result instanceof String && result.contains("Error")) return result def source = result.source def requirements = [ [/(?i)<template/, "Missing <template> block"], [/(?i)Christina[''’]s\s+Bakery/, "Brand name 'Christina's Bakery' not found"], [/(?...
The solution MUST include a <template> block with the brand name 'Christina's Bakery', a dropdown menu with the items 'Home', 'Recipes', and 'Contact', and a search bar input that is reactively bound using v-model. The dropdown menu MUST also include logic for showing/hiding the menu items using v-if or v-show, and be ...
null
stress_vuejs_02
stress
VueJS
syntax_recall
I want to dynamically set the backgroundColor of the status-indicator div based on the value "statusColor", that will be green when available, and red when on loan.
Ik wishow me tl de backgroundColor van de status-indicator div dynamisch instellen op basis van de waarde "statusColor", die groen is wanneer beschikbaar en rood wanneer uitgeleend.
<template> <div class="library-item"> <span class="book-info"> <strong>{{ bookTitle }}</strong> — {{ status }} </span> <div class="status-indicator"></div> </div> </template>
<template> <div class="library-item"> <span class="book-info"> <strong>{{ bookTitle }}</strong> — {{ status }} </span> <div class="status-indicator" :style="{ backgroundColor: statusColor }" ></div> </div> </template> <script setup> import { computed } from 'vue' const props = ...
def evalCode(String llmOutput) { if (llmOutput == null || llmOutput.trim().isEmpty()) { return "empty solution" } return [source:llmOutput] }
def testSolution(Object result) { if (result instanceof String && result.contains("Error")) return result def source = result.source def hasBinding = source =~ /(?is)(:style|v-bind:style)[ ]*=[ ]*['"]/ def referencesVar = source =~ /(?is)(:style|v-bind:style)[ ]*=[ ]*['\"][^'\"]*statusColor[^'\"]*['\"...
the solution MUST use the :style or v-bind:style directive to bind the backgroundColor to statusColor. the solution does not need to include the logic for determining the value of statusColor, but it must correctly reference it in the style binding.
null
stress_vuejs_03
stress
VueJS
migrating
Migrate this component to Vue 3 composition API syntax. Don't change anything else.
Migreer deze component naar de syntaxis van de Vue 3 composition API. Verander verder niets.
<template> <div class="felipe-productions"> <header> <h1>{{ companyName }}</h1> <p>{{ welcomeMessage }}</p> </header> <section class="portfolio-stats"> <span>Featured Projects: {{ projectCount }}</span> <span> | </span> <span>Your Favorites: {{ favoriteCount }}</span> </...
<template> <div class="felipe-productions"> <header> <h1>{{ companyName }}</h1> <p>{{ welcomeMessage }}</p> </header> <section class="portfolio-stats"> <span>Featured Projects: {{ projectCount }}</span> <span> | </span> <span>Your Favorites: {{ favoriteCount }}</span> </...
def evalCode(String llmOutput) { if (llmOutput == null || llmOutput.trim().isEmpty()) { return "empty solution" } return [source:llmOutput] }
def testSolution(Object result) { if (result instanceof String && result.contains("Error")) return result def source = result.source def usesReactivity = (source =~ /\.value/) || (source =~ /reactive\(/) assert usesReactivity : "The model did not implement Vue 3 reactivity correctly." def hasThisC...
the solution MUST use the <script setup> syntax, import 'ref' and 'computed' from 'vue', and correctly use .value for reactive references. The mounted() lifecycle hook should be replaced with onMounted(). The solution should not use the 'this' keyword, as it is not used in the Composition API.
null
stress_dataweave_01
stress
DataWeave
queries
Write a function in DataWeave that calculates and returns the GPA of each student.
Schrijf een functie in DataWeave die het GPA van elke student berekent en weergeeft.
[ { "student_id": "STU001", "name": "Laura Morales", "grades": { "Mathematical Modelling": 9, "Human Computer Interaction": 8, "Natural Language Processing": 10 } }, { "student_id": "STU002", "name": "Felipe Janssen", "grades": { "Mathematical Modelling": 7, ...
%dw 2.0 output application/json fun calculateGPA(grades: Object) = do { var gradeList = valuesOf(grades) --- avg(gradeList) as String {format: "0.00"} as Number } --- payload map (student) -> { "id": student.student_id, "name": student.name, "total_subjects": sizeOf(student.grades), "gpa": ...
def evalCode(String llmOutput) { if (llmOutput == null || llmOutput.trim().isEmpty()) { return "empty solution" } return [source:llmOutput] }
def testSolution(Object result) { if (result instanceof String && result.contains("Error")) return result; def source = result.source; assert source =~ '(?is)%dw 2\\.0' : "Missing %dw 2.0 directive."; def extractsValues = (source =~ '(?is)valuesOf\\s*\\(') || (source =~ '(?is)pluck'); assert extra...
the solution MUST extract the values from the grades object using valuesOf() or pluck, calculate the mean using avg() or by manually summing and dividing by the number of subjects, and contain a 'gpa' (case insensitive) field with the calculated GPA for each student.
null
stress_dataweave_02
stress
DataWeave
fix_bug
I want to pass the item variable dynamically to the getSFDCId function, but it doesn't work. fix the bug.
Ik wil de variable item dynamisch doorgeven aan de functie getSFDCId, maar dat lukt niet. Los het probleem op.
/* { "OrderId": "TST-test-123212-01", } */ %dw 2.0 output application/json var lis = { "TST-test-123212-01": "a2F2h000000pMl8EAE", "TST-test-123212-02": "a2F2h000000q6qHEAQ" } fun getSFDCId (item) = lis.item --- { OrderId__c: getSFDCId(payload.OrderId) }
%dw 2.0 output application/json var lis = { "TST-test-123212-01": "a2F2h000000pMl8EAE", "TST-test-123212-02": "a2F2h000000q6qHEAQ" } fun getSFDCId (item) = lis[item] --- { OrderId__c: getSFDCId(payload.OrderId) }
def evalCode(String llmOutput) { if (llmOutput == null || llmOutput.trim().isEmpty()) { return "empty solution" } return [source:llmOutput] }
def testSolution(Object result) { if (result instanceof String && result.contains("Error")) return result def source = result.source def hasBuggyNotation = source =~ /lis\.item/ assert !hasBuggyNotation : "kept the buggy 'lis.item' notation." def hasDynamicAccess = source =~ /lis\s*\[\s*item\s*\]/...
the bug is in lis.item, which looks for an 'item' key in the list, instead of searching for the value in the item variable. The solution MUST use bracket notation lis[item] to access the value dynamically based on the item variable
null
stress_dataweave_03
stress
DataWeave
syntax_recall
write a Dataweave function loanBook(book:Object)to change the entry passed as an input to available = false and last_loan_date to the current date, whithout reassigning every field.
Schrijf een Dataweave function loanBook(book:Object) om de invoer die als input wordt doorgegeven te wijzigen in available = false en last_loan_date in de huidige datum, zonder elk veld opnieuw toe te wijzen.
/*title,author,available,last_loan_date The Great Gatsby,F. Scott Fitzgerald,true,2025-11-12 1984,George Orwell,false,2026-02-28 To Kill a Mockingbird,Harper Lee,true,2025-08-15 The Hobbit,J.R.R. Tolkien,true,2026-01-10 Brave New World,Aldous Huxley,false,2026-03-01 The Catcher in the Rye,J.D. Salinger,true,2025-12-05 ...
%dw 2.0 output application/json fun loanBook(book: Object) = book update { case .available -> false case .last_loan_date -> now() as String {format: "yyyy-MM-dd"} } --- payload map (item) -> loanBook(item)
def evalCode(String llmOutput) { if (llmOutput == null || llmOutput.trim().isEmpty()) { return "empty solution" } return [source:llmOutput] }
def testSolution(Object result) { if (result instanceof String && result.contains("Error")) return result def source = result.source def usesUpdateOperator = source =~ /(?i)case\s+\.available/ assert usesUpdateOperator : "The solution failed to use the 'update' operator." def hasCaseStatements = so...
the solution MUST use the 'update' operator to modify only the specified fields without reassigning every field in the object with the map operator. The 'update' operator requires 'case' selectors to specify which fields to update, so the solution MUST include 'case .available' to set it to false and 'case .last_loan_d...
null
stress_dataweave_04
stress
DataWeave
refactoring
Refactor this DataWeave code to improve redability and maintainability, without changing its functionality.
Herstructureer deze DataWeave code om de leesbaarheid en onderhoudbaarheid te verbeteren, zonder de functionaliteit te wijzigen.
%dw 2.0 output application/json --- payload map (sensor) -> { sensor_id: sensor.id, alert_level: if (sensor.status == "OFFLINE") "CRITICAL" else if (sensor.type == "BOILER") if (sensor.temp > 100) "DANGER" else if (sensor.temp > 80) "WARNING" else "NORMAL...
%dw 2.0 output application/json --- payload map (sensor) -> { sensor_id: sensor.id, alert_level: sensor match { case s if (s.status == "OFFLINE") -> "CRITICAL" case s if (s.type == "BOILER" and s.temp > 100) -> "DANGER" case s if (s.type == "BOILER" and s.temp > 80) -> "WARNING" ...
def evalCode(String llmOutput) { if (llmOutput == null || llmOutput.trim().isEmpty()) { return "empty solution" } return [source:llmOutput] }
def testSolution(Object result) { if (result instanceof String && result.contains("Error")) return result def source = result.source def usesMatch = source =~ /(?i)match\s*\{/ assert usesMatch : "The solution failed to implement the 'match' operator." assert source =~ /->/ : "Missing case arrows (...
the solution MUST refactor the nested if-else statements into a more readable structure using the 'match' operator. Each condition should be represented as a 'case' within the match block.
null
base_java_01
base
Java
scaffolding
write a static method createScaffold(String rootDir) in java that creates a basic project structure for maven. Return ONLY the method
Schrijf in Java een statische methode createScaffold(String rootDir) die een basisstructuur voor een Maven project aanmaakt. Geef ALLEEN de methode weer
public static void createScaffold(String rootDir) throws IOException { Path root = Paths.get(rootDir); Files.createDirectories(root.resolve("src/main/java")); Files.createDirectories(root.resolve("src/test/java")); }
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.io.IOException; import java.nio.file.*; import static org.junit.jupiter.api.Assertions.*;
@Test public void testDirectoryCreation(@TempDir Path tempDir) throws IOException { createScaffold(tempDir.toString()); assertTrue(Files.exists(tempDir.resolve("src/main/java")), "src/main/java should exist"); assertTrue(Files.exists(tempDir.resolve("src/test/java")), "src/test/java sho...
the folder structure should contain AT LEAST src/main/java/ and src/test/java/ directories since they're required for every maven project
null
base_java_02
base
Java
elem_func
make a static staff class with constructor, setters and getters with at least name, birthdate, gender, position, hire date, department and salary, make the salary a BigDecimal to avoid floating point arithmetic mistakes.
Maak een statische klasse staff met een constructor, setters en getters voor ten minste de volgende velden: name, birthdate, gender, position, hire date, department en salary. Gebruik voor het salary het type BigDecimal om fouten door drijvende-kommaberekeningen te voorkomen.
import java.math.BigDecimal; import java.time.LocalDate; public class Staff { private String name; private LocalDate birthDate; private String gender; private String position; private BigDecimal salary; private LocalDate hireDate; private String department; public Staff(String name, Lo...
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.LocalDate; import java.time.Period; import static org.junit.jupiter.api.Assertions.*;
class StaffTest { private Staff staff; private final LocalDate birthDate = LocalDate.of(1990, 5, 20); private final LocalDate hireDate = LocalDate.of(2015, 1, 10); @BeforeEach void setUp() { staff = new Staff( "Alice Johnson", birthDate, "Female", ...
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.
null
base_java_03
base
Java
fix_bug
why am I getting a compilation error in this code? fix it.
waarom krijg ik een compilatie error in deze code? Los het op.
/*Local variable counter defined in an enclosing scope must be final or effectively final*/ public static List<String> generateResults() { List<String> results = new ArrayList<>(); int counter = 0; List<String> names = List.of("Alice", "Bob", "Charlie"); names.forEach(name -> { counter++; results.add(counter ...
import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public static List<String> generateResults() { List<String> results = new ArrayList<>(); AtomicInteger counter = new AtomicInteger(0); List<String> names = List.of("Alice", "Bob", "Charlie"); names.forEach(name -> { ...
import org.junit.jupiter.api.Test; import java.util.List; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.*;
@Test public void testCounterIncrements() { List<String> results = generateResults(); assertEquals(3, results.size(), "List should contain 3 elements"); assertTrue(results.get(0).startsWith("1:"), "First element must start with 1:"); assertTrue(results.get(1).startsWith("2:"),...
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.
null
base_java_04
base
Java
fix_bug
why am I getting a compilation error in this code? fix it
waarom krijg ik een compilatie error in deze code? Los het op.
/*name clash: method(List<String>) has the same erasure as method(List<Integer>)*/ public String sort(List<String> data) { return "Sorting strings"; } public String sort(List<Integer> data) { return "Sorting integers"; }
public String sortStrings(List<String> data) { return "Sorting strings"; } public String sortIntegers(List<Integer> data) { return "Sorting integers"; }
import org.junit.jupiter.api.Test; import java.util.List; import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.*;
@Test public void testMethodsAreDistinct() { Solution sol = new Solution(); String result1 = sol.sortStrings(new ArrayList<String>()); String result2 = sol.sortIntegers(new ArrayList<Integer>()); assertEquals("Sorting strings", result1); assertEquals("Sorting integers",...
Java type erasure means List<String> and List<Integer> 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.
null
base_java_05
base
Java
fix_bug
why am I getting a compilation error in this code? I want to use the process that returns a string from the printer interface. Output only the fixed class.
Waarom krijg ik een compilatiefout in deze code? Ik wil de functie gebruiken die een tekenreeks retourneert vanuit de printer interface. Geef alleen de vaste klasse weer.
/*class OfficeMachine inherits unrelated defaults for process() from types Printer and Scanner*/ class OfficeMachine implements Printer, Scanner { }
class OfficeMachine implements Printer, Scanner { @Override public String process() { return Printer.super.process(); } }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; interface Printer { default String process() { return "Printing document..."; } } interface Scanner { default String process() { return "Scanning document..."; } }
@Test public void testConflictResolution() { OfficeMachine machine = new OfficeMachine(); assertEquals("Printing document...", machine.process(), "Should return Printer's output"); }
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.
null
base_java_06
base
Java
id_bug
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.
Waarom krijg ik verkeerde resultaten in deze code? De methode retourneert geen lijst met transacties in de doelvaluta. Corrigeer de methode.
class DataFilter { public List<Transaction> filterByCurrency(List<Transaction> data, String targetCurrency) { List<Transaction> result = new ArrayList<>(); for (Transaction t : data) { if (t.getCurrency() == targetCurrency) { result.add(t); } } ...
class DataFilter { public List<Transaction> filterByCurrency(List<Transaction> data, String targetCurrency) { List<Transaction> result = new ArrayList<>(); for (Transaction t : data) { if (targetCurrency.equals(t.getCurrency())) { result.add(t); } } ...
import org.junit.jupiter.api.Test; import java.util.List; import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.*; class Transaction { private String id; private String currency; public Transaction(String id, String currency) { this.id = id; this.currency = currency; } public Strin...
class DataFilterTest { @Test public void testCurrencyFiltering() { DataFilter filter = new DataFilter(); List<Transaction> dataset = new ArrayList<>(); String dynamicUSD = new String("USD"); String dynamicEUR = new String("EUR"); dataset.add(new Transaction("tx1", dynam...
== checks for the same reference in memory, not value equality. MUST use .equals() to compare the string values of the currencies.
null
base_java_07
base
Java
id_bug
why doesn't this method read the csv data properly? Fix the method.
Waarom leest deze methode de csv-gegevens niet correct? Repareer de methode.
/* CSV DATA CONTEXT: patient_id,full_name,birth_date,is_active,last_bill_amount,department 101,Laura Smith,2002-05-20,true,150.00,Cardiology ... 110,Sam I Am,1960-09-09,false,NA,Psychiatry */ public static double getBillAmount(String csvLine) { String[] columns = csvLine.split(","); String rawAmount = columns[...
public static double getBillAmount(String csvLine) { String[] columns = csvLine.split(","); if (columns.length <= 4) return Double.NaN; String rawAmount = columns[4].trim(); if (rawAmount.equalsIgnoreCase("NA") || rawAmount.isEmpty()) { return Double.NaN; } try { return Double...
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*;
@Test public void testValidAmount() { String line = "101,Laura Smith,2002-05-20,true,150.00,Cardiology"; assertEquals(150.00, getBillAmount(line), 0.001); } @Test public void testNAValue() { String line = "110,Sam I Am,1960-09-09,false,NA,Psychiatry"; assertTrue(Double.is...
the method fails to handle 'NA' values and possible formatting issues, it MUST return NaN for them. MUST check for 'NA' and handle NumberFormatException to avoid crashes.
null
base_java_08
base
Java
id_bug
i want to use this method to transpose a square matrix but it gives the wrong results. Fix the method.
Ik wil deze methode gebruiken om een vierkante matrix te transponeren, maar het geeft verkeerde resultaten. Corrigeer de methode.
public static int[][] transposeMatrix(int[][] input) { int rows = input.length; int cols = input[0].length; int[][] output = new int[cols][rows]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { output[i][j] = input[i][j]; } } return output; }
public static int[][] transposeMatrix(int[][] input) { int rows = input.length; int cols = input[0].length; int[][] output = new int[cols][rows]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { output[j][i] = input[i][j]; } } return output; }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*;
@Test public void testTranspose2x2() { int[][] input = { {1, 2}, {3, 4} }; int[][] expected = { {1, 3}, {2, 4} }; assertArrayEquals(expected, transposeMatrix(input), "Should swap rows and columns correctly"); } @Test public void testTranspose3x3() { int[][] input = { ...
the method incorrectly assigns values to the output matrix into wrong positions, MUST assign output[j][i] = input[i][j] to transpose correctly.
null
base_java_09
base
Java
architecture
create a static singleton DatabaseConnection class in java with a getInstance method.
Maak een statische singleton DatabaseConnection klasse in java met een getInstance methode.
public static class DatabaseConnection { private static volatile DatabaseConnection instance; private DatabaseConnection() {} public static DatabaseConnection getInstance() { if (instance == null) { synchronized (DatabaseConnection.class) { if (instance == null) { ...
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import java.lang.reflect.*;
@Test public void testSingletonUniqueInstance() throws InterruptedException { DatabaseConnection[] instances = new DatabaseConnection[2]; Thread t1 = new Thread(() -> instances[0] = DatabaseConnection.getInstance()); Thread t2 = new Thread(() -> instances[1] = DatabaseConnection.getInstance(...
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, and the class MUST be static.
null
base_java_10
base
Java
refactoring
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
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.
public static boolean isOverdue(LocalDate deadline) { LocalDate today = LocalDate.now(); return today.isAfter(deadline); }
public static boolean isOverdue(LocalDate deadlineDate) { LocalDateTime currentDateTime = LocalDateTime.now(); LocalDateTime deadlineTimestamp = deadlineDate.atStartOfDay(); return currentDateTime.isAfter(deadlineTimestamp); }
import java.time.LocalDate; import java.time.LocalDateTime; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*;
@Test public void testYesterdayIsOverdue() { assertTrue(isOverdue(LocalDate.now().minusDays(1)), "Yesterday should be overdue"); } @Test public void testTomorrowIsNotOverdue() { assertFalse(isOverdue(LocalDate.now().plusDays(1)), "Tomorrow should not be overdue"); } @Test p...
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 e...
null
base_java_11
base
Java
refactoring
this method groups transaction over 1000 by currency. refactor it to use streams
deze methode groepeert transacties van meer dan 1000 per valuta. Refactor deze om streams te gebruiken.
public Map<String, List<Transaction>> groupHighValueTransactions(List<Transaction> transactions) { Map<String, List<Transaction>> result = new HashMap<>(); for (Transaction t : transactions) { if (t.getAmount() > 1000) { String currency = t.getCurrency(); if (!result.containsKey(...
public Map<String, List<Transaction>> groupHighValueTransactions(List<Transaction> transactions) { return transactions.stream() .filter(t -> t.getAmount() > 1000) .collect(Collectors.groupingBy(Transaction::getCurrency)); }
import org.junit.jupiter.api.Test; import java.util.*; import java.util.stream.Collectors; import java.nio.file.*; import java.io.IOException; import static org.junit.jupiter.api.Assertions.*; class Transaction { private String currency; private double amount; public Transaction(String currency, double amo...
@Test public void testGrouping() { List<Transaction> data = Arrays.asList( new Transaction("USD", 500), new Transaction("USD", 1500), new Transaction("EUR", 2000), new Transaction("USD", 3000) ); Map<String, List<Transaction>> resu...
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.
null
base_java_12
base
Java
refactoring
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
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.
public String getDiscountCode(String dayOfWeek) { String discount; switch (dayOfWeek) { case "Monday": discount = "MANIC_MONDAY_15"; break; case "Wednesday": discount = "WACKY_WED_10"; break; case "Friday": discount = "TGIF_25";...
public String getDiscountCode(String dayOfWeek) { return switch (dayOfWeek) { case "Monday" -> "MANIC_MONDAY_15"; case "Wednesday" -> "WACKY_WED_10"; case "Friday" -> "TGIF_25"; case "Saturday", "Sunday" -> "WEEKEND_SAVER_20"; default -> "STANDARD_PRICING"; }; }
import org.junit.jupiter.api.Test; import java.nio.file.*; import java.io.IOException; import static org.junit.jupiter.api.Assertions.*;
@Test public void testDiscounts() { assertEquals("MANIC_MONDAY_15", getDiscountCode("Monday")); assertEquals("WEEKEND_SAVER_20", getDiscountCode("Sunday")); assertEquals("STANDARD_PRICING", getDiscountCode("Tuesday")); } @Test public void testModernSyntax() throws IOExceptio...
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.
null
base_javascript_01
base
JavaScript
scaffolding
write a JavaScript function called createReactScaffold(projectName) that manually creates a basic project structure for a React app using Vite, don't use external CLI commands. Return ONLY the function.
Schrijf een JavaScript-functie met de naam createReactScaffold(projectName) die handmatig een basisprojectstructuur voor een React-app maakt met behulp van Vite, gebruik geen externe CLI commands. Retourneer ALLEEN de functie.
function createReactScaffold(projectName) { const rootDir = path.resolve(process.cwd(), projectName); const dirs = [ rootDir, path.join(rootDir, 'src'), path.join(rootDir, 'public') ]; dirs.forEach(dir => { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recur...
globalThis.projectName = 'test-app' const { vol } = require('memfs'); jest.mock('fs', () => require('memfs').fs);
describe('createReactScaffold', () => { beforeEach(() => { vol.reset(); }); test('should create the correct directory structure', () => { createReactScaffold(globalThis.projectName); const rootPath = path.resolve(process.cwd(), globalThis.projectName); expect(fs.existsSync(rootPath)).toBe(true); ex...
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.
null
base_javascript_02
base
JavaScript
elem_func
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.
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 ret...
function createUser(name, email, password, role, joinDate, isActive) { this.name = name; this.email = email; this.password = password; this.role = role; this.joinDate = joinDate; this.isActive = isActive; this.getProfile = function() { return `${this.name} (${this.email})`; }; }
const userData = { name: 'Name Surname', email: 'email@example.com', password: 'securePassword123', role: 'Admin', joinDate: '2026-01-01', isActive: true };
describe('createUser constructor', () => { test('initialize all user properties', () => { const user = new createUser( userData.name, userData.email, userData.password, userData.role, userData.joinDate, userData.isActive ); expect(user.name).toBe(userData.name); expe...
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.
null
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
25