Upload dataset_base.jsonl with huggingface_hub
Browse files- dataset_base.jsonl +6 -6
dataset_base.jsonl
CHANGED
|
@@ -110,7 +110,7 @@
|
|
| 110 |
"prompt_en":"write a JavaScript function called createReactScaffold(projectName) that creates a basic project structure for a React app using Vite. Return ONLY the function.",
|
| 111 |
"prompt_nl":"Schrijf een JavaScript-functie met de naam createReactScaffold(projectName) die een basisprojectstructuur voor een React-app maakt met behulp van Vite. Retourneer ALLEEN de functie.",
|
| 112 |
"code_snippet_input":"",
|
| 113 |
-
"canonical_solution":"function createReactScaffold(projectName) {\n const rootDir = path.resolve(process.cwd(), projectName);\n const dirs = [\n rootDir,\n path.join(rootDir, 'src'),\n path.join(rootDir, 'public')\n ];\n\n dirs.forEach(dir => {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n });\n const indexHtml = `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Vite + React</title>\n</head>\n<body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/src/main.jsx\"></script>\n</body>\n</html>`;\n const packageJson = {\n name: projectName,\n private: true,\n version: '0.0.0',\n type: 'module',\n scripts: {\n dev: 'vite',\n build: 'vite build',\n lint: 'eslint .',\n preview: 'vite preview'\n },\n dependencies: {\n react: '^18.2.0',\n 'react-dom': '^18.2.0'\n },\n devDependencies: {\n '@types/react': '^18.2.0',\n '@types/react-dom': '^18.2.0',\n '@vitejs/plugin-react': '^4.2.0',\n vite: '^5.0.0'\n }\n };\n const viteConfig = `import { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n})`;\n\n const mainJsx = `import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App.jsx'\nimport './index.css'\nReactDOM.createRoot(document.getElementById('root')).render(\n <React.StrictMode>\n <App />\n </React.StrictMode>,\n)`;\n\n const appJsx = `import { useState } from 'react'\nimport './App.css'\nfunction App() {\n const [count, setCount] = useState(0)\n return (\n <>\n <h1>Vite + React</h1>\n <div className=\"card\">\n <button onClick={() => setCount((count) => count + 1)}>\n count is {count}\n </button>\n </div>\n </>\n )\n}\nexport default App`;\n\n const files = [\n { path: path.join(rootDir, 'index.html'), content: indexHtml },\n { path: path.join(rootDir, 'package.json'), content: JSON.stringify(packageJson, null, 2) },\n { path: path.join(rootDir, 'vite.config.js'), content: viteConfig },\n { path: path.join(rootDir,
|
| 114 |
"unit_test_setup":"const { vol } = require('memfs');\nconst fs = require('fs');\nconst path = require('path');\njest.mock('fs', () => require('memfs').fs);\n\ndescribe('createReactScaffold', () => {\n beforeEach(() => {\n vol.reset();\n });\n\n const projectName = 'test-app';",
|
| 115 |
"unit_test_assertion":"test('should create the correct directory structure', () => {\n createReactScaffold(projectName);\n const rootPath = path.resolve(process.cwd(), projectName);\n expect(fs.existsSync(rootPath)).toBe(true);\n expect(fs.existsSync(path.join(rootPath, 'src'))).toBe(true);\n expect(fs.existsSync(path.join(rootPath, 'public'))).toBe(true);\n });\n\n test('should generate a valid package.json with the project name', () => {\n createReactScaffold(projectName);\n const pkgPath = path.resolve(process.cwd(), projectName, 'package.json');\n const pkgContent = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));\n expect(pkgContent.name).toBe(projectName);\n expect(pkgContent.dependencies).toHaveProperty('react');\n expect(pkgContent.scripts).toHaveProperty('dev', 'vite');\n });\n\n test('should create main.jsx with React hydration logic', () => {\n createReactScaffold(projectName);\n const mainJsxPath = path.resolve(process.cwd(), projectName, 'src', 'main.jsx');\n const content = fs.readFileSync(mainJsxPath, 'utf8');\n expect(content).toContain(\"ReactDOM.createRoot\");\n expect(content).toContain(\"<App />\");\n });\n});",
|
| 116 |
"comment":"the solution MUST physically create directories, it must use modern Vite 5 and React 18 dependencies, (additionally React.StrictMode is preferred). the unit test uses mocks to verify file and directory creation. solution should be cleaned before processing to remove any const declarations."
|
|
@@ -182,7 +182,7 @@
|
|
| 182 |
"prompt_en":"Write a method createScaffold(project_name, root_dir) in python that creates a basic project structure for a kotlin project using gradle. Return ONLY the method",
|
| 183 |
"prompt_nl":"Schrijf een methode createScaffold in Python die een basisprojectstructuur voor een Kotlin-project maakt met behulp van Gradle. Retourneer ALLEEN de methode.",
|
| 184 |
"code_snippet_input":"",
|
| 185 |
-
"canonical_solution":"from pathlib import Path\n\ndef createScaffold(project_name: str, root_dir: str = \".\"):\n base_path = Path(root_dir) / project_name\n \n directories = [\n base_path / \"src/main/kotlin\",\n base_path / \"src/main/resources\",\n base_path / \"src/test/kotlin\",\n base_path / \"src/test/resources\",\n base_path / \"gradle/wrapper\"\n ]\n \n files = {\n base_path / \"settings.gradle.kts\": f'rootProject.name = \"{project_name}\"\\n',\n base_path / \"build.gradle.kts\": \"\"\"plugins {\n kotlin(\"jvm\") version \"1.9.22\"\n}\ngroup = \"org.example\"\nversion = \"1.0-SNAPSHOT\"\nrepositories {\n mavenCentral()\n}\ndependencies {\n testImplementation(kotlin(\"test\"))\n}\ntasks.test {\n useJUnitPlatform()\n}\n\"\"\",\n base_path / \".
|
| 186 |
"unit_test_setup":"import unittest\nimport tempfile\nimport shutil\nfrom pathlib import Path\nimport os\n\n",
|
| 187 |
"unit_test_assertion":"class TestKotlinScaffold(unittest.TestCase):\n def setUp(self):\n self.test_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n shutil.rmtree(self.test_dir)\n\n def test_directory_structure(self):\n project_name = \"MyKotlinApp\"\n createScaffold(project_name, self.test_dir)\n \n base = Path(self.test_dir) / project_name\n \n required_dirs = [\n \"src/main/kotlin\",\n \"src/test/kotlin\",\n \"gradle/wrapper\"\n ]\n for d in required_dirs:\n self.assertTrue((base / d).exists(), f\"Directory missing: {d}\")\n self.assertTrue((base / d).is_dir(), f\"Path is not a directory: {d}\")\n \n required_files = [\n \"build.gradle.kts\",\n \"settings.gradle.kts\",\n \".gitignore\"\n ]\n for f in required_files:\n self.assertTrue((base / f).exists(), f\"File missing: {f}\")\n \n settings_content = (base / \"settings.gradle.kts\").read_text()\n self.assertIn(f'rootProject.name = \"{project_name}\"', settings_content, \"settings.gradle.kts has wrong project name\")\n\nif __name__ == '__main__':\n unittest.main()",
|
| 188 |
"comment":"the solution MUST create src/main/kotlin, src/test/kotlin, gradle/wrapper directories and settings.gradle.kts, build.gradle.kts, .gitignore files, the root project name MUST be correctly assigned in settings.gradle.kts."
|
|
@@ -256,7 +256,7 @@
|
|
| 256 |
"code_snippet_input":"#KeyError\ndef count_word_frequencies(words):\n frequency_map = {}\n for word in words:\n frequency_map[word] = frequency_map[word] + 1\n return frequency_map",
|
| 257 |
"canonical_solution":"from collections import defaultdict\ndef count_word_frequencies(words):\n frequency_map = defaultdict(int) \n for word in words:\n frequency_map[word] += 1\n return dict(frequency_map)",
|
| 258 |
"unit_test_setup":"import unittest\nfrom collections import defaultdict\n\n",
|
| 259 |
-
"unit_test_assertion":"class TestFrequency(unittest.TestCase):\n def test_counting(self):\n input_words = [\"apple\", \"banana\", \"apple\", \"cherry\", \"banana\", \"banana\"]\n expected = {\"apple\": 2, \"banana\": 3, \"cherry\": 1}\n \n
|
| 260 |
"comment":"the original code fails every time it encounters a new word because the key doesn't exist in the disctionary yet. the solution MUST use defaultdict or get() to assign a default value 0 to new keys."
|
| 261 |
}
|
| 262 |
{"id":"base_python_10","dataset_type":"base","language":"Python","task_category":"fix_bug",
|
|
@@ -290,8 +290,8 @@
|
|
| 290 |
"prompt_en":"Refactor this funtion to reduce code complexity by splitting it into smaller functions validate_order(order), calculate_total(order), apply_discount(total, discount_code), and generate_receipt(total) and process_order(order). also use a dictionary to avoid hardcoded values and reduce codde ducplication in the discount logic.",
|
| 291 |
"prompt_nl":"Herstructureer deze functie om de complexiteit van de code te verminderen door deze op te splitsen in kleinere functies validate_order(order), calculate_total(order), apply_discount(total, discount_code) en generate_receipt(total). gebruik ook een woordenboek om hardgecodeerde waarden te vermijden en codeduplicatie in de kortingslogica te verminderen.",
|
| 292 |
"code_snippet_input":"def process_order(order):\n if not order.get(\"items\"):\n return \"Order must contain items\"\n\n total = sum(item[\"price\"] * item[\"quantity\"] for item in order[\"items\"])\n\n if order.get(\"discount_code\") == \"SAVE10\":\n total *= 0.9 \n elif order.get(\"discount_code\") == \"SAVE20\":\n total *= 0.8\n elif order.get(\"discount_code\") == \"SAVE50\":\n total *= 0.5\n\n receipt = f\"Total: ${total:.2f}\"\n return receipt",
|
| 293 |
-
"canonical_solution":"def validate_order(order):\n if not order.get(\"items\"):\n return False, \"Order must contain items\"\n return True, \"\"\n\ndef calculate_total(order):\n return sum(item[\"price\"] * item[\"quantity\"] for item in order[\"items\"])\n\ndef apply_discount(total, discount_code):
|
| 294 |
-
"unit_test_setup":"import unittest\n\n",
|
| 295 |
"unit_test_assertion":"class TestRefactoring(unittest.TestCase):\n def test_functionality(self):\n order = {\n \"items\": [{\"price\": 100, \"quantity\": 1}],\n \"discount_code\": \"SAVE20\"\n }\n self.assertEqual(process_order(order), \"Total: $80.00\")\n self.assertEqual(process_order({}), \"Order must contain items\")\n\n def test_structure(self):\n g = globals()\n required = ['validate_order', 'calculate_total', 'apply_discount', 'generate_receipt']\n for func in required:\n self.assertIn(func, g, f\"Missing required function: {func}\")\n \n def test_complexity_reduction(self):\n src = inspect.getsource(apply_discount)\n \n has_dict = \"{\" in src or \"dict(\" in src\n \n if_count = src.count(\"if \") + src.count(\"elif \")\n \n if not has_dict and if_count > 1:\n self.fail(\"You used multiple if/elif statements. Please use a Dictionary/Map constant to reduce code complexity.\")\n\nif __name__ == '__main__':\n unittest.main()",
|
| 296 |
"comment":"the solution MUST split the origial function into the specified smaller functions, use the same method signature, and use a constant for the discount logic, while preserving the same functionality"
|
| 297 |
}
|
|
@@ -308,7 +308,7 @@
|
|
| 308 |
"prompt_en":"This function retrieves the names of all senior members from a any team in a nested structure. Refactor the method to use list comprehensions.",
|
| 309 |
"prompt_nl":"Deze functie haalt de namen op van alle senior leden van elk team in een geneste structuur. Herstructureer de methode om list comprehensions te gebruiken.",
|
| 310 |
"code_snippet_input":"def get_seniors_loop(data):\n seniors = []\n for team in data:\n for member in team['members']:\n if member['role'] == 'Senior':\n seniors.append(member['name'])\n return seniors",
|
| 311 |
-
"canonical_solution":"def
|
| 312 |
"unit_test_setup":"import unittest\nimport inspect\n\n",
|
| 313 |
"unit_test_assertion":"class TestListComp(unittest.TestCase):\n def test_behavior(self):\n data = [\n {'members': [{'name': 'Alice', 'role': 'Junior'}, {'name': 'Bob', 'role': 'Senior'}]},\n {'members': [{'name': 'Charlie', 'role': 'Senior'}, {'name': 'Dave', 'role': 'Lead'}]}\n ]\n expected = ['Bob', 'Charlie']\n self.assertEqual(get_seniors_loop(data), expected)\n self.assertEqual(get_seniors_loop([]), [])\n\n def test_structure(self):\n src = inspect.getsource(get_seniors_loop)\n \n if \"append(\" in src:\n self.fail(\"You are still using .append(). Use a list comprehension instead.\")\n \n if \"[\" not in src or \"]\" not in src:\n self.fail(\"List comprehension brackets [] not found.\")\n\nif __name__ == '__main__':\n unittest.main()",
|
| 314 |
"comment":"The solution MUST keep the same functionality, but change the implementation from nested for loops to a list comprehension."
|
|
|
|
| 110 |
"prompt_en":"write a JavaScript function called createReactScaffold(projectName) that creates a basic project structure for a React app using Vite. Return ONLY the function.",
|
| 111 |
"prompt_nl":"Schrijf een JavaScript-functie met de naam createReactScaffold(projectName) die een basisprojectstructuur voor een React-app maakt met behulp van Vite. Retourneer ALLEEN de functie.",
|
| 112 |
"code_snippet_input":"",
|
| 113 |
+
"canonical_solution":"function createReactScaffold(projectName) {\n const rootDir = path.resolve(process.cwd(), projectName);\n const dirs = [\n rootDir,\n path.join(rootDir, 'src'),\n path.join(rootDir, 'public')\n ];\n\n dirs.forEach(dir => {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n });\n const indexHtml = `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Vite + React</title>\n</head>\n<body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/src/main.jsx\"></script>\n</body>\n</html>`;\n const packageJson = {\n name: projectName,\n private: true,\n version: '0.0.0',\n type: 'module',\n scripts: {\n dev: 'vite',\n build: 'vite build',\n lint: 'eslint .',\n preview: 'vite preview'\n },\n dependencies: {\n react: '^18.2.0',\n 'react-dom': '^18.2.0'\n },\n devDependencies: {\n '@types/react': '^18.2.0',\n '@types/react-dom': '^18.2.0',\n '@vitejs/plugin-react': '^4.2.0',\n vite: '^5.0.0'\n }\n };\n const viteConfig = `import { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n})`;\n\n const mainJsx = `import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App.jsx'\nimport './index.css'\nReactDOM.createRoot(document.getElementById('root')).render(\n <React.StrictMode>\n <App />\n </React.StrictMode>,\n)`;\n\n const appJsx = `import { useState } from 'react'\nimport './App.css'\nfunction App() {\n const [count, setCount] = useState(0)\n return (\n <>\n <h1>Vite + React</h1>\n <div className=\"card\">\n <button onClick={() => setCount((count) => count + 1)}>\n count is {count}\n </button>\n </div>\n </>\n )\n}\nexport default App`;\n\n const files = [\n { path: path.join(rootDir, 'index.html'), content: indexHtml },\n { path: path.join(rootDir, 'package.json'), content: JSON.stringify(packageJson, null, 2) },\n { path: path.join(rootDir, 'vite.config.js'), content: viteConfig },\n { path: path.join(rootDir, `.gitignore`), content: `node_modules\ndist\n.env` },\n { path: path.join(rootDir, 'src', 'main.jsx'), content: mainJsx },\n { path: path.join(rootDir, 'src', 'App.jsx'), content: appJsx },\n { path: path.join(rootDir, 'src', 'App.css'), content: '/* App styles */' },\n { path: path.join(rootDir, 'src', 'index.css'), content: '/* Global styles */' },\n { path: path.join(rootDir, 'public', 'vite.svg'), content: '<svg></svg>' }\n ];\n files.forEach(file => {\n fs.writeFileSync(file.path, file.content.trim());\n });\n\n console.log(`React Vite project created at ${rootDir}`);\n}",
|
| 114 |
"unit_test_setup":"const { vol } = require('memfs');\nconst fs = require('fs');\nconst path = require('path');\njest.mock('fs', () => require('memfs').fs);\n\ndescribe('createReactScaffold', () => {\n beforeEach(() => {\n vol.reset();\n });\n\n const projectName = 'test-app';",
|
| 115 |
"unit_test_assertion":"test('should create the correct directory structure', () => {\n createReactScaffold(projectName);\n const rootPath = path.resolve(process.cwd(), projectName);\n expect(fs.existsSync(rootPath)).toBe(true);\n expect(fs.existsSync(path.join(rootPath, 'src'))).toBe(true);\n expect(fs.existsSync(path.join(rootPath, 'public'))).toBe(true);\n });\n\n test('should generate a valid package.json with the project name', () => {\n createReactScaffold(projectName);\n const pkgPath = path.resolve(process.cwd(), projectName, 'package.json');\n const pkgContent = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));\n expect(pkgContent.name).toBe(projectName);\n expect(pkgContent.dependencies).toHaveProperty('react');\n expect(pkgContent.scripts).toHaveProperty('dev', 'vite');\n });\n\n test('should create main.jsx with React hydration logic', () => {\n createReactScaffold(projectName);\n const mainJsxPath = path.resolve(process.cwd(), projectName, 'src', 'main.jsx');\n const content = fs.readFileSync(mainJsxPath, 'utf8');\n expect(content).toContain(\"ReactDOM.createRoot\");\n expect(content).toContain(\"<App />\");\n });\n});",
|
| 116 |
"comment":"the solution MUST physically create directories, it must use modern Vite 5 and React 18 dependencies, (additionally React.StrictMode is preferred). the unit test uses mocks to verify file and directory creation. solution should be cleaned before processing to remove any const declarations."
|
|
|
|
| 182 |
"prompt_en":"Write a method createScaffold(project_name, root_dir) in python that creates a basic project structure for a kotlin project using gradle. Return ONLY the method",
|
| 183 |
"prompt_nl":"Schrijf een methode createScaffold in Python die een basisprojectstructuur voor een Kotlin-project maakt met behulp van Gradle. Retourneer ALLEEN de methode.",
|
| 184 |
"code_snippet_input":"",
|
| 185 |
+
"canonical_solution":"from pathlib import Path\n\ndef createScaffold(project_name: str, root_dir: str = \".\"):\n base_path = Path(root_dir) / project_name\n \n directories = [\n base_path / \"src/main/kotlin\",\n base_path / \"src/main/resources\",\n base_path / \"src/test/kotlin\",\n base_path / \"src/test/resources\",\n base_path / \"gradle/wrapper\"\n ]\n \n files = {\n base_path / \"settings.gradle.kts\": f'rootProject.name = \"{project_name}\"\\n',\n base_path / \"build.gradle.kts\": \"\"\"plugins {\n kotlin(\"jvm\") version \"1.9.22\"\n}\ngroup = \"org.example\"\nversion = \"1.0-SNAPSHOT\"\nrepositories {\n mavenCentral()\n}\ndependencies {\n testImplementation(kotlin(\"test\"))\n}\ntasks.test {\n useJUnitPlatform()\n}\n\"\"\",\n base_path / \".gittignore\": \".gradle/\\build/\\nout/\\n.idea/\\n*.iml\\n.DS_Store\",\n base_path / \"README.md\": f\"# {project_name}\\n\\nGenerated Kotlin/Gradle Project.\",\n base_path / \"gradle/wrapper/gradle-wrapper.properties\": \"\"\"distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-8.5-bin.zip\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n\"\"\"\n }\n\n print(f\"Creating Kotlin/Gradle scaffold for '{project_name}'...\")\n for d in directories:\n d.mkdir(parents=True, exist_ok=True)\n \n for path, content in files.items():\n path.write_text(content, encoding=\"utf-8\")\n \n print(f\"Project created at {base_path.resolve()}\")",
|
| 186 |
"unit_test_setup":"import unittest\nimport tempfile\nimport shutil\nfrom pathlib import Path\nimport os\n\n",
|
| 187 |
"unit_test_assertion":"class TestKotlinScaffold(unittest.TestCase):\n def setUp(self):\n self.test_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n shutil.rmtree(self.test_dir)\n\n def test_directory_structure(self):\n project_name = \"MyKotlinApp\"\n createScaffold(project_name, self.test_dir)\n \n base = Path(self.test_dir) / project_name\n \n required_dirs = [\n \"src/main/kotlin\",\n \"src/test/kotlin\",\n \"gradle/wrapper\"\n ]\n for d in required_dirs:\n self.assertTrue((base / d).exists(), f\"Directory missing: {d}\")\n self.assertTrue((base / d).is_dir(), f\"Path is not a directory: {d}\")\n \n required_files = [\n \"build.gradle.kts\",\n \"settings.gradle.kts\",\n \".gitignore\"\n ]\n for f in required_files:\n self.assertTrue((base / f).exists(), f\"File missing: {f}\")\n \n settings_content = (base / \"settings.gradle.kts\").read_text()\n self.assertIn(f'rootProject.name = \"{project_name}\"', settings_content, \"settings.gradle.kts has wrong project name\")\n\nif __name__ == '__main__':\n unittest.main()",
|
| 188 |
"comment":"the solution MUST create src/main/kotlin, src/test/kotlin, gradle/wrapper directories and settings.gradle.kts, build.gradle.kts, .gitignore files, the root project name MUST be correctly assigned in settings.gradle.kts."
|
|
|
|
| 256 |
"code_snippet_input":"#KeyError\ndef count_word_frequencies(words):\n frequency_map = {}\n for word in words:\n frequency_map[word] = frequency_map[word] + 1\n return frequency_map",
|
| 257 |
"canonical_solution":"from collections import defaultdict\ndef count_word_frequencies(words):\n frequency_map = defaultdict(int) \n for word in words:\n frequency_map[word] += 1\n return dict(frequency_map)",
|
| 258 |
"unit_test_setup":"import unittest\nfrom collections import defaultdict\n\n",
|
| 259 |
+
"unit_test_assertion":"class TestFrequency(unittest.TestCase):\n def test_counting(self):\n input_words = [\"apple\", \"banana\", \"apple\", \"cherry\", \"banana\", \"banana\"]\n expected = {\"apple\": 2, \"banana\": 3, \"cherry\": 1}\n \n result = count_word_frequencies(input_words)\n self.assertEqual(result, expected, \"Counts do not match expected frequencies\")\n\n def test_empty(self):\n self.assertEqual(count_word_frequencies([]), {}, \"Empty list should return empty dict\")\n\nif __name__ == '__main__':\n unittest.main()",
|
| 260 |
"comment":"the original code fails every time it encounters a new word because the key doesn't exist in the disctionary yet. the solution MUST use defaultdict or get() to assign a default value 0 to new keys."
|
| 261 |
}
|
| 262 |
{"id":"base_python_10","dataset_type":"base","language":"Python","task_category":"fix_bug",
|
|
|
|
| 290 |
"prompt_en":"Refactor this funtion to reduce code complexity by splitting it into smaller functions validate_order(order), calculate_total(order), apply_discount(total, discount_code), and generate_receipt(total) and process_order(order). also use a dictionary to avoid hardcoded values and reduce codde ducplication in the discount logic.",
|
| 291 |
"prompt_nl":"Herstructureer deze functie om de complexiteit van de code te verminderen door deze op te splitsen in kleinere functies validate_order(order), calculate_total(order), apply_discount(total, discount_code) en generate_receipt(total). gebruik ook een woordenboek om hardgecodeerde waarden te vermijden en codeduplicatie in de kortingslogica te verminderen.",
|
| 292 |
"code_snippet_input":"def process_order(order):\n if not order.get(\"items\"):\n return \"Order must contain items\"\n\n total = sum(item[\"price\"] * item[\"quantity\"] for item in order[\"items\"])\n\n if order.get(\"discount_code\") == \"SAVE10\":\n total *= 0.9 \n elif order.get(\"discount_code\") == \"SAVE20\":\n total *= 0.8\n elif order.get(\"discount_code\") == \"SAVE50\":\n total *= 0.5\n\n receipt = f\"Total: ${total:.2f}\"\n return receipt",
|
| 293 |
+
"canonical_solution":"def validate_order(order):\n if not order.get(\"items\"):\n return False, \"Order must contain items\"\n return True, \"\"\n\ndef calculate_total(order):\n return sum(item[\"price\"] * item[\"quantity\"] for item in order[\"items\"])\n\ndef apply_discount(total, discount_code): \ndiscount_rates = {\n \"SAVE10\": 0.9,\n \"SAVE20\": 0.8,\n \"SAVE50\": 0.5\n }\n multiplier = discount_rates.get(discount_code, 1.0)\n return total * multiplier\n\ndef generate_receipt(total):\n return f\"Total: ${total:.2f}\"\n\ndef process_order(order):\n valid, message = validate_order(order)\n if not valid:\n return message\n total = calculate_total(order)\n total = apply_discount(total, order.get(\"discount_code\"))\n return generate_receipt(total)",
|
| 294 |
+
"unit_test_setup":"import unittest\nimport inspect\n\n",
|
| 295 |
"unit_test_assertion":"class TestRefactoring(unittest.TestCase):\n def test_functionality(self):\n order = {\n \"items\": [{\"price\": 100, \"quantity\": 1}],\n \"discount_code\": \"SAVE20\"\n }\n self.assertEqual(process_order(order), \"Total: $80.00\")\n self.assertEqual(process_order({}), \"Order must contain items\")\n\n def test_structure(self):\n g = globals()\n required = ['validate_order', 'calculate_total', 'apply_discount', 'generate_receipt']\n for func in required:\n self.assertIn(func, g, f\"Missing required function: {func}\")\n \n def test_complexity_reduction(self):\n src = inspect.getsource(apply_discount)\n \n has_dict = \"{\" in src or \"dict(\" in src\n \n if_count = src.count(\"if \") + src.count(\"elif \")\n \n if not has_dict and if_count > 1:\n self.fail(\"You used multiple if/elif statements. Please use a Dictionary/Map constant to reduce code complexity.\")\n\nif __name__ == '__main__':\n unittest.main()",
|
| 296 |
"comment":"the solution MUST split the origial function into the specified smaller functions, use the same method signature, and use a constant for the discount logic, while preserving the same functionality"
|
| 297 |
}
|
|
|
|
| 308 |
"prompt_en":"This function retrieves the names of all senior members from a any team in a nested structure. Refactor the method to use list comprehensions.",
|
| 309 |
"prompt_nl":"Deze functie haalt de namen op van alle senior leden van elk team in een geneste structuur. Herstructureer de methode om list comprehensions te gebruiken.",
|
| 310 |
"code_snippet_input":"def get_seniors_loop(data):\n seniors = []\n for team in data:\n for member in team['members']:\n if member['role'] == 'Senior':\n seniors.append(member['name'])\n return seniors",
|
| 311 |
+
"canonical_solution":"def get_seniors_loop(data):\n return [\n member['name']\n for team in data\n for member in team['members']\n if member['role'] == 'Senior'\n ]",
|
| 312 |
"unit_test_setup":"import unittest\nimport inspect\n\n",
|
| 313 |
"unit_test_assertion":"class TestListComp(unittest.TestCase):\n def test_behavior(self):\n data = [\n {'members': [{'name': 'Alice', 'role': 'Junior'}, {'name': 'Bob', 'role': 'Senior'}]},\n {'members': [{'name': 'Charlie', 'role': 'Senior'}, {'name': 'Dave', 'role': 'Lead'}]}\n ]\n expected = ['Bob', 'Charlie']\n self.assertEqual(get_seniors_loop(data), expected)\n self.assertEqual(get_seniors_loop([]), [])\n\n def test_structure(self):\n src = inspect.getsource(get_seniors_loop)\n \n if \"append(\" in src:\n self.fail(\"You are still using .append(). Use a list comprehension instead.\")\n \n if \"[\" not in src or \"]\" not in src:\n self.fail(\"List comprehension brackets [] not found.\")\n\nif __name__ == '__main__':\n unittest.main()",
|
| 314 |
"comment":"The solution MUST keep the same functionality, but change the implementation from nested for loops to a list comprehension."
|