### Install Claude Code Plugin Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/README.md Use this command to install the Karpathy skills plugin after adding the marketplace. ```bash /plugin install andrej-karpathy-skills@karpathy-skills ``` -------------------------------- ### Add Project-Specific Guidelines Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/README.md Integrate project-specific rules into your existing CLAUDE.md or create a new one. This example shows how to add rules for TypeScript, API endpoint testing, and error handling patterns. ```markdown ## Project-Specific Guidelines - Use TypeScript strict mode - All API endpoints must have tests - Follow the existing error handling patterns in `src/utils/errors.ts` ``` -------------------------------- ### Create New Project CLAUDE.md Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/README.md Download the CLAUDE.md file for a new project using curl. ```bash curl -o CLAUDE.md https://raw.githubusercontent.com/forrestchang/andrej-karpathy-skills/main/CLAUDE.md ``` -------------------------------- ### Calculate Discount (Simple Implementation) Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/EXAMPLES.md A straightforward Python function to calculate a discount based on amount and percentage. This approach avoids premature abstraction and is suitable for simple use cases. ```python def calculate_discount(amount: float, percent: float) -> float: """Calculate discount amount. percent should be 0-100.""" return amount * (percent / 100) # Usage discount = calculate_discount(100.0, 10.0) # $10 off ``` -------------------------------- ### Define Verifiable Goals for Multi-Step Tasks Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/skills/karpathy-guidelines/SKILL.md When tackling multi-step tasks, outline a brief plan with clear verification steps for each stage. This ensures progress is measurable and reduces ambiguity. ```markdown 1. [Step] → verify: [check] 2. [Step] → verify: [check] 3. [Step] → verify: [check] ``` -------------------------------- ### Python: Add Logging to Upload Function (Matching Style) Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/EXAMPLES.md This snippet demonstrates how to add logging to an existing Python function while strictly adhering to the original code's style, including quote usage, type hints, and boolean return patterns. It shows the correct way to integrate logging without reformatting or adding unsolicited changes. ```diff import logging logger = logging.getLogger(__name__) def upload_file(file_path, destination): logger.info(f'Starting upload: {file_path}') try: with open(file_path, 'rb') as f: data = f.read() response = requests.post(destination, files={'file': data}) if response.status_code == 200: logger.info(f'Upload successful: {file_path}') return True else: logger.error(f'Upload failed: {file_path}, status={response.status_code}') return False except Exception as e: logger.exception(f'Upload error: {file_path}') return False ``` -------------------------------- ### Calculate Discount (Over-engineered Abstraction) Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/EXAMPLES.md This Python code demonstrates an over-engineered solution for calculating discounts using abstract base classes, strategies, and dataclasses. It introduces significant complexity for a task that could be handled more simply. ```python from abc import ABC, abstractmethod from enum import Enum from typing import Protocol, Union from dataclasses import dataclass class DiscountStrategy(ABC): @abstractmethod def calculate(self, amount: float) -> float: pass class PercentageDiscount(DiscountStrategy): def __init__(self, percentage: float): self.percentage = percentage def calculate(self, amount: float) -> float: return amount * (self.percentage / 100) class FixedDiscount(DiscountStrategy): def __init__(self, fixed_amount: float): self.fixed_amount = fixed_amount def calculate(self, amount: float) -> float: return min(self.fixed_amount, amount) @dataclass class DiscountConfig: strategy: DiscountStrategy min_purchase: float = 0.0 max_discount: float = float('inf') class DiscountCalculator: def __init__(self, config: DiscountConfig): self.config = config def apply_discount(self, amount: float) -> float: if amount < self.config.min_purchase: return 0 discount = self.config.strategy.calculate(amount) return min(discount, self.config.max_discount) # Usage requires 30+ lines of setup for a simple calculation ``` -------------------------------- ### Python: Add Logging to Upload Function (Incorrect Reformat) Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/EXAMPLES.md This diff shows an incorrect approach to adding logging, where the LLM reformats the entire function, adds type hints, changes quote styles, and modifies boolean return logic, deviating from the original code's established style. ```diff def upload_file(file_path: str, destination: str) -> bool: """Upload file to destination with logging.""" logger.info(f"Uploading {file_path} to {destination}") try: with open(file_path, "rb") as f: data = f.read() response = requests.post(destination, files={"file": data}) success = response.status_code == 200 if success: logger.info(f"Upload successful: {file_path}") else: logger.error(f"Upload failed: {file_path}, status={response.status_code}") return success except Exception as e: logger.exception(f"Upload error for {file_path}: {e}") return False ``` -------------------------------- ### Add Claude Code Marketplace Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/README.md Use this command to add the marketplace for Claude Code plugins. ```bash /plugin marketplace add forrestchang/andrej-karpathy-skills ``` -------------------------------- ### Save User Preferences to Database (LLM - Unnecessary Features) Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/EXAMPLES.md This class includes speculative features like caching, validation, and notifications that were not requested, demonstrating potential LLM over-engineering. ```python class PreferenceManager: def __init__(self, db, cache=None, validator=None): self.db = db self.cache = cache or InMemoryCache() self.validator = validator or DefaultValidator() def save(self, user_id: int, prefs: dict, merge: bool = True, validate: bool = True, notify: bool = False) -> bool: """Save preferences with optional merging, validation, and notifications.""" if validate: errors = self.validator.validate(prefs) if errors: raise ValidationError(errors) existing = self.get(user_id) if merge else {} if merge: existing.update(prefs) prefs = existing self.db.execute( "UPDATE users SET preferences = ? WHERE id = ?", (json.dumps(prefs), user_id) ) if self.cache: self.cache.set(f"prefs:{user_id}", prefs) if notify: self.notify_preference_change(user_id, prefs) return True def notify_preference_change(self, user_id: int, prefs: dict): # Another 30 lines for a feature nobody asked for pass ``` -------------------------------- ### Append to Existing Project CLAUDE.md Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/README.md Append the CLAUDE.md file to an existing project's CLAUDE.md file. ```bash echo "" >> CLAUDE.md curl https://raw.githubusercontent.com/forrestchang/andrej-karpathy-skills/main/CLAUDE.md >> CLAUDE.md ``` -------------------------------- ### Save User Preferences to Database (Ideal) Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/EXAMPLES.md This function directly addresses the user request to save preferences to the database without unnecessary features like caching or validation. ```python def save_preferences(db, user_id: int, preferences: dict): """Save user preferences to database.""" db.execute( "UPDATE users SET preferences = ? WHERE id = ?", (json.dumps(preferences), user_id) ) ``` -------------------------------- ### Improve Search Speed (Over-engineered) Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/EXAMPLES.md This Python snippet demonstrates an LLM's tendency to silently implement optimizations like caching and async processing for a 'faster search' request, without understanding the user's specific definition of 'faster'. ```python # Adds caching, database indexes, and async processing # without asking which "faster" matters @lru_cache(maxsize=1000) async def search(query: str) -> List[Result]: # ... 200 lines of optimization code ``` -------------------------------- ### Export User Data (Incorrect Assumptions) Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/EXAMPLES.md This Python code incorrectly assumes export scope, file location, and fields without user clarification. It fails to consider pagination or privacy implications. ```python def export_users(format='json'): """Export all users to a file.""" users = User.query.all() if format == 'json': with open('users.json', 'w') as f: json.dump([u.to_dict() for u in users], f) elif format == 'csv': with open('users.csv', 'w') as f: writer = csv.DictWriter(f, fieldnames=['id', 'email', 'name']) writer.writeheader() writer.writerows([u.to_dict() for u in users]) return f"Exported {len(users)} users" ``` -------------------------------- ### Test Sorting with Duplicate Scores (Python) Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/EXAMPLES.md This test case is designed to reproduce an issue with non-deterministic sorting when multiple items share the same score. It asserts the expected scores but highlights the potential for inconsistent ordering of duplicate items. ```python def test_sort_with_duplicate_scores(): """Test sorting when multiple items have same score.""" scores = [ {'name': 'Alice', 'score': 100}, {'name': 'Bob', 'score': 100}, {'name': 'Charlie', 'score': 90}, ] result = sort_scores(scores) # The bug: order is non-deterministic for duplicates # Run this test multiple times, it should be consistent assert result[0]['score'] == 100 assert result[1]['score'] == 100 assert result[2]['score'] == 90 ``` -------------------------------- ### Python: Sort Scores with Duplicate Scores (Buggy Fix) Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/EXAMPLES.md This snippet represents an incorrect attempt to fix a sorting bug. The code immediately changes the sorting logic without first reproducing or verifying the bug, which is a common LLM pitfall. ```python def sort_scores(scores): return sorted(scores, key=lambda x: (-x['score'], x['name'])) ``` -------------------------------- ### Fix Bug in Email Validation (LLM - Too Much) Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/EXAMPLES.md This diff demonstrates an LLM's tendency to over-correct by adding unrequested features like improved email validation and username validation beyond the scope of the bug fix. ```diff def validate_user(user_data): - # Check email format - if not user_data.get('email'): + """Validate user data.""" + email = user_data.get('email', '').strip() + + # Validate email + if not email: raise ValueError("Email required") - - # Basic email validation - if '@' not in user_data['email']: + if '@' not in email or '.' not in email.split('@')[1]: raise ValueError("Invalid email") - # Check username - if not user_data.get('username'): + # Validate username + username = user_data.get('username', '').strip() + if not username: raise ValueError("Username required") + if len(username) < 3: + raise ValueError("Username too short") + if not username.isalnum(): + raise ValueError("Username must be alphanumeric") return True ``` -------------------------------- ### Fix Sorting with Stable Sort (Python) Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/EXAMPLES.md This function implements a stable sort for a list of scores. It sorts primarily by score in descending order and secondarily by name in ascending order to ensure deterministic results for items with identical scores. ```python def sort_scores(scores): """Sort by score descending, then name ascending for ties.""" return sorted(scores, key=lambda x: (-x['score'], x['name'])) ``` -------------------------------- ### Fix Bug in Email Validation (Surgical) Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/EXAMPLES.md This diff shows a surgical fix for a bug where empty emails crash the validator, making only the necessary changes. ```diff def validate_user(user_data): # Check email format - if not user_data.get('email'): + email = user_data.get('email', '') + if not email or not email.strip(): raise ValueError("Email required") # Basic email validation - if '@' not in user_data['email']: + if '@' not in email: raise ValueError("Invalid email") # Check username if not user_data.get('username'): raise ValueError("Username required") return True ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.