@booklib/skills 1.2.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CONTRIBUTING.md +122 -0
  2. package/README.md +20 -2
  3. package/ROADMAP.md +36 -0
  4. package/animation-at-work/evals/evals.json +44 -0
  5. package/animation-at-work/examples/after.md +64 -0
  6. package/animation-at-work/examples/before.md +35 -0
  7. package/animation-at-work/scripts/audit_animations.py +295 -0
  8. package/bin/skills.js +552 -42
  9. package/clean-code-reviewer/SKILL.md +109 -1
  10. package/clean-code-reviewer/evals/evals.json +121 -3
  11. package/clean-code-reviewer/examples/after.md +48 -0
  12. package/clean-code-reviewer/examples/before.md +33 -0
  13. package/clean-code-reviewer/references/api_reference.md +158 -0
  14. package/clean-code-reviewer/references/practices-catalog.md +282 -0
  15. package/clean-code-reviewer/references/review-checklist.md +254 -0
  16. package/clean-code-reviewer/scripts/pre-review.py +206 -0
  17. package/data-intensive-patterns/evals/evals.json +43 -0
  18. package/data-intensive-patterns/examples/after.md +61 -0
  19. package/data-intensive-patterns/examples/before.md +38 -0
  20. package/data-intensive-patterns/scripts/adr.py +213 -0
  21. package/data-pipelines/evals/evals.json +45 -0
  22. package/data-pipelines/examples/after.md +97 -0
  23. package/data-pipelines/examples/before.md +37 -0
  24. package/data-pipelines/scripts/new_pipeline.py +444 -0
  25. package/design-patterns/evals/evals.json +46 -0
  26. package/design-patterns/examples/after.md +52 -0
  27. package/design-patterns/examples/before.md +29 -0
  28. package/design-patterns/scripts/scaffold.py +807 -0
  29. package/domain-driven-design/SKILL.md +120 -0
  30. package/domain-driven-design/evals/evals.json +48 -0
  31. package/domain-driven-design/examples/after.md +80 -0
  32. package/domain-driven-design/examples/before.md +43 -0
  33. package/domain-driven-design/scripts/scaffold.py +421 -0
  34. package/effective-java/evals/evals.json +46 -0
  35. package/effective-java/examples/after.md +83 -0
  36. package/effective-java/examples/before.md +37 -0
  37. package/effective-java/scripts/checkstyle_setup.py +211 -0
  38. package/effective-kotlin/evals/evals.json +45 -0
  39. package/effective-kotlin/examples/after.md +36 -0
  40. package/effective-kotlin/examples/before.md +38 -0
  41. package/effective-python/evals/evals.json +44 -0
  42. package/effective-python/examples/after.md +56 -0
  43. package/effective-python/examples/before.md +40 -0
  44. package/effective-python/references/api_reference.md +218 -0
  45. package/effective-python/references/practices-catalog.md +483 -0
  46. package/effective-python/references/review-checklist.md +190 -0
  47. package/effective-python/scripts/lint.py +173 -0
  48. package/kotlin-in-action/evals/evals.json +43 -0
  49. package/kotlin-in-action/examples/after.md +53 -0
  50. package/kotlin-in-action/examples/before.md +39 -0
  51. package/kotlin-in-action/scripts/setup_detekt.py +224 -0
  52. package/lean-startup/evals/evals.json +43 -0
  53. package/lean-startup/examples/after.md +80 -0
  54. package/lean-startup/examples/before.md +34 -0
  55. package/lean-startup/scripts/new_experiment.py +286 -0
  56. package/microservices-patterns/SKILL.md +140 -0
  57. package/microservices-patterns/evals/evals.json +45 -0
  58. package/microservices-patterns/examples/after.md +69 -0
  59. package/microservices-patterns/examples/before.md +40 -0
  60. package/microservices-patterns/scripts/new_service.py +583 -0
  61. package/package.json +2 -8
  62. package/refactoring-ui/evals/evals.json +45 -0
  63. package/refactoring-ui/examples/after.md +85 -0
  64. package/refactoring-ui/examples/before.md +58 -0
  65. package/refactoring-ui/scripts/audit_css.py +250 -0
  66. package/skill-router/SKILL.md +142 -0
  67. package/skill-router/evals/evals.json +38 -0
  68. package/skill-router/examples/after.md +63 -0
  69. package/skill-router/examples/before.md +39 -0
  70. package/skill-router/references/api_reference.md +24 -0
  71. package/skill-router/references/routing-heuristics.md +89 -0
  72. package/skill-router/references/skill-catalog.md +156 -0
  73. package/skill-router/scripts/route.py +266 -0
  74. package/storytelling-with-data/evals/evals.json +47 -0
  75. package/storytelling-with-data/examples/after.md +50 -0
  76. package/storytelling-with-data/examples/before.md +33 -0
  77. package/storytelling-with-data/scripts/chart_review.py +301 -0
  78. package/system-design-interview/evals/evals.json +45 -0
  79. package/system-design-interview/examples/after.md +94 -0
  80. package/system-design-interview/examples/before.md +27 -0
  81. package/system-design-interview/scripts/new_design.py +421 -0
  82. package/using-asyncio-python/evals/evals.json +43 -0
  83. package/using-asyncio-python/examples/after.md +68 -0
  84. package/using-asyncio-python/examples/before.md +39 -0
  85. package/using-asyncio-python/scripts/check_blocking.py +270 -0
  86. package/web-scraping-python/evals/evals.json +46 -0
  87. package/web-scraping-python/examples/after.md +109 -0
  88. package/web-scraping-python/examples/before.md +40 -0
  89. package/web-scraping-python/scripts/new_scraper.py +231 -0
  90. /package/{effective-python-skill → effective-python}/SKILL.md +0 -0
  91. /package/{effective-python-skill → effective-python}/ref-01-pythonic-thinking.md +0 -0
  92. /package/{effective-python-skill → effective-python}/ref-02-lists-and-dicts.md +0 -0
  93. /package/{effective-python-skill → effective-python}/ref-03-functions.md +0 -0
  94. /package/{effective-python-skill → effective-python}/ref-04-comprehensions-generators.md +0 -0
  95. /package/{effective-python-skill → effective-python}/ref-05-classes-interfaces.md +0 -0
  96. /package/{effective-python-skill → effective-python}/ref-06-metaclasses-attributes.md +0 -0
  97. /package/{effective-python-skill → effective-python}/ref-07-concurrency.md +0 -0
  98. /package/{effective-python-skill → effective-python}/ref-08-robustness-performance.md +0 -0
  99. /package/{effective-python-skill → effective-python}/ref-09-testing-debugging.md +0 -0
  100. /package/{effective-python-skill → effective-python}/ref-10-collaboration.md +0 -0
@@ -0,0 +1,211 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ checkstyle_setup.py - Set up Checkstyle with an Effective Java-aligned configuration.
4
+
5
+ Usage:
6
+ python checkstyle_setup.py [--output-dir ./]
7
+
8
+ Generates:
9
+ effective-java-checkstyle.xml - Checkstyle rules mapped to Effective Java items
10
+ run_checkstyle.sh - Shell script to run Checkstyle on src/
11
+
12
+ Each config section references the Effective Java item it enforces.
13
+ """
14
+
15
+ import argparse
16
+ import os
17
+ import pathlib
18
+ import stat
19
+ import sys
20
+ import urllib.request
21
+ import urllib.error
22
+
23
+ CHECKSTYLE_VERSION = "10.14.2"
24
+ CHECKSTYLE_JAR = f"checkstyle-{CHECKSTYLE_VERSION}-all.jar"
25
+ CHECKSTYLE_URL = (
26
+ f"https://github.com/checkstyle/checkstyle/releases/download/"
27
+ f"checkstyle-{CHECKSTYLE_VERSION}/{CHECKSTYLE_JAR}"
28
+ )
29
+
30
+ CHECKSTYLE_XML = """\
31
+ <?xml version="1.0"?>
32
+ <!DOCTYPE module PUBLIC
33
+ "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
34
+ "https://checkstyle.org/dtds/configuration_1_3.dtd">
35
+
36
+ <!--
37
+ Effective Java - Checkstyle Configuration
38
+ Each module references the Effective Java item it enforces.
39
+ Book: "Effective Java" by Joshua Bloch, 3rd Edition.
40
+ -->
41
+ <module name="Checker">
42
+ <property name="severity" value="warning"/>
43
+
44
+ <module name="TreeWalker">
45
+
46
+ <!--
47
+ Item 15: Minimize the accessibility of classes and members.
48
+ Prefer private fields; expose only what is necessary.
49
+ -->
50
+ <module name="VisibilityModifier">
51
+ <property name="protectedAllowed" value="false"/>
52
+ <property name="publicMemberPattern" value="^serialVersionUID$"/>
53
+ </module>
54
+
55
+ <!--
56
+ Item 17: Minimize mutability — utility/helper classes should be final.
57
+ FinalClass flags classes with only private constructors that are not final.
58
+ -->
59
+ <module name="FinalClass"/>
60
+
61
+ <!--
62
+ Item 10: Obey the general contract when overriding equals.
63
+ Always override hashCode when you override equals.
64
+ -->
65
+ <module name="EqualsHashCode"/>
66
+
67
+ <!--
68
+ Item 34: Use enums instead of int constants.
69
+ Magic numbers in code signal that an enum or named constant should be used.
70
+ -->
71
+ <module name="MagicNumber">
72
+ <property name="ignoreNumbers" value="-1, 0, 1, 2"/>
73
+ <property name="ignoreAnnotation" value="true"/>
74
+ <property name="ignoreHashCodeMethod" value="true"/>
75
+ </module>
76
+
77
+ <!--
78
+ Item 77: Don't ignore exceptions.
79
+ Empty catch blocks hide failures; always handle or rethrow.
80
+ -->
81
+ <module name="EmptyCatchBlock">
82
+ <property name="exceptionVariableName" value="expected|ignore"/>
83
+ </module>
84
+
85
+ <!--
86
+ Item 2: Consider a builder when faced with many constructor parameters.
87
+ More than 3 parameters is a signal to introduce a Builder.
88
+ -->
89
+ <module name="ParameterNumber">
90
+ <property name="max" value="3"/>
91
+ <property name="tokens" value="METHOD_DEF, CTOR_DEF"/>
92
+ </module>
93
+
94
+ <!--
95
+ General best practice aligned with Effective Java's emphasis on small,
96
+ focused methods. Methods longer than 30 lines are harder to reason about.
97
+ -->
98
+ <module name="MethodLength">
99
+ <property name="max" value="30"/>
100
+ <property name="countEmpty" value="false"/>
101
+ </module>
102
+
103
+ <!--
104
+ Item 11: Always override toString.
105
+ Not directly checkable, but HideUtilityClassConstructor complements
106
+ Item 4 (enforce non-instantiability with private constructor).
107
+ -->
108
+ <module name="HideUtilityClassConstructor"/>
109
+
110
+ <!--
111
+ Item 57: Minimize the scope of local variables.
112
+ Inner assignments make scope harder to reason about.
113
+ -->
114
+ <module name="InnerAssignment"/>
115
+
116
+ <!--
117
+ Item 67: Optimize judiciously — avoid redundant string concatenation in loops.
118
+ -->
119
+ <module name="StringLiteralEquality"/>
120
+
121
+ </module>
122
+ </module>
123
+ """
124
+
125
+ RUN_SCRIPT = """\
126
+ #!/usr/bin/env bash
127
+ # run_checkstyle.sh
128
+ # Runs Checkstyle with the Effective Java configuration against src/
129
+ # Generated by checkstyle_setup.py
130
+
131
+ set -euo pipefail
132
+
133
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
134
+ JAR="${SCRIPT_DIR}/{jar}"
135
+ CONFIG="${SCRIPT_DIR}/effective-java-checkstyle.xml"
136
+ SRC_DIR="${1:-src}"
137
+
138
+ if [[ ! -f "$JAR" ]]; then
139
+ echo "ERROR: Checkstyle jar not found at $JAR"
140
+ echo "Run: python checkstyle_setup.py --output-dir \\"$(dirname "$JAR")\\""
141
+ exit 1
142
+ fi
143
+
144
+ if [[ ! -d "$SRC_DIR" ]]; then
145
+ echo "ERROR: Source directory not found: $SRC_DIR"
146
+ echo "Usage: ./run_checkstyle.sh [src-dir]"
147
+ exit 1
148
+ fi
149
+
150
+ echo "Running Checkstyle on $SRC_DIR ..."
151
+ java -jar "$JAR" -c "$CONFIG" -r "$SRC_DIR"
152
+ echo "Done."
153
+ """.format(jar=CHECKSTYLE_JAR)
154
+
155
+
156
+ def download_jar(output_dir: pathlib.Path) -> bool:
157
+ jar_path = output_dir / CHECKSTYLE_JAR
158
+ if jar_path.exists():
159
+ print(f"Checkstyle jar already present: {jar_path}")
160
+ return True
161
+ print(f"Downloading Checkstyle {CHECKSTYLE_VERSION} from GitHub ...")
162
+ try:
163
+ urllib.request.urlretrieve(CHECKSTYLE_URL, jar_path)
164
+ print(f"Downloaded: {jar_path}")
165
+ return True
166
+ except urllib.error.URLError as exc:
167
+ print(f"Download failed: {exc}")
168
+ print()
169
+ print("To install manually:")
170
+ print(f" curl -L -o {jar_path} \\")
171
+ print(f" {CHECKSTYLE_URL}")
172
+ return False
173
+
174
+
175
+ def write_file(path: pathlib.Path, content: str, executable: bool = False) -> None:
176
+ path.write_text(content, encoding="utf-8")
177
+ if executable:
178
+ path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
179
+ print(f"Wrote: {path}")
180
+
181
+
182
+ def main() -> None:
183
+ parser = argparse.ArgumentParser(
184
+ description="Set up Checkstyle with an Effective Java-aligned configuration."
185
+ )
186
+ parser.add_argument(
187
+ "--output-dir",
188
+ default=".",
189
+ help="Directory to write config files and download the jar (default: ./)",
190
+ )
191
+ args = parser.parse_args()
192
+
193
+ output_dir = pathlib.Path(args.output_dir).resolve()
194
+ output_dir.mkdir(parents=True, exist_ok=True)
195
+
196
+ download_jar(output_dir)
197
+
198
+ write_file(output_dir / "effective-java-checkstyle.xml", CHECKSTYLE_XML)
199
+ write_file(output_dir / "run_checkstyle.sh", RUN_SCRIPT, executable=True)
200
+
201
+ print()
202
+ print("Setup complete.")
203
+ print(f" Config : {output_dir / 'effective-java-checkstyle.xml'}")
204
+ print(f" Runner : {output_dir / 'run_checkstyle.sh'}")
205
+ print()
206
+ print("Run Checkstyle:")
207
+ print(f" cd {output_dir} && ./run_checkstyle.sh [src-dir]")
208
+
209
+
210
+ if __name__ == "__main__":
211
+ main()
@@ -0,0 +1,45 @@
1
+ {
2
+ "evals": [
3
+ {
4
+ "id": "eval-01-mutable-var-nullable-overuse",
5
+ "prompt": "Review this Kotlin code:\n\n```kotlin\nclass UserSession {\n var userId: String? = null\n var userName: String? = null\n var email: String? = null\n var isLoggedIn: Boolean = false\n var loginTime: Long? = null\n var sessionToken: String? = null\n var permissionLevel: Int = 0\n \n fun login(userId: String, userName: String, email: String, token: String, level: Int) {\n this.userId = userId\n this.userName = userName\n this.email = email\n this.isLoggedIn = true\n this.loginTime = System.currentTimeMillis()\n this.sessionToken = token\n this.permissionLevel = level\n }\n \n fun logout() {\n this.userId = null\n this.userName = null\n this.email = null\n this.isLoggedIn = false\n this.loginTime = null\n this.sessionToken = null\n this.permissionLevel = 0\n }\n \n fun getDisplayName(): String {\n if (userName != null) {\n return userName!!\n }\n return \"Guest\"\n }\n \n fun isAdmin(): Boolean {\n if (permissionLevel != null) {\n return permissionLevel!! >= 10\n }\n return false\n }\n}\n```",
6
+ "expectations": [
7
+ "Flags Item 1 (Limit mutability): all properties are var but most could be val if the design is reconsidered — the entire class should likely be replaced with two states (LoggedIn / LoggedOut) using a sealed class",
8
+ "Flags Item 8 (Avoid !! operator): getDisplayName() uses userName!! after a null check — should use userName ?: \"Guest\" with Elvis or smart cast",
9
+ "Notes that permissionLevel is Int (non-nullable) but isAdmin() checks 'if (permissionLevel != null)' — this check is always true and indicates confusion about nullability",
10
+ "Flags that nullable types (String?, Long?) are used for all properties even though they are only null in the logged-out state — this is a design smell, not a nullability need",
11
+ "Suggests modeling this with a sealed class: sealed class SessionState with data class LoggedIn(...) and object LoggedOut — making illegal states unrepresentable",
12
+ "References Item 2 (Minimize variable scope): all these properties have class-wide scope when they only have meaning in the logged-in state",
13
+ "Notes that the login() function taking 5 positional parameters (Item 17: named arguments) is error-prone — a data class or named arguments should be used"
14
+ ]
15
+ },
16
+ {
17
+ "id": "eval-02-missing-data-class-extension",
18
+ "prompt": "Review this Kotlin code:\n\n```kotlin\nclass Point {\n var x: Double\n var y: Double\n \n constructor(x: Double, y: Double) {\n this.x = x\n this.y = y\n }\n \n fun distanceTo(other: Point): Double {\n val dx = this.x - other.x\n val dy = this.y - other.y\n return Math.sqrt(dx * dx + dy * dy)\n }\n \n override fun toString(): String {\n return \"Point(\" + x + \", \" + y + \")\"\n }\n}\n\nfun translatePoints(points: List<Point>, dx: Double, dy: Double): List<Point> {\n val result = mutableListOf<Point>()\n for (point in points) {\n val newPoint = Point(point.x + dx, point.y + dy)\n result.add(newPoint)\n }\n return result\n}\n\nfun findClosestTo(points: List<Point>, target: Point): Point? {\n var closest: Point? = null\n var minDist = Double.MAX_VALUE\n for (point in points) {\n val dist = point.distanceTo(target)\n if (dist < minDist) {\n minDist = dist\n closest = point\n }\n }\n return closest\n}\n```",
19
+ "expectations": [
20
+ "Flags that Point should be a data class — it has structural equality semantics but lacks the data modifier, meaning equals() and hashCode() use reference equality by default",
21
+ "Flags Item 1 (Limit mutability): Point fields are var but a geometric point is naturally immutable — they should be val",
22
+ "Notes that translatePoints uses an imperative for-loop with a mutable list where map { Point(it.x + dx, it.y + dy) } is idiomatic and more readable",
23
+ "Notes that findClosestTo uses an imperative loop where minByOrNull { it.distanceTo(target) } from the stdlib is idiomatic (Item 20: use stdlib algorithms)",
24
+ "Points out that Math.sqrt() is Java interop — Kotlin has kotlin.math.sqrt() which is more idiomatic",
25
+ "May suggest an extension function Point.translate(dx: Double, dy: Double) as a cleaner API that could also be placed in the data class with copy()",
26
+ "Notes that the string concatenation in toString() is replaced automatically by data class, but if kept manually, string templates are idiomatic: \"Point($x, $y)\""
27
+ ]
28
+ },
29
+ {
30
+ "id": "eval-03-idiomatic-kotlin-already-good",
31
+ "prompt": "Review this Kotlin code:\n\n```kotlin\nsealed interface PaymentResult {\n data class Success(val transactionId: String, val amount: Money) : PaymentResult\n data class Failure(val code: ErrorCode, val message: String) : PaymentResult\n data object Pending : PaymentResult\n}\n\nenum class ErrorCode { INSUFFICIENT_FUNDS, CARD_DECLINED, NETWORK_ERROR, FRAUD_DETECTED }\n\n@JvmInline\nvalue class Money(val cents: Long) {\n init {\n require(cents >= 0) { \"Money cannot be negative: $cents cents\" }\n }\n \n operator fun plus(other: Money) = Money(cents + other.cents)\n operator fun minus(other: Money): Money {\n require(other.cents <= cents) { \"Cannot subtract more than available\" }\n return Money(cents - other.cents)\n }\n \n override fun toString() = \"$${cents / 100}.${(cents % 100).toString().padStart(2, '0')}\"\n}\n\nfun interface PaymentGateway {\n suspend fun charge(amount: Money, token: String): PaymentResult\n}\n\nsuspend fun processWithRetry(\n gateway: PaymentGateway,\n amount: Money,\n token: String,\n maxAttempts: Int = 3\n): PaymentResult {\n repeat(maxAttempts) { attempt ->\n val result = gateway.charge(amount, token)\n when (result) {\n is PaymentResult.Success -> return result\n is PaymentResult.Failure -> {\n if (result.code != ErrorCode.NETWORK_ERROR || attempt == maxAttempts - 1) return result\n }\n PaymentResult.Pending -> return result\n }\n }\n return PaymentResult.Failure(ErrorCode.NETWORK_ERROR, \"Max retries exceeded\")\n}\n```",
32
+ "expectations": [
33
+ "Recognizes this is already idiomatic, well-designed Kotlin and says so explicitly",
34
+ "Praises the use of sealed interface for PaymentResult — exhaustive when expressions, extensible outside the module",
35
+ "Praises @JvmInline value class Money — Item 46/49 efficiency (no boxing overhead), type-safe, with require() precondition (Item 5)",
36
+ "Praises operator overloading on Money — follows convention (plus/minus) and is semantically meaningful (Item 12)",
37
+ "Praises fun interface PaymentGateway — SAM interface enabling lambda usage, clean abstraction",
38
+ "Praises using repeat with when instead of a for-loop with if/else — idiomatic control flow",
39
+ "Praises the sealed hierarchy discriminating between Pending and Failure so the retry logic doesn't retry non-network errors",
40
+ "Does NOT manufacture fake issues just to have something to say",
41
+ "May suggest minor optional improvements (e.g., a Currency field on Money for multi-currency support) but clearly frames them as out-of-scope for the given context"
42
+ ]
43
+ }
44
+ ]
45
+ }
@@ -0,0 +1,36 @@
1
+ # After
2
+
3
+ Idiomatic Kotlin with `val` properties, non-null types where absence is not meaningful, and a functional pipeline replacing the manual while loop.
4
+
5
+ ```kotlin
6
+ class UserReportGenerator(
7
+ private val users: List<User>,
8
+ private val reportTitle: String,
9
+ private val includeInactive: Boolean = false,
10
+ ) {
11
+
12
+ fun generateSummary(): String {
13
+ val activeUsers = if (includeInactive) users else users.filter { it.active }
14
+
15
+ val lines = activeUsers.map { user ->
16
+ buildString {
17
+ append("${user.name} (${user.email})")
18
+ user.role?.let { append(" - $it") }
19
+ }
20
+ }
21
+
22
+ return buildString {
23
+ appendLine(reportTitle)
24
+ lines.forEach(::appendLine)
25
+ }
26
+ }
27
+ }
28
+ ```
29
+
30
+ Key improvements:
31
+ - Constructor parameters replace mutable properties (Item 1: Limit Mutability) — the generator is now immutable after construction
32
+ - `users: List<User>` and `reportTitle: String` are non-null types; nullability would only be meaningful if absence were valid (Item 8: Handle Nulls Properly)
33
+ - `filter`, `map`, and `buildString` replace the manual `while` index loop — idiomatic stdlib use (Item 20: Use stdlib algorithms)
34
+ - `user.role?.let { append(" - $it") }` replaces the null-check `if` block with a safe-call chain (Item 8)
35
+ - `includeInactive = false` as a default parameter eliminates the need for an overloaded constructor (Item 34: Consider named and optional args)
36
+ - `generateSummary()` returns `String` (non-null) — the empty report is a valid empty string, not `null` (Item 7: Prefer null or Failure over exceptions for expected failures)
@@ -0,0 +1,38 @@
1
+ # Before
2
+
3
+ Kotlin code written in Java style with `var` everywhere, misused nullability, and index-based loops that ignore idiomatic Kotlin features.
4
+
5
+ ```kotlin
6
+ class UserReportGenerator {
7
+
8
+ var users: MutableList<User>? = null
9
+ var reportTitle: String? = null
10
+ var includeInactive: Boolean = false
11
+
12
+ fun generateSummary(): String? {
13
+ var result = ""
14
+ if (users == null) {
15
+ return null
16
+ }
17
+ result = result + reportTitle + "\n"
18
+ var i = 0
19
+ while (i < users!!.size) {
20
+ val user = users!![i]
21
+ if (includeInactive == false) {
22
+ if (user.active == false) {
23
+ i++
24
+ continue
25
+ }
26
+ }
27
+ var line = ""
28
+ line = line + user.name + " (" + user.email + ")"
29
+ if (user.role != null) {
30
+ line = line + " - " + user.role
31
+ }
32
+ result = result + line + "\n"
33
+ i++
34
+ }
35
+ return result
36
+ }
37
+ }
38
+ ```
@@ -0,0 +1,44 @@
1
+ {
2
+ "evals": [
3
+ {
4
+ "id": "eval-01-loop-except-mutable-default",
5
+ "prompt": "Review this Python code:\n\n```python\ndef process_orders(orders, results=[]):\n for i in range(len(orders)):\n order = orders[i]\n try:\n total = order['price'] * order['quantity']\n results.append({'id': order['id'], 'total': total})\n except:\n pass\n\n processed = []\n for item in results:\n processed.append(item['total'])\n return processed\n\n\ndef get_high_value(orders, threshold):\n high = []\n for order in orders:\n if order['total'] > threshold:\n high.append(order)\n return high\n```",
6
+ "expectations": [
7
+ "Flags the mutable default argument `results=[]` as a critical bug (Item 24: Use None and docstrings for dynamic default arguments)",
8
+ "Flags bare `except:` that silently swallows all exceptions including KeyboardInterrupt and SystemExit (Item 65: always catch specific exception types)",
9
+ "Identifies `for i in range(len(orders))` as non-idiomatic; recommends `for order in orders` with enumerate if index is needed (Item 7)",
10
+ "Identifies the manual list-building loop in `process_orders` that should be a list comprehension (Item 27)",
11
+ "Identifies the manual list-building loop in `get_high_value` that should be a list comprehension (Item 27)",
12
+ "Provides a corrected version that uses `None` as default and initializes inside the function",
13
+ "Provides corrected versions using list comprehensions for both loops"
14
+ ]
15
+ },
16
+ {
17
+ "id": "eval-02-class-missing-dataclass",
18
+ "prompt": "Review this Python code:\n\n```python\nclass Product:\n def __init__(self, name, price, category, in_stock=True):\n self.name = name\n self.price = price\n self.category = category\n self.in_stock = in_stock\n\n def get_name(self):\n return self.name\n\n def set_price(self, price):\n if price < 0:\n raise ValueError('Price cannot be negative')\n self.price = price\n\n def is_available(self):\n return self.in_stock == True\n\n\nclass ProductCatalog:\n def __init__(self):\n self.__items = []\n\n def add(self, product):\n self.__items.append(product)\n\n def find_by_category(self, category):\n result = []\n for p in self.__items:\n if p.category == category:\n result.append(p)\n return result\n```",
19
+ "expectations": [
20
+ "Identifies that `Product` is a plain data holder and recommends converting it to a `@dataclass` — eliminates the boilerplate `__init__`, provides automatic `__repr__` and `__eq__`, and makes the data-holder intent explicit (Pythonic class design; Items 37–43: class and interface guidelines)",
21
+ "Flags `get_name()` as a Java-style getter; Pythonic code uses direct attribute access (Item 44: use plain attributes over getter/setter methods)",
22
+ "Flags `set_price()` as a Java-style setter; recommends replacing with `@property` with a setter that includes the validation (Item 44)",
23
+ "Flags `self.in_stock == True` comparison; should be `return self.in_stock` (Item 2: Follow the PEP 8 Style Guide — never compare to True with ==)",
24
+ "Flags `self.__items` name mangling via double underscore; recommends single underscore `_items` for internal use (Item 42: prefer public attributes)",
25
+ "Notes absence of `__repr__` on `Product` making debugging harder; a dataclass provides this automatically",
26
+ "Identifies the manual list-building loop in `find_by_category` as a candidate for a list comprehension (Item 27)",
27
+ "Provides a corrected version using `@dataclass` with `@property` for price validation"
28
+ ]
29
+ },
30
+ {
31
+ "id": "eval-03-idiomatic-python-already-good",
32
+ "prompt": "Review this Python code:\n\n```python\nfrom contextlib import contextmanager\nfrom typing import Generator, Iterator\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\n@contextmanager\ndef managed_connection(host: str, port: int) -> Generator:\n \"\"\"Open a connection and ensure it is closed on exit.\"\"\"\n conn = _connect(host, port)\n try:\n logger.debug('Opened connection to %s:%d', host, port)\n yield conn\n finally:\n conn.close()\n logger.debug('Closed connection to %s:%d', host, port)\n\n\ndef read_records(filepath: str) -> Iterator[dict]:\n \"\"\"Yield records from a newline-delimited JSON file one at a time.\"\"\"\n with open(filepath, encoding='utf-8') as fh:\n for line in fh:\n line = line.strip()\n if line:\n yield _parse(line)\n\n\ndef process_batch(records: Iterator[dict], batch_size: int = 500) -> Iterator[list]:\n \"\"\"Yield successive fixed-size batches from an iterator.\"\"\"\n batch: list[dict] = []\n for record in records:\n batch.append(record)\n if len(batch) >= batch_size:\n yield batch\n batch = []\n if batch:\n yield batch\n```",
33
+ "expectations": [
34
+ "Recognizes this is already idiomatic, well-structured Python and says so explicitly",
35
+ "Praises the use of `@contextmanager` for resource management (Item 66: use contextlib for reusable try/finally patterns)",
36
+ "Praises the generator function `read_records` for memory-efficient file reading (Item 30: consider generators instead of returning lists)",
37
+ "Praises the generator function `process_batch` for lazy batch production without loading the entire sequence into memory (Item 30)",
38
+ "Praises type annotations and docstrings on all public functions (Item 84: Write docstrings for all public APIs)",
39
+ "Does NOT manufacture issues to appear thorough; any suggestions are explicitly framed as minor optional improvements",
40
+ "May note minor optional suggestions such as using `itertools.islice` for batching, but frames them as stylistic alternatives, not violations"
41
+ ]
42
+ }
43
+ ]
44
+ }
@@ -0,0 +1,56 @@
1
+ # After
2
+
3
+ Pythonic code with specific exception handling, a dataclass for structure, a comprehension for filtering, and no mutable default argument.
4
+
5
+ ```python
6
+ import requests
7
+ from dataclasses import dataclass
8
+ from requests.exceptions import HTTPError, ConnectionError, Timeout
9
+
10
+ @dataclass
11
+ class Order:
12
+ id: str
13
+ customer: str
14
+ total: float
15
+
16
+
17
+ def fetch_orders(api_url: str, filters: dict | None = None) -> list[Order]:
18
+ """Fetch completed orders from the partner API.
19
+
20
+ Args:
21
+ api_url: Base URL for the orders endpoint.
22
+ filters: Optional extra query parameters. Defaults to empty dict.
23
+
24
+ Returns:
25
+ List of Order dataclasses for all completed orders with positive totals.
26
+
27
+ Raises:
28
+ HTTPError: If the API returns a non-2xx response.
29
+ ConnectionError: If the API is unreachable.
30
+ Timeout: If the request exceeds the timeout threshold.
31
+ """
32
+ params = {"status": "completed", **(filters or {})}
33
+
34
+ response = requests.get(api_url, params=params, timeout=10)
35
+ response.raise_for_status() # raises HTTPError for 4xx/5xx
36
+
37
+ data = response.json()
38
+ return [
39
+ Order(id=item["id"], customer=item["customer_name"], total=item["total"])
40
+ for item in data["orders"]
41
+ if item["total"] > 0
42
+ ]
43
+
44
+
45
+ def summarize(orders: list[Order]) -> float:
46
+ """Return the grand total revenue across all orders."""
47
+ return sum(order.total for order in orders)
48
+ ```
49
+
50
+ Key improvements:
51
+ - `filters: dict | None = None` with `filters or {}` fixes the mutable default argument bug (Item 24: Use None as a default for mutable default arguments)
52
+ - Specific exceptions `HTTPError`, `ConnectionError`, `Timeout` replace the bare `except` clause — errors propagate appropriately and `KeyboardInterrupt` is no longer swallowed (Item 65: Handle exceptions specifically)
53
+ - `response.raise_for_status()` replaces silent failure on bad HTTP responses
54
+ - List comprehension with inline `if` replaces the manual `append` loop (Item 27: Use Comprehensions Instead of map and filter)
55
+ - `@dataclass` replaces a raw `dict` for the order structure — typed, readable, and self-documenting (Item 37: Compose Classes Instead of Nesting Many Levels of Built-in Types)
56
+ - `sum(order.total for order in orders)` in `summarize` is a single idiomatic expression, no intermediate list needed
@@ -0,0 +1,40 @@
1
+ # Before
2
+
3
+ Python ETL helper with a bare `except`, a mutable default argument bug, and a manual loop that should be a comprehension.
4
+
5
+ ```python
6
+ import json
7
+ import requests
8
+
9
+ def fetch_orders(api_url, filters={}):
10
+ # filters dict persists across calls — mutable default arg bug
11
+ filters['status'] = 'completed'
12
+ try:
13
+ response = requests.get(api_url, params=filters)
14
+ data = response.json()
15
+ except:
16
+ # swallows every exception including KeyboardInterrupt
17
+ print("something went wrong")
18
+ return []
19
+
20
+ orders = []
21
+ for item in data['orders']:
22
+ if item['total'] > 0:
23
+ order = {
24
+ 'id': item['id'],
25
+ 'customer': item['customer_name'],
26
+ 'total': item['total'],
27
+ }
28
+ orders.append(order)
29
+ return orders
30
+
31
+
32
+ def summarize(orders):
33
+ totals = []
34
+ for o in orders:
35
+ totals.append(o['total'])
36
+ grand_total = 0
37
+ for t in totals:
38
+ grand_total = grand_total + t
39
+ return grand_total
40
+ ```