# Test · Code Each block exercises all Prism token categories: comments, keywords, strings, numbers, functions, classes, properties, operators, punctuation. --- ## Python ```python # ── Ionian Navigation System ────────────────────────────────────────────────── from __future__ import annotations from dataclasses import dataclass, field from typing import Iterator import math KNOTS_TO_KMH: float = 1.852 MAX_WAYPOINTS: int = 24 TIDE_OFFSET: int = 0x3F # hex literal FLAGS: int = 0b1010 # binary literal EARTH_NM: float = 3_440.065 IONIAN_ISLANDS: tuple[str, ...] = ( "Κέρκυρα", "Λευκάδα", "Κεφαλονιά", "Ιθάκη", "Ζάκυνθος" ) BearingError = type("BearingError", (ValueError,), {}) def validate_bearing(deg: float) -> float: """Normalise a bearing to [0, 360).""" if not (0.0 <= deg < 360.0): deg = deg % 360.0 return round(deg, 2) @dataclass class Position: lat: float lon: float def distance_to(self, other: Position) -> float: """Haversine distance in nautical miles.""" φ1, φ2 = math.radians(self.lat), math.radians(other.lat) dφ = math.radians(other.lat - self.lat) dλ = math.radians(other.lon - self.lon) a = (math.sin(dφ / 2) ** 2 + math.cos(φ1) * math.cos(φ2) * math.sin(dλ / 2) ** 2) return 2 * math.asin(math.sqrt(a)) * EARTH_NM @dataclass class Voyage: origin: str destination: str speed_kn: float = 6.5 waypoints: list[str] = field(default_factory=list) def sail(self, island: str, bearing: float = 0.0) -> None: if island not in IONIAN_ISLANDS: raise ValueError(f"Unknown island: {island!r}") self.waypoints.append(island) def legs(self) -> Iterator[tuple[str, str]]: route = [self.origin, *self.waypoints, self.destination] yield from zip(route, route[1:]) @property def complete(self) -> bool: return bool(self.waypoints) and self.waypoints[-1] == self.destination odyssey = Voyage(origin="Τροία", destination="Ιθάκη", speed_kn=5.0) try: for island, bearing in [("Κέρκυρα", 195.5), ("Ιθάκη", 88.0)]: odyssey.sail(island, bearing) except (ValueError, OverflowError) as exc: print(f"Navigation error: {exc}") speeds = [KNOTS_TO_KMH * odyssey.speed_kn * h for h in range(1, 5)] fmt_leg = lambda a, b: f"{a} → {b}" route = ", ".join(fmt_leg(a, b) for a, b in odyssey.legs()) print(f"Route: {route} Complete: {odyssey.complete!r}") ``` --- ## JavaScript (ES2022) ```javascript // Dragon Catalogue — async fetch with error boundaries const API_BASE = 'https://api.tenebrous-dragon.example/v2'; /** @typedef {{ id: string, name: string, cr: number, habitat: string[] }} DragonEntry */ class DragonCatalogue { #cache = new Map(); #abortController = null; constructor(baseUrl = API_BASE) { this.baseUrl = baseUrl; this.#cache.clear(); } async fetchAll(signal) { const url = `${this.baseUrl}/dragons?limit=100`; const res = await fetch(url, { signal }); if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`); return /** @type {DragonEntry[]} */ (await res.json()); } async getByHabitat(habitat) { if (this.#cache.has(habitat)) return this.#cache.get(habitat); this.#abortController?.abort(); this.#abortController = new AbortController(); try { const all = await this.fetchAll(this.#abortController.signal); const filtered = all.filter(d => d.habitat.includes(habitat)); this.#cache.set(habitat, filtered); return filtered; } catch (err) { if (err.name !== 'AbortError') console.error('Fetch failed:', err); return []; } } *[Symbol.iterator]() { for (const [key, value] of this.#cache) { yield { habitat: key, entries: value }; } } } // Destructuring, rest/spread, optional chaining, nullish coalescing const { name = 'Unknown', cr = 0, habitat: [primary = 'unknown'] = [] } = {}; const dragons = [ { name: 'Sapphire', cr: 15, tags: ['gem', 'psionic'] }, { name: 'Bronze', cr: 18, tags: ['metallic', 'coastal'] }, ]; const sorted = dragons .filter(d => d.cr >= 15) .sort((a, b) => b.cr - a.cr) .map(({ name, cr, tags }) => ({ name, cr, primary: tags[0] ?? 'none' })); const catalogue = new DragonCatalogue(); const coastal = await catalogue.getByHabitat('coastal'); console.log(`Coastal dragons: ${coastal.length ?? 0}`); ``` --- ## TypeScript ```typescript // ── Typed Bestiary with generics, decorators, mapped types ──────────────────── type DragonSize = 'Wyrmling' | 'Young' | 'Adult' | 'Ancient' | 'Greatwyrm'; type Alignment = `${'Lawful' | 'Neutral' | 'Chaotic'} ${'Good' | 'Neutral' | 'Evil'}`; interface CreatureStats { readonly hp: number; readonly ac: number; readonly cr: number; speed: Partial<Record<'walk' | 'fly' | 'swim', number>>; } interface DragonEntry extends CreatureStats { name: string; colour: string; size: DragonSize; align: Alignment; breath: string; habitat: string[]; } type PartialEntry = Partial<DragonEntry>; type RequiredEntry = Required<DragonEntry>; type DragonKeys = keyof DragonEntry; // Generic repository class Repository<T extends { name: string }> { private readonly store = new Map<string, T>(); add(item: T): this { this.store.set(item.name, item); return this; } get(name: string): T | undefined { return this.store.get(name); } filter<K extends keyof T>(key: K, value: T[K]): T[] { return [...this.store.values()].filter(item => item[key] === value); } *[Symbol.iterator](): IterableIterator<T> { yield* this.store.values(); } } // Decorator factory function LogMethod(label: string) { return function (_target: object, key: string, descriptor: PropertyDescriptor) { const original = descriptor.value as (...args: unknown[]) => unknown; descriptor.value = function (...args: unknown[]) { console.log(`[${label}] ${key}(${args.join(', ')})`); return original.apply(this, args); }; return descriptor; }; } class BestiaryService { constructor(private readonly repo: Repository<DragonEntry>) {} @LogMethod('Bestiary') lookup(name: string): DragonEntry | undefined { return this.repo.get(name); } bySize(size: DragonSize): DragonEntry[] { return this.repo.filter('size', size); } } const repo = new Repository<DragonEntry>(); repo .add({ name: 'Sapphire', colour: 'blue', size: 'Ancient', align: 'Lawful Neutral', hp: 297, ac: 20, cr: 22, breath: 'Psychic', habitat: ['Underdark'], speed: { walk: 40, fly: 80 } }) .add({ name: 'Bronze', colour: 'bronze', size: 'Adult', align: 'Lawful Good', hp: 212, ac: 18, cr: 15, breath: 'Lightning', habitat: ['Coastal'], speed: { walk: 40, fly: 80, swim: 40 } }); const service = new BestiaryService(repo); const ancient = service.bySize('Ancient'); console.log(ancient.map(d => `${d.name} (CR ${d.cr})`)); ``` --- ## Bash ```bash #!/usr/bin/env bash # vault-backup.sh -- Backup Obsidian vaults to iCloud set -euo pipefail IFS=\n\t' readonly BACKUP_ROOT="${HOME}/Library/Mobile Documents/com~apple~CloudDocs/Backups" readonly TIMESTAMP=$(date +%Y-%m-%dT%H%M%S) readonly LOG_FILE="${BACKUP_ROOT}/backup-${TIMESTAMP}.log" VAULTS=( "${HOME}/Vaults/Tenebrous-dragon" "${HOME}/Vaults/Arbiters-of-Fate" ) log() { local level="$1"; shift printf '[%s] [%s] %s\n' "$(date -u +%H:%M:%S)" "${level}" "$*" | tee -a "${LOG_FILE}" } backup_vault() { local src="$1" local name name="$(basename "${src}")" local dest="${BACKUP_ROOT}/${name}-${TIMESTAMP}" if [[ ! -d "${src}" ]]; then log ERROR "Source not found: ${src}" return 1 fi log INFO "Backing up ${name} → ${dest}" rsync -av --exclude='.DS_Store' --exclude='*.tmp' \ "${src}/" "${dest}/" 2>&1 | tee -a "${LOG_FILE}" local exit_code=$? if (( exit_code == 0 )); then log INFO "Done: ${name}" else log ERROR "rsync exited with code ${exit_code}" return "${exit_code}" fi } main() { mkdir -p "${BACKUP_ROOT}" local failed=0 for vault in "${VAULTS[@]}"; do backup_vault "${vault}" || (( failed++ )) || true done if (( failed > 0 )); then log ERROR "${failed} vault(s) failed to back up" exit 1 fi log INFO "All backups complete" } main "$@" ``` --- ## JSON ```json { "site": { "name": "Tenebrous Dragon", "url": "https://tenebrous-dragon.example", "theme": "dark", "version": "2026.4" }, "navigation": { "maxDepth": 3, "showTags": true, "collapsedByDefault": false, "separators": ["Dragon Lore", "The World", "Arbiter Tools"] }, "dragons": [ { "name": "Sapphire", "cr": 22, "size": "Ancient", "stats": { "hp": 297, "ac": 20, "str": 27, "dex": 12, "con": 25 }, "habitat": ["Underdark", "Crystal Caverns"], "breath": { "type": "Psychic", "damage": "12d8", "save": "INT DC 21" }, "legendary": true, "lair": null }, { "name": "Bronze", "cr": 15, "size": "Adult", "stats": { "hp": 212, "ac": 18, "str": 25, "dex": 10, "con": 23 }, "habitat": ["Coastal", "Island"], "breath": { "type": "Lightning", "damage": "12d10", "save": "DEX DC 19" }, "legendary": false, "lair": "Sea Cave 39.12N 20.88E" } ], "settings": { "indexBatchSize": 50, "cacheMaxAge": 3600, "features": { "sidebarCollapse": true, "serpentHunt": true, "celestialHeadings": true } } } ``` --- ## YAML ```yaml # Creature frontmatter schema name: Sapphire Dragon aliases: - Great Sapphire - Crystal Wyrm type: Dragon subtype: Gem size: Ancient alignment: Lawful Neutral cr: 22 stats: hp: 297 ac: 20 speed: walk: 40 fly: 80 ability_scores: { str: 27, dex: 12, con: 25, int: 22, wis: 17, cha: 21 } senses: - blindsight 60 ft. - darkvision 120 ft. - truesight 30 ft. languages: - Common - Draconic - Deep Speech - telepathy 120 ft. breath_weapon: name: Psychic Breath type: psychic recharge: "5-6" area: 90-foot cone damage: 12d8 psychic save: ability: INT dc: 21 tags: - Dragon - Gem - Psionic - Δημοσίευση publish: true created: 2026-04-13 last: 2026-04-13 ``` --- ## CSS ```css /* ── Tenebrous Dragon Publish Theme · Core Variables ────────────────────────── */ :root { --color-ocean-deep: #0a1628; --color-aegean: #3d6b8c; --color-teal: #2ab8c8; --color-amber: #e8a84a; --color-crimson: #c94040; --font-text: 'Palatino Linotype', 'Book Antiqua', Palatino, serif; --font-mono: 'Fira Code', 'Cascadia Code', 'Consolas', monospace; --sidebar-width: 16rem; --page-width: clamp(30rem, 82vw, 52rem); } /* ── Component: Sidebar Tab ─────────────────────────────────────────────────── */ .sidebar-close-btn, .sidebar-open-tab { cursor: pointer; color: var(--text-muted); font-size: 0.9rem; padding: 1.35rem 0.55rem; background: var(--background-secondary); border: 1px solid var(--background-modifier-border); transition: color 150ms ease, background-color 150ms ease; } .sidebar-close-btn:hover, .sidebar-open-tab:hover { color: var(--text-normal); background-color: var(--background-modifier-hover); } /* ── Animation: Ship sail ───────────────────────────────────────────────────── */ @keyframes ship-sail { from { left: -24px; } to { left: calc(100% + 4px); } } @media (prefers-reduced-motion: reduce) { .markdown-rendered h1::before, .markdown-rendered h2::before { animation: none; } } @media screen and (max-width: 750px) { :root { --page-width: 100%; --sidebar-width: 0; } } ``` --- ## SQL ```sql -- Dragon bestiary queries with CTEs and window functions WITH dragon_stats AS ( SELECT name, colour, size, cr, hp, habitat, ROW_NUMBER() OVER (PARTITION BY colour ORDER BY cr DESC) AS rank_in_colour FROM creatures WHERE type = 'Dragon' AND published = TRUE ), colour_averages AS ( SELECT colour, ROUND(AVG(cr), 1) AS avg_cr, MAX(hp) AS max_hp, COUNT(*) AS total FROM dragon_stats GROUP BY colour HAVING COUNT(*) >= 2 ) SELECT ds.name, ds.colour, ds.cr, ds.hp, ca.avg_cr, ds.cr - ca.avg_cr AS cr_vs_avg, RANK() OVER (ORDER BY ds.cr DESC) AS global_rank, STRING_AGG(ds.habitat, ', ' ORDER BY ds.habitat) AS habitats FROM dragon_stats ds INNER JOIN colour_averages ca ON ca.colour = ds.colour WHERE ds.rank_in_colour <= 3 GROUP BY ds.name, ds.colour, ds.cr, ds.hp, ca.avg_cr ORDER BY ds.cr DESC, ds.name; -- Update last-seen timestamp UPDATE creatures SET last_seen = CURRENT_TIMESTAMP, sightings = sightings + 1 WHERE name = 'Sapphire' AND type = 'Dragon' RETURNING name, last_seen, sightings; ``` --- ## Haskell ```haskell -- Dragon Bestiary in Haskell -- Exercises: data types, type classes, pattern matching, list comprehensions, -- Maybe/Either, where clauses, guards, higher-order functions module Bestiary ( Dragon(..) , DragonSize(..) , Habitat(..) , mkDragon , challengeRating , habitatFilter , routeSummary ) where import Data.List (intercalate, sortBy) import Data.Maybe (mapMaybe) import Data.Ord (comparing, Down(..)) -- ── Types ──────────────────────────────────────────────────────────────────── data DragonSize = Wyrmling | Young | Adult | Ancient | Greatwyrm deriving (Show, Eq, Ord, Enum, Bounded) data Habitat = Coastal | Underdark | Mountain | Aerial | Aquatic | Volcanic deriving (Show, Eq, Ord, Enum, Bounded) data Dragon = Dragon { dragonName :: String , dragonColour :: String , dragonSize :: DragonSize , dragonHP :: Int , dragonAC :: Int , dragonCR :: Double , dragonHabitat :: [Habitat] } deriving (Show, Eq) -- ── Smart constructor ──────────────────────────────────────────────────────── mkDragon :: String -> String -> DragonSize -> Int -> Int -> [Habitat] -> Either String Dragon mkDragon name colour sz hp ac habitats | null name = Left "Dragon must have a name" | hp <= 0 = Left $ "Invalid HP for " ++ name | ac < 10 || ac > 30 = Left $ "AC out of range for " ++ name | null habitats = Left $ name ++ " must have at least one habitat" | otherwise = Right Dragon { dragonName = name , dragonColour = colour , dragonSize = sz , dragonHP = hp , dragonAC = ac , dragonCR = challengeRating sz hp ac , dragonHabitat = habitats } -- ── Challenge rating heuristic ─────────────────────────────────────────────── challengeRating :: DragonSize -> Int -> Int -> Double challengeRating sz hp ac = base + hpBonus + acBonus where base = fromIntegral (fromEnum sz) * 4.5 + 1.0 hpBonus = fromIntegral hp / 100.0 acBonus = fromIntegral (ac - 15) * 0.25 -- ── Queries ────────────────────────────────────────────────────────────────── habitatFilter :: Habitat -> [Dragon] -> [Dragon] habitatFilter h = filter (elem h . dragonHabitat) topBySize :: DragonSize -> [Dragon] -> [Dragon] topBySize sz = sortBy (comparing (Down . dragonCR)) . filter ((== sz) . dragonSize) routeSummary :: [Dragon] -> String routeSummary [] = "No dragons encountered." routeSummary dragons = intercalate "\n" $ map fmt ranked where ranked = sortBy (comparing (Down . dragonCR)) dragons fmt d = dragonName d ++ " (" ++ dragonColour d ++ ", CR " ++ show (dragonCR d) ++ ")" -- ── Sample data ────────────────────────────────────────────────────────────── bestiary :: [Dragon] bestiary = mapMaybe toMaybe [ mkDragon "Sapphire" "blue" Ancient 297 20 [Underdark] , mkDragon "Bronze" "bronze" Adult 212 18 [Coastal, Aquatic] , mkDragon "Red" "crimson" Ancient 256 19 [Mountain, Volcanic] , mkDragon "Sea Wyrm" "green" Wyrmling 52 14 [Aquatic, Coastal] , mkDragon "" "silver" Young 120 16 [] -- invalid: no name ] where toMaybe (Right d) = Just d toMaybe (Left _) = Nothing ``` --- ## HTML ```html <!DOCTYPE html> <html lang="el" data-theme="dark"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Tenebrous Dragon — Obsidian Publish theme"> <title>Τenebrous Dragon</title> <link rel="stylesheet" href="/publish.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> </head> <body class="theme-dark"> <div class="published-container has-navigation has-outline"> <aside class="site-body-left-column" aria-label="Navigation"> <div class="site-body-left-column-site-logo"> <img src="/attachments/tenebrous-dark-mode.png" alt="Tenebrous Dragon" width="256" height="128" loading="eager"> </div> <nav class="nav-view-outer" aria-label="Site navigation"> <!-- tree items injected by Publish JS --> </nav> </aside> <main class="site-body-center-column"> <article class="publish-renderer markdown-rendered"> <h1>Ζετελκάστεν για Δράκους</h1> <p>Explore the <strong>Ionian Islands</strong> and their <em>mythological</em> inhabitants.</p> <blockquote> <p>The sea is the same as it has been since before men ever went on it in boats.</p> </blockquote> </article> </main> <aside class="site-body-right-column" aria-label="Outline"> <!-- outline injected by Publish JS --> </aside> </div> <script src="/publish.js" defer></script> </body> </html> ```