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.*;

public class ScaffoldTest {

    @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 should exist");
        assertTrue(Files.isDirectory(tempDir.resolve("src/main/java")), "Should be a directory");
    }
}

the folder structure should contain AT LEAST src/main/java/ and src/test/java/ directories since they're required for every maven project


make a staff class with constructor, setters and getters with at least name, birthdate, gender, position, salary, hire date, and department. Don't include imports

maak een staff class met constructor, setters en getters met ten minste name, birthdate, gender, position, salary, hire date en department. Voeg geen imports toe.

public class Staff {
    private String name;
    private java.time.LocalDate birthDate;
    private String gender;
    private String position;
    private double salary;
    private java.time.LocalDate hireDate;
    private String department;

    public Staff(String name, java.time.LocalDate birthDate, String gender, String position, double salary, java.time.LocalDate hireDate, String department) {
        this.name = name;
        this.birthDate = birthDate;
        this.gender = gender;
        this.position = position;
        this.salary = salary;
        this.hireDate = hireDate;
        this.department = department;
    }
    // ... Getters and Setters omitted for brevity in this view, but include them in real JSON ...
}

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", "Data Scientist", 75000.00, hireDate, "R&D");
    }

    @Test
    void testConstructorAndGetters() {
        assertEquals("Alice Johnson", staff.getName());
    }
    // ... other tests ...
}

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).


why am I getting a compilation error in this code? fix it and don't include imports

waarom krijg ik een compilatie error in deze code? Los het op en voeg geen imports toe.

/*Local variable counter defined in an enclosing scope must be final or effectively final*/
List<String> results = new ArrayList<>();
int counter = 0;
List<String> names = List.of("Alice", "Bob", "Charlie");

names.forEach(name -> {
    counter++;
    results.add(counter + ": " + name);
});

List<String> results = new ArrayList<>();
AtomicInteger counter = new AtomicInteger(0);
List<String> names = List.of("Alice", "Bob", "Charlie");

names.forEach(name -> {
    results.add(counter.incrementAndGet() + ": " + 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.*;

class LambdaTest {
       private List<String> generateResults() {

return results;
    }

    @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:"), "Second element must start with 2:");
        assertTrue(results.get(2).startsWith("3:"), "Third element must start with 3:");
    }
}

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.


/*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.*;

public class Solution {

@Test
    public void testMethodsAreDistinct() {
        String result1 = sortStrings(new ArrayList<String>());
        String result2 = sortIntegers(new ArrayList<Integer>());

        assertEquals("Sorting strings", result1);
        assertEquals("Sorting integers", result2);
    }
}

java compiles List<Integer> and List<String> to the same type List, so can't overload the method. SOlution MUST rename the methods to have distinct names.


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*/
public class OfficeMachine implements Printer, Scanner {

}

public 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..."; }
}

class DiamondProblemTest {
    @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.


why am i getting wrong results in this code? The method doesn't return a list of the transaction in the target currency. Fix the method and don't include imports

Waarom krijg ik verkeerde resultaten in deze code? De methode retourneert geen lijst met transacties in de doelvaluta. Corrigeer de methode en neem geen imports op.

public 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);
}
}
return result;
}

public 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);
}
}
return result;
}
}

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 String getCurrency() { return currency; }
}

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", dynamicUSD));
        dataset.add(new Transaction("tx2", dynamicEUR));
        dataset.add(new Transaction("tx3", dynamicUSD));

        List<Transaction> result = filter.filterByCurrency(dataset, "USD");

        assertEquals(2, result.size(), "Should find 2 USD transactions even if memory addresses differ");
    }
}

== checks for the same reference in memory, not value equality. MUST use .equals() to compare the string values of the currencies.


why doesn't this method read the csv data properly? Fix the method and don't include imports

Waarom leest deze methode de csv-gegevens niet correct? Repareer de methode en neem geen imports op.

/*
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[4];
    return Double.parseDouble(rawAmount);
}

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.parseDouble(rawAmount);
    } catch (NumberFormatException e) {
        return Double.NaN;
    }
}

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class Solution {

@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.isNaN(getBillAmount(line)), "NA should return NaN, not throw exception");
    }

    @Test
    public void testGarbageValue() {
        String line = "105,Big Mike,1978-06-30,0,FREE,Emergency";
        assertTrue(Double.isNaN(getBillAmount(line)), "Invalid text should return NaN");
    }
}

the method fails to handle 'NA' values and possible formatting issues. MUST check for 'NA' and handle NumberFormatException to avoid crashes.


i want to use this method to transpose a square matrix but it gives the wrong results. Fix the method and don't include imports

Ik wil deze methode gebruiken om een vierkante matrix te transponeren, maar het geeft verkeerde resultaten. Corrigeer de methode en neem geen imports op.

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.*;
import java.util.Arrays;

public class Solution {

    @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 = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        int[][] expected = {
            {1, 4, 7},
            {2, 5, 8},
            {3, 6, 9}
        };
        assertArrayEquals(expected, transposeMatrix(input));
    }
}

the method incorrectly assigns values to the output matrix into wrong positions, MUST assign output[j][i] = input[i][j] to transpose correctly.


create a singleton DatabaseConnection class in java with a getInstance method. Don't include imports

Maak een singleton DatabaseConnection klasse in java met een getInstance methode. Voeg geen imports toe.

public class DatabaseConnection {
private static volatile DatabaseConnection instance;
private DatabaseConnection() {
System.out.println("Connecting to Database... Success.");
}
    public static DatabaseConnection getInstance() {
if (instance == null) {
synchronized (DatabaseConnection.class) {
if (instance == null) {
instance = new DatabaseConnection();
}
}
}
return instance;
}
}

import static org.junit.Assert.*;
import java.lang.reflect.*;

DatabaseConnection i1 = DatabaseConnection.getInstance();
DatabaseConnection i2 = DatabaseConnection.getInstance();
assertNotNull(i1);
assertSame(i1, i2);

Constructor<DatabaseConnection> constructor = DatabaseConnection.class.getDeclaredConstructor();
assertTrue(Modifier.isPrivate(constructor.getModifiers()));

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.


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.*;

public class DateTest {

@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
    public void testTodayIsOverdue() {
assertTrue(isOverdue(LocalDate.now()), "Today (current time) should be considered after Today (start of day)");
    }
}

the original method ignores time of day so assignments due on the same day are not overdue, the solution MUST set the deadline to the start of the day and compare with current date and time, so that assignemnts due on the same day are overdue. The unit test includes structural checks (as well as functional checks) to ensure refactoring.


this method groups transaction over 1000 by currency. refactor it to use streams and dont include imports

deze methode groepeert transacties van meer dan 1000 per valuta. Refactor deze om streams te gebruiken en neem geen imports op.

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(currency)) {
result.put(currency, new ArrayList<>());
}
result.get(currency).add(t);
}
}
return result;
}

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 amount) {
        this.currency = currency;
        this.amount = amount;
    }
    public String getCurrency() { return currency; }
    public double getAmount() { return amount; }
}

public class Solution {

    @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>> result = groupHighValueTransactions(data);

        assertEquals(2, result.size());
        assertEquals(2, result.get("USD").size());
    }

    @Test
    public void testRefactoringCompliance() throws IOException {

        String source = Files.readString(Path.of("Solution.java"));

        assertTrue(source.contains(".stream("), "LLM failed to use Stream API");
        assertTrue(source.contains(".collect("), "LLM failed to use Collector");
        assertFalse(source.contains("for ("), "LLM failed to remove 'for' loop");
    }
}

RUNNER MUST SAVE SOLUTION IN Solution.java Includes a structural check to ensure the LLM actually followed the instruction to use Streams. The unit test includes structural checks (as well as functional checks) to ensure refactoring.


This is a method that returns a discount code based on the day of the week, refactor the method to use a modern switch expression. Keep the same functionality and don't include imports

Dit is een methode die een kortingscode retourneert op basis van de dag van de week. Herstructureer de methode om een moderne switch-expressie te gebruiken. Behoud dezelfde functionaliteit en neem geen imports op.

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";
break;
case "Saturday":
case "Sunday":
discount = "WEEKEND_SAVER_20";
break;
default:
discount = "STANDARD_PRICING";
break;
}
return discount;
}

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.*;

public class Solution {

    @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 IOException {
        String source = Files.readString(Path.of("Solution.java"));

        assertTrue(source.contains("->"), "LLM failed to use modern arrow syntax '->'");
        assertFalse(source.contains("break;"), "LLM failed to remove legacy 'break' statements");
    }
}

RUNNER MUST SAVE SOLUTION IN Solution.java the old method uses the old switch statement with multiple breaks and variable assignments, the solution MUST use the modern switch expression syntax introduced in Java 14 while keeping the same functionality. The unit test includes structural checks (as well as functional checks) to ensure refactoring.


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.

const fs = require('fs');
const path = require('path');
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, { recursive: true });
}
});
const indexHtml = `<!doctype html>

<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>

`;
const packageJson = {
name: projectName,
private: true,
version: '0.0.0',
type: 'module',
scripts: {
dev: 'vite',
build: 'vite build',
lint: 'eslint .',
preview: 'vite preview'
},
dependencies: {
react: '^18.2.0',
'react-dom': '^18.2.0'
},
devDependencies: {
'@types/react': '^18.2.0',
'@types/react-dom': '^18.2.0',
'@vitejs/plugin-react': '^4.2.0',
vite: '^5.0.0'
}
};
const viteConfig = `import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
})`;
const mainJsx = `import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)`;
const appJsx = `import { useState } from 'react'
import './App.css'
function App() {
const [count, setCount] = useState(0)
return (
<>

Vite + React

<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>

</>
)
}
export default App`;
const files = [
{ path: path.join(rootDir, 'index.html'), content: indexHtml },
{ path: path.join(rootDir, 'package.json'), content: JSON.stringify(packageJson, null, 2) },
{ path: path.join(rootDir, 'vite.config.js'), content: viteConfig },
{ path: path.join(rootDir, '.gitignore'), content: 'node_modules
dist
.env' },
{ path: path.join(rootDir, 'src', 'main.jsx'), content: mainJsx },
{ path: path.join(rootDir, 'src', 'App.jsx'), content: appJsx },
{ path: path.join(rootDir, 'src', 'App.css'), content: '/* App styles */' },
{ path: path.join(rootDir, 'src', 'index.css'), content: '/* Global styles */' },
{ path: path.join(rootDir, 'public', 'vite.svg'), content: '<svg></svg>' }
];
files.forEach(file => {
fs.writeFileSync(file.path, file.content.trim());
});
console.log(`React Vite project created at ${rootDir}`);
}


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",
        base_path / "gradle/wrapper"
    ]

    files = {
        base_path / "settings.gradle.kts": f'rootProject.name = "{project_name}"\n',
        base_path / "build.gradle.kts": """plugins {
    kotlin("jvm") version "1.9.22"
}
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
    mavenCentral()
}
dependencies {
    testImplementation(kotlin("test"))
}
tasks.test {
    useJUnitPlatform()
}
""",
        base_path / ".gitignore": """
.gradle/
build/
out/
.idea/
*.iml
.DS_Store
""",
        base_path / "README.md": f"# {project_name}\n\nGenerated Kotlin/Gradle Project.",
        base_path / "gradle/wrapper/gradle-wrapper.properties": """distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
"""
    }

    print(f"Creating Kotlin/Gradle scaffold for '{project_name}'...")
    for d in directories:
        d.mkdir(parents=True, exist_ok=True)

    for path, content in files.items():
        path.write_text(content, encoding="utf-8")

    print(f"Project created at {base_path.resolve()}")

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)

        base = Path(self.test_dir) / project_name

        required_dirs = [
            "src/main/kotlin",
            "src/test/kotlin",
            "gradle/wrapper"
        ]
        for d in required_dirs:
            self.assertTrue((base / d).exists(), f"Directory missing: {d}")
            self.assertTrue((base / d).is_dir(), f"Path is not a directory: {d}")

        required_files = [
            "build.gradle.kts",
            "settings.gradle.kts",
            ".gitignore"
        ]
        for f in required_files:
            self.assertTrue((base / f).exists(), f"File missing: {f}")

        settings_content = (base / "settings.gradle.kts").read_text()
        self.assertIn(f'rootProject.name = "{project_name}"', settings_content, "settings.gradle.kts has wrong project name")

if __name__ == '__main__':
    unittest.main()

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.


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 = {
        base / "index.html": """<!DOCTYPE html>

""",
        base / "vite.config.js": """import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})""",
        base / "package.json": f"""{{
  "name": "{project_name}",
  "version": "0.0.0",
  "scripts": {{
    "dev": "vite",
    "build": "vite build"
  }},
  "dependencies": {{
    "vue": "^3.4.0",
    "pinia": "^2.1.0",
    "vue-router": "^4.2.0"
  }},
  "devDependencies": {{
    "@vitejs/plugin-vue": "^5.0.0",
    "vite": "^5.0.0"
  }}
}}""",
        src / "main.js": """import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')
""",
        src / "App.vue": """
<template>

      <RouterLink to="/">Home</RouterLink>
      <RouterLink to="/about">About</RouterLink>

  <RouterView />
</template>
"""
    }

    # Execution
    print(f"Scaffolding Vue project: {project_name}")
    for d in dirs:
        d.mkdir(parents=True, exist_ok=True)

    for path, content in files.items():
        path.write_text(content, encoding="utf-8")

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):
        project_name = "frontend-app"
        create_vue_scaffold(project_name)

        base = Path(project_name)

        self.assertTrue((base / "src/components").is_dir(), "Missing src/components")
        self.assertTrue((base / "src/views").is_dir(), "Missing src/views")
        self.assertTrue((base / "public").is_dir(), "Missing public folder")

        # Check vital files
        self.assertTrue((base / "vite.config.js").exists(), "Missing vite.config.js")
        self.assertTrue((base / "package.json").exists(), "Missing package.json")
        self.assertTrue((base / "src/App.vue").exists(), "Missing App.vue")

        pkg_json = (base / "package.json").read_text()
        self.assertIn('"name": "frontend-app"', pkg_json, "package.json name not set correctly")

if __name__ == '__main__':
    unittest.main()

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.


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 patiëntklasse in Python met de velden patient_id (int), first_name (str), last_name (str), birth_date (str in YYYY-MM-DD-formaat), is_active (bool), gp_id (int), zip_code (str), met pythonic setters, getters en constructor.

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_active = is_active
        self._gp_id = gp_id
        self._zip_code = zip_code

    @property
    def patient_id(self):
        return self._patient_id

    @patient_id.setter
    def patient_id(self, value):
        self._patient_id = value

    @property
    def first_name(self):
        return self._first_name

    @first_name.setter
    def first_name(self, value):
        self._first_name = value

    @property
    def last_name(self):
        return self._last_name

    @last_name.setter
    def last_name(self, value):
        self._last_name = value

    @property
    def birth_date(self):
        return self._birth_date

    @birth_date.setter
    def birth_date(self, value):
        self._birth_date = value

    @property
    def is_active(self):
        return self._is_active

    @is_active.setter
    def is_active(self, value):
        self._is_active = value

    @property
    def gp_id(self):
        return self._gp_id

    @gp_id.setter
    def gp_id(self, value):
        self._gp_id = value

    @property
    def zip_code(self):
        return self._zip_code

    @zip_code.setter
    def zip_code(self, value):
        self._zip_code = value

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"
        self.assertEqual(p.first_name, "Jane", "Property setter failed for first_name")

        p.is_active = False
        self.assertFalse(p.is_active, "Property setter failed for is_active")

        self.assertTrue(isinstance(Patient.first_name, property), "Field 'first_name' must use @property decorator")
        self.assertTrue(isinstance(Patient.gp_id, property), "Field 'gp_id' must use @property decorator")
        self.assertTrue(isinstance(Patient.zip_code, property), "Field 'zip_code' must use @property decorator")

if __name__ == '__main__':
    unittest.main()

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.


write a class Transaction with fields transaction_id (int), user_id (int), amount (float), currency (str), timestamp (str in ISO 8601 format), status (bool), and pythonic setters, getters and constructor.

Schrijf een klasse Transaction met velden transaction_id (int), user_id (int), amount (float), currency (str), timestamp (str in ISO 8601-formaat), status (bool) en pythonic setters, getters en constructor.

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 = timestamp
        self.status = status
    @property
    def transaction_id(self) -> int:
        return self._transaction_id
    @transaction_id.setter
    def transaction_id(self, value: int):
        if not isinstance(value, int):
            raise TypeError("Transaction ID must be an integer")
        self._transaction_id = value
    @property
    def user_id(self) -> int:
        return self._user_id
    @user_id.setter
    def user_id(self, value: int):
        if not isinstance(value, int):
            raise TypeError("User ID must be an integer")
        self._user_id = value
    @property
    def amount(self) -> float:
        return self._amount
    @amount.setter
    def amount(self, value: float):
        if not isinstance(value, (int, float)):
            raise TypeError("Amount must be a number")
        if value < 0:
            raise ValueError("Amount cannot be negative")
        self._amount = float(value)
    @property
    def currency(self) -> str:
        return self._currency
    @currency.setter
    def currency(self, value: str):
        if not isinstance(value, str):
            raise TypeError("Currency must be a string")
        if len(value) != 3:
            raise ValueError("Currency must be a 3-letter ISO code (e.g., 'USD')")
        self._currency = value.upper()
    @property
    def timestamp(self) -> str:
        return self._timestamp
    @timestamp.setter
    def timestamp(self, value: str):
        if not isinstance(value, str):
            raise TypeError("Timestamp must be a string (ISO 8601)")
        self._timestamp = value
    @property
    def status(self) -> bool:
        return self._status
    @status.setter
    def status(self, value: bool):
        if not isinstance(value, bool):
            raise TypeError("Status must be a boolean")
        self._status = value
    def __repr__(self):
        return (f"Transaction(id={self.transaction_id}, user={self.user_id}, "
                f"amount={self.amount} {self.currency}, status={self.status})")

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.50)
        t.status = False
        self.assertFalse(t.status)

        # 3. Meta-Test: Verify @property usage
        self.assertTrue(isinstance(Transaction.amount, property), "Field 'amount' is not a @property")
        self.assertTrue(isinstance(Transaction.transaction_id, property), "Field 'transaction_id' is not a @property")

if __name__ == '__main__':
    unittest.main()

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.


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.DataFrame(data)

        result = clean_transactions(df)

        self.assertFalse((result['amount'] < 0).any(), "Negative amounts should be removed.")
        self.assertEqual(len(result), 3, "Row count mismatch. Did you filter negative amounts?")

        cat_val = result.loc[result['id'] == 3, 'category'].values[0]
        self.assertEqual(cat_val, 'Unknown', "NaN category should be replaced with 'Unknown'.")

        risk_amount = result.loc[result['id'] == 4, 'amount'].values[0]
        self.assertEqual(risk_amount, 1000.0, "High risk transactions (>0.9) must be capped at 1000. Did you use .loc?")

if __name__ == '__main__':
    unittest.main()

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.


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 isinstance(data, list):
        for item in data:
            extract_all_values(item, target_key, results)
    return results

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_values(value, target_key, results)
    elif isinstance(data, list):
        for item in data:
            extract_all_values(item, target_key, results)
    return results

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}
        res2 = extract_all_values(data2, 'id')

        self.assertEqual(res2, [999], f"Memory Leak Detected! Expected [999] but got {res2}. Did you remove the mutable default argument?")

if __name__ == '__main__':
    unittest.main()

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.


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": time.strftime("%H:%M:%S")
        }
        report.append(entry)
    return report

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_score = score
            status = "Ranked"
        entry = {
            "player_id": player["id"],
            "username": player["username"],
            "score": final_score,
            "status": status,
            "processed_at": time.strftime("%H:%M:%S")
        }
        report.append(entry)
    return report

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, scores)

        self.assertEqual(len(report), 3, f"Data Loss! Expected 3 players, got {len(report)}. zip() drops items if lists are unequal.")

        bob_entry = next((r for r in report if r['username'] == 'Bob'), None)
        self.assertIsNotNone(bob_entry, "Bob is missing from the report")
        self.assertTrue(bob_entry['score'] == 0 or bob_entry['score'] is None, "Bob should have a default score (0 or None)")

if __name__ == '__main__':
    unittest.main()

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.


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

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.assertEqual(calculate_average([-1, -2, -3]), 0, "No positive numbers should return 0")

if __name__ == '__main__':
    unittest.main()

the return statement is too indented and executes in the first iteration the loop. the solution MUST unindent the return statement.


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 do not match expected frequencies")

    def test_empty(self):
        self.assertEqual(count_word_frequencies([]), {}, "Empty list should return empty dict")

if __name__ == '__main__':
    unittest.main()

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.


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_word.lower())
    return total_count

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 = count_word_occurrences(self.tf.name, "python")
        except UnicodeDecodeError:
            self.fail("Function crashed on non-UTF-8 file! Did you handle encoding errors?")

        self.assertEqual(count, 1, "Failed to count words in the problematic file")

if __name__ == '__main__':
    unittest.main()

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.


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):
        vegan_badge = " (vegan)" if bool(pi.Vegan_Pizza) else ""
        vegetarian_badge = " (vegetarian)" if bool(pi.Vegetarian_Pizza) else ""

        # Note: calculate_price is assumed to exist externally
        print(f"{pi.Pizza_ID} | {pi.Pizza_Name}{vegan_badge}{vegetarian_badge}.......... ")

    print("Pizzas:")
    for pi in pizzas:
        line_pizza(pi)
    print("----------")

    print("Drinks:")
    for mi in items[10:20]:
        line_item(mi)
    print("----------")

    print("Desserts:")
    for mi in items[20:30]:
        line_item(mi)

    continue_message(session)

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_pizza

session.execute.reset_mock()
get_items(session)
args_items, _ = session.execute.call_args
sql_items = str(args_items[0]).replace('\n', ' ').strip()

assert "Item_ID" in sql_items
assert "Item_Name" in sql_items
assert "Item_Price" in sql_items
assert "FROM Items" in sql_items

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


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 classes terug

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 get_description(self):
        return self._pizza.get_description() + ", Pepperoni"
    def get_cost(self):
        return self._pizza.get_cost() + 1.50
class Mozzarella(ToppingDecorator):
    def get_description(self):
        return self._pizza.get_description() + ", Mozzarella"
    def get_cost(self):
        return self._pizza.get_cost() + 1.00
class Mushrooms(ToppingDecorator):
    def get_description(self):
        return self._pizza.get_description() + ", Mushrooms"
    def get_cost(self):
        return self._pizza.get_cost() + 0.75
class Tuna(ToppingDecorator):
    def get_description(self):
        return self._pizza.get_description() + ", Tuna"
    def get_cost(self):
        return self._pizza.get_cost() + 2.00
class Olives(ToppingDecorator):
    def get_description(self):
        return self._pizza.get_description() + ", Olives"
    def get_cost(self):
        return self._pizza.get_cost() + 0.50

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.00

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())

        my_pizza = Pepperoni(my_pizza)
        self.assertEqual(my_pizza.get_cost(), 6.50)
        self.assertIn("Pepperoni", my_pizza.get_description())

        desc = my_pizza.get_description()
        self.assertTrue("Thin dough" in desc)
        self.assertTrue("Mozzarella" in desc)
        self.assertTrue("Pepperoni" in desc)

if __name__ == '__main__':
    unittest.main()

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.


Refactor this funtion to reduce code complexity by splitting it into smaller functions validate_order(order), calculate_total(order), apply_discount(total, discount_code), and generate_receipt(total) and process_order(order). also use a dictionary to avoid hardcoded values and reduce codde ducplication in the discount logic.

Herstructureer deze functie om de complexiteit van de code te verminderen door deze op te splitsen in kleinere functies validate_order(order), calculate_total(order), apply_discount(total, discount_code) en generate_receipt(total). gebruik ook een woordenboek om hardgecodeerde waarden te vermijden en codeduplicatie in de kortingslogica te verminderen.

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
    elif order.get("discount_code") == "SAVE50":
        total *= 0.5

    receipt = f"Total: ${total:.2f}"
    return receipt

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,
        "SAVE20": 0.8,
        "SAVE50": 0.5
    }
    multiplier = discount_rates.get(discount_code, 1.0)
    return total * multiplier

def generate_receipt(total):
    return f"Total: ${total:.2f}"

def process_order(order):
    valid, message = validate_order(order)
    if not valid:
        return message
    total = calculate_total(order)
    total = apply_discount(total, order.get("discount_code"))
    return generate_receipt(total)

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 contain items")

    def test_structure(self):
        g = globals()
        required = ['validate_order', 'calculate_total', 'apply_discount', 'generate_receipt']
        for func in required:
            self.assertIn(func, g, f"Missing required function: {func}")

    def test_complexity_reduction(self):
        src = inspect.getsource(apply_discount)

        has_dict = "{" in src or "dict(" in src

        if_count = src.count("if ") + src.count("elif ")

        if not has_dict and if_count > 1:
            self.fail("You used multiple if/elif statements. Please use a Dictionary/Map constant to reduce code complexity.")

if __name__ == '__main__':
    unittest.main()

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


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="Jane Doe",
author_email="jane.doe@example.com",
license="MIT",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: Build Tools",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
],
keywords="data processing, legacy, conversion test",
packages=find_packages(where="src"),
package_dir={"": "src"},
python_requires=">=3.8, <4",
install_requires=[
"pandas>=1.3.0",
"requests==2.26.0",
"numpy",
],
extras_require={
"dev": ["check-manifest"],
"test": ["pytest", "coverage"],
},
entry_points={
"console_scripts": [
"data-cli=legacy_tool.cli:main",
],
},
project_urls={
"Bug Reports": "https://github.com/example/legacy-data-tool/issues",
"Source": "https://github.com/example/legacy-data-tool",
},
)

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 = {text = "MIT"}
keywords = ["data processing", "legacy", "conversion test"]
authors = [
  {name = "Jane Doe", email = "jane.doe@example.com"}
]
classifiers = [
  "Development Status :: 4 - Beta",
  "Intended Audience :: Developers",
  "Topic :: Software Development :: Build Tools",
  "License :: OSI Approved :: MIT License",
  "Programming Language :: Python :: 3.8",
  "Programming Language :: Python :: 3.9",
]
dependencies = [
  "pandas>=1.3.0",
  "requests==2.26.0",
  "numpy",
]

[project.optional-dependencies]
dev = ["check-manifest"]
test = ["pytest", "coverage"]

[project.scripts]
data-cli = "legacy_tool.cli:main"

[project.urls]
"Bug Reports" = "https://github.com/example/legacy-data-tool/issues"
"Source" = "https://github.com/example/legacy-data-tool"

[tool.setuptools.packages.find]
where = ["src"]
"""

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.


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_comp(data):
    return [
        member['name']
        for team in data
        for member in team['members']
        if member['role'] == 'Senior'
    ]

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', 'Charlie']
        self.assertEqual(get_seniors_loop(data), expected)
        self.assertEqual(get_seniors_loop([]), [])

    def test_structure(self):
        src = inspect.getsource(get_seniors_loop)

        if "append(" in src:
            self.fail("You are still using .append(). Use a list comprehension instead.")

        if "[" not in src or "]" not in src:
             self.fail("List comprehension brackets [] not found.")

if __name__ == '__main__':
    unittest.main()

The solution MUST keep the same functionality, but change the implementation from nested for loops to a list comprehension.


I am calculating and retrieving data for a tableau chart using an MSSQL query. Above the chart is AGG (average number of customer hours cost center), which is SUM([Direct Time In Hours])/[numberofclients].[Sum unique clients cost center]. Sum unique clients cost center is in Tableau with the following calculation: SUM({FIXED [Year], [Month], [Cost Center Name]: COUNTD([Client])}) I want the tableau to have a row per cost center per month, and all the data comes from the numberofclients table. Can you convert this to an MSSQL database query?

Ik bereken en haal gegevens op voor een tableau chart met behulp van een MSSQL query. Boven de chart staat AGG (average number of customer hours cost center), wat SUM([Direct Time In Hours])/[numberofclients].[Sum unique clients cost center]. Som unieke klanten kostenplaats staat in Tableau met de volgende berekening: SUM({FIXED [Year], [Month], [Cost Center Name]: COUNTD([Client])}) Ik wil dat het tableau één rij per kostenplaats per maand heeft en dat alle gegevens afkomstig zijn uit de tabel numberofclients. Kunt u dit omzetten naar een MSSQL databasequery?

-- Schema Context:
-- CREATE TABLE students (
--    id INTEGER AUTO_INCREMENT UNIQUE,
--    name VARCHAR(255),
--    valedictorian BOOLEAN,
--    ...
-- );
--
-- CREATE TABLE valedictorians (
--    id INTEGER UNIQUE
-- );

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],
[Month],
[Cost Center Name];

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', 'ClientA', 20.0); -- Same client, different hours (Total hours=30, Unique Clients=1)
INSERT INTO numberofclients VALUES (2023, 1, 'IT', 'ClientB', 30.0); -- New client (Total IT hours=60, Unique Clients=2, Avg=30)

    @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");

          assertEquals("IT", rs.getString("Cost Center Name"));
            assertEquals(60.0, rs.getDouble("TotalHours"), 0.01, "Total hours sum failed");
            assertEquals(2, rs.getInt("UniqueClientsPerMonth"), "Distinct client count failed");

           assertEquals(30.0, rs.getDouble("AvgCustomerHours"), 0.01, "Average calculation failed");
        }
    }

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.


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
-- );

-- Write your UPDATE statement below:

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, name, valedictorian) VALUES (2, 'Bob', TRUE);

@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(rs1.next());
            assertTrue(rs1.getBoolean("valedictorian"), "Alice should be updated to TRUE (1)");

           ResultSet rs2 = stmt.executeQuery("SELECT valedictorian FROM students WHERE id = 2");
            assertTrue(rs2.next());
            assertFalse(rs2.getBoolean("valedictorian"), "Bob should be updated to FALSE (0)");
        }
    }

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.


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)
);

-- Dept A Data: 10, 20, 30, 40
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', 'Electronics', 30.00);
INSERT INTO daily_sales VALUES (4, '2023-01-04', 'Electronics', 40.00);

-- Dept B Data: 100 (Should not mix with Dept A)
INSERT INTO daily_sales VALUES (5, '2023-01-01', 'Furniture', 100.00);

    @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);

           assertTrue(rs.next());
            assertEquals(15.0, rs.getDouble("moving_avg_3_day"), 0.01);

              assertTrue(rs.next());
            assertEquals(20.0, rs.getDouble("moving_avg_3_day"), 0.01);

              assertTrue(rs.next());
            assertEquals(30.0, rs.getDouble("moving_avg_3_day"), 0.01, "Window sliding logic failed");

       assertTrue(rs.next());
            assertEquals("Furniture", rs.getString("department"));
            assertEquals(100.0, rs.getDouble("moving_avg_3_day"), 0.01, "Partition logic failed");
        }
    }

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).


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; -- Logic happens BEFORE the join

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 INTO students VALUES (3, 'Charlie');

    @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++;
                String name = rs.getString("student_name");
                int score = rs.getInt("distinction_grade");
                boolean isNull = rs.wasNull();
                if (name.equals("Alice")) {
                    assertEquals(9, score, "Alice should have a score of 9");
                } else if (name.equals("Bob")) {
                    assertTrue(isNull, "Bob should have NULL score (filtered out by ON clause)");
                } else if (name.equals("Charlie")) {
                    assertTrue(isNull, "Charlie should have NULL score (no exam)");
                }
            }
            assertEquals(3, rowCount, "Should return ALL 3 students, not just the high scorers");
        }
    }

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.


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?");

            assertEquals("Bob", rs.getString("customer_name"), "Should return Bob (who has no orders)");
        assertFalse(rs.next(), "Should only return customers with no orders");
        }
    }

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.


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("disease_probability");

          assertTrue(probability > 0, "Result was 0. Did you fix the integer division problem?");
            assertEquals(0.5, probability, 0.001, "Calculation should be correct (50/100 = 0.5)");
        }
    }

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.


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++;
                Timestamp ts = rs.getTimestamp("transaction_date");
                // Assert we did NOT pick up the 2024 date
                assertFalse(ts.toLocalDateTime().getYear() == 2024, "Query incorrectly included a 2024 transaction due to rounding.");
            }
            assertEquals(2, count, "Should return exactly 2 rows from 2023.");
        }
    }

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.


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;

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 = filtered.max_time;

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) {
                    foundUser1 = true;
                    assertEquals("2.2.2.2", rs.getString("ip_address"), "Should return the IP of the LATEST login, not a random one.");
                }
            }
            assertTrue(foundUser1, "User 1 should be in the results.");
        }
    }

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).


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;  -- <--- Correct

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), (1), (1);

INSERT INTO patients VALUES (2, 'Bob');
INSERT INTO radiology_log (patient_id) VALUES (2);

    @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");
            assertEquals("Alice", rs.getString("patient_name"));
            assertEquals(11, rs.getInt("visit_count"));
           assertFalse(rs.next(), "Should filter out patients with <= 10 visits");
        }
    }

The solution MUST replace the WHERE clause with HAVING for filtering aggregate fields.


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,
name,
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.");
            assertEquals(1, rs.getInt("patient_id"));
            assertEquals("John Doe", rs.getString("name"));
               assertNotNull(rs.getDate("admission_date"));
        }
    }

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).


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", rs.getString("result_value"));

         assertFalse(rs.next(), "Should filter out low numbers and non-numeric strings without crashing.");
        }
    }

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


This query retrieves the names, the total spend and the date of the most recent order of out top buyers (spent more than 1000$ total). Refactor this query to make it more efficient and readable without changing functionality.

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_spend > 1000
)
SELECT
c.customer_name,
hvc.total_spend,
hvc.last_order_date
FROM customers c
INNER JOIN HighValueCustomers hvc
ON c.id = hvc.customer_id;

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, 1, 500, '2023-01-05');

INSERT INTO customers VALUES (2, 'Bob');
INSERT INTO orders VALUES (201, 2, 900, '2023-02-01');

-- 3. Edge Case (Charlie): 1000 total (Should be filtered out)
INSERT INTO customers VALUES (3, 'Charlie');
INSERT INTO orders VALUES (301, 3, 1000, '2023-03-01');

    @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, "Refactoring failed: You must optimize the query using a CTE (WITH) or JOINs instead of correlated subqueries.");

      try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {

            assertTrue(rs.next(), "Should return high value customers.");
            assertEquals("Alice", rs.getString("customer_name"));
            assertEquals(1100, rs.getInt("total_spend"));
            assertEquals(Date.valueOf("2023-01-05"), rs.getDate("last_order_date"));

            assertFalse(rs.next(), "Should strictly filter > 1000 (Bob and Charlie should not appear).");
        }
    }

the solution MUST separate the big query with redundant subqueries into multiple queries with sepration of concerns (i.e. one for the math, one for the filtering, and one for the display), this makes the code mre efficient (less redundancy), more readable, and more maintainable (easier to debug). The unit test includes structural checks (as well as functional checks) to ensure refactoring.


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 (weight_kg / (height_m * height_m)) < 30 THEN 'Overweight'
WHEN (weight_kg / (height_m * height_m)) >= 30 THEN 'Obese'
END as bmi_category
FROM patients;

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 means ">= 25 AND < 30"
ELSE 'Obese'
END as bmi_category
FROM PatientBMI;

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.70);

    @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();
             ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {

            int count = 0;
            while(rs.next()) {
                count++;
                String name = rs.getString("patient_name");
                String category = rs.getString("bmi_category");

                if (name.equals("Alice")) assertEquals("Underweight", category);
                else if (name.equals("Bob")) assertEquals("Healthy", category);
                else if (name.equals("Charlie")) assertEquals("Overweight", category);
                else if (name.equals("Diana")) assertEquals("Obese", category);
            }
            assertEquals(4, count, "Should return all 4 patients");
        }
    }

the solution MUST use a CTE to calculate BMI just once, then reference that in the main query to assign a category. The unit test includes structural checks (as well as functional checks) to ensure refactoring and specific use of CTE as the prompt requires. The unit test includes structural checks (as well as functional checks) to ensure refactoring.


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
WHERE s.id = 101
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 ON s.id = g.student_id
JOIN courses c ON g.course_id = c.id
GROUP BY s.student_name
HAVING SUM(g.score * c.credits) * 1.0 / SUM(c.credits) > 8.0;

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.student_name;

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), (1, 102, 8);

INSERT INTO students VALUES (2, 'Bob');
INSERT INTO grades VALUES (2, 101, 6), (2, 102, 7);

    @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 (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(verifySql)) {

         assertTrue(rs.next(), "The view should return rows.");
            assertEquals("Felipe", rs.getString("student_name"));
            assertEquals(8.5, rs.getDouble("gpa"), 0.01, "Felipe's GPA should be 8.5");

      assertTrue(rs.next());
            assertEquals("Bob", rs.getString("student_name"));
            assertEquals(6.5, rs.getDouble("gpa"), 0.01, "Bob's GPA should be 6.5");
        }
    }

the solution MUST create a view called student_gpa_view that encapsulates the GPA calculation logic, so that both original queries can be simplified to select from this view with appropriate filtering (by student_id for the first, and by gpa for the second). This reduces redundancy and improves maintainability. The unit test includes structural checks (as well as functional checks) to ensure refactoring.


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 order_date DESC LIMIT 1) as amount
FROM customers c;

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 INTO orders VALUES (102, 1, 'Laptop', 1000, '2023-01-02');
INSERT INTO orders VALUES (103, 1, 'Tablet', 300, '2023-01-03');

INSERT INTO customers VALUES (2, 'Bob');

    @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();
             ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {

          assertTrue(rs.next());
            assertEquals("Alice", rs.getString("name"));
            assertEquals("Tablet", rs.getString("product_name"));

       assertTrue(rs.next());
            assertEquals("Bob", rs.getString("name"));
            assertNull(rs.getString("product_name"), "Bob was filtered out or data is wrong. Did you use LEFT JOIN LATERAL?");
        }
    }

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.